Update TAPI Topology Service on port change
[transportpce.git] / tapi / src / main / java / org / opendaylight / transportpce / tapi / topology / TapiNetworkModelServiceImpl.java
1 /*
2  * Copyright © 2021 Nokia, 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 package org.opendaylight.transportpce.tapi.topology;
9
10 import java.nio.charset.StandardCharsets;
11 import java.util.ArrayList;
12 import java.util.Collection;
13 import java.util.Collections;
14 import java.util.Comparator;
15 import java.util.HashMap;
16 import java.util.HashSet;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Objects;
20 import java.util.Optional;
21 import java.util.Set;
22 import java.util.UUID;
23 import java.util.concurrent.ExecutionException;
24 import java.util.stream.Collectors;
25 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
26 import org.opendaylight.transportpce.common.network.NetworkTransactionService;
27 import org.opendaylight.transportpce.tapi.R2RTapiLinkDiscovery;
28 import org.opendaylight.transportpce.tapi.TapiStringConstants;
29 import org.opendaylight.transportpce.tapi.utils.TapiLink;
30 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220316.mapping.Mapping;
31 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220316.network.Nodes;
32 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.state.types.rev191129.State;
33 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.types.rev181019.NodeTypes;
34 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.types.rev191129.XpdrNodeTypes;
35 import org.opendaylight.yang.gen.v1.http.org.openroadm.equipment.states.types.rev191129.AdminStates;
36 import org.opendaylight.yang.gen.v1.http.org.openroadm.network.topology.types.rev201211.xpdr.odu.switching.pools.OduSwitchingPools;
37 import org.opendaylight.yang.gen.v1.http.org.openroadm.network.topology.types.rev201211.xpdr.odu.switching.pools.OduSwitchingPoolsBuilder;
38 import org.opendaylight.yang.gen.v1.http.org.openroadm.network.topology.types.rev201211.xpdr.odu.switching.pools.odu.switching.pools.NonBlockingList;
39 import org.opendaylight.yang.gen.v1.http.org.openroadm.network.topology.types.rev201211.xpdr.odu.switching.pools.odu.switching.pools.NonBlockingListBuilder;
40 import org.opendaylight.yang.gen.v1.http.org.openroadm.network.topology.types.rev201211.xpdr.odu.switching.pools.odu.switching.pools.NonBlockingListKey;
41 import org.opendaylight.yang.gen.v1.http.org.openroadm.network.types.rev211210.OpenroadmNodeType;
42 import org.opendaylight.yang.gen.v1.http.org.openroadm.network.types.rev211210.xpdr.tp.supported.interfaces.SupportedInterfaceCapability;
43 import org.opendaylight.yang.gen.v1.http.org.openroadm.network.types.rev211210.xpdr.tp.supported.interfaces.SupportedInterfaceCapabilityBuilder;
44 import org.opendaylight.yang.gen.v1.http.org.openroadm.network.types.rev211210.xpdr.tp.supported.interfaces.SupportedInterfaceCapabilityKey;
45 import org.opendaylight.yang.gen.v1.http.org.openroadm.port.types.rev201211.SupportedIfCapability;
46 import org.opendaylight.yang.gen.v1.http.org.openroadm.switching.pool.types.rev191129.SwitchingPoolTypes;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.NodeId;
48 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.topology.rev180226.TpId;
49 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.AdministrativeState;
50 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.Context;
51 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.ContextBuilder;
52 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.LAYERPROTOCOLQUALIFIER;
53 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.LayerProtocolName;
54 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.LifecycleState;
55 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.OperationalState;
56 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.PortDirection;
57 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.PortRole;
58 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.TerminationDirection;
59 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.TerminationState;
60 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.Uuid;
61 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.capacity.pac.AvailableCapacityBuilder;
62 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.capacity.pac.TotalPotentialCapacityBuilder;
63 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.global._class.Name;
64 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.global._class.NameBuilder;
65 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.global._class.NameKey;
66 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.tapi.context.ServiceInterfacePoint;
67 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.tapi.context.ServiceInterfacePointBuilder;
68 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.tapi.context.ServiceInterfacePointKey;
69 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.Connection;
70 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.ConnectionBuilder;
71 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.ConnectionKey;
72 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.ConnectivityService;
73 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.ConnectivityServiceBuilder;
74 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.ConnectivityServiceKey;
75 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.service.EndPoint;
76 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.service.EndPointKey;
77 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContext;
78 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.dsr.rev181210.DIGITALSIGNALTYPE100GigE;
79 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.dsr.rev181210.DIGITALSIGNALTYPE10GigELAN;
80 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.dsr.rev181210.DIGITALSIGNALTYPEGigE;
81 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.odu.rev181210.ODUTYPEODU0;
82 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.odu.rev181210.ODUTYPEODU2;
83 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.odu.rev181210.ODUTYPEODU2E;
84 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.odu.rev181210.ODUTYPEODU4;
85 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.photonic.media.rev181210.PHOTONICLAYERQUALIFIEROMS;
86 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.photonic.media.rev181210.PHOTONICLAYERQUALIFIEROTSi;
87 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.Context1;
88 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.ForwardingRule;
89 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.NodeEdgePointRef;
90 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.RuleType;
91 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.context.TopologyContext;
92 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.node.NodeRuleGroup;
93 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.node.NodeRuleGroupBuilder;
94 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.node.NodeRuleGroupKey;
95 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.node.OwnedNodeEdgePoint;
96 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.node.OwnedNodeEdgePointBuilder;
97 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.node.OwnedNodeEdgePointKey;
98 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.node.edge.point.MappedServiceInterfacePoint;
99 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.node.edge.point.MappedServiceInterfacePointBuilder;
100 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.node.edge.point.MappedServiceInterfacePointKey;
101 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.node.rule.group.NodeEdgePoint;
102 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.node.rule.group.NodeEdgePointBuilder;
103 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.node.rule.group.NodeEdgePointKey;
104 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.node.rule.group.Rule;
105 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.node.rule.group.RuleBuilder;
106 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.node.rule.group.RuleKey;
107 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.risk.parameter.pac.RiskCharacteristic;
108 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.risk.parameter.pac.RiskCharacteristicBuilder;
109 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.Link;
110 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.LinkBuilder;
111 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.LinkKey;
112 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.Node;
113 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.NodeBuilder;
114 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.NodeKey;
115 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.context.Topology;
116 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.context.TopologyBuilder;
117 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.context.TopologyKey;
118 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.transfer.cost.pac.CostCharacteristic;
119 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.transfer.cost.pac.CostCharacteristicBuilder;
120 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.transfer.timing.pac.LatencyCharacteristic;
121 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.transfer.timing.pac.LatencyCharacteristicBuilder;
122 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
123 import org.opendaylight.yangtools.yang.common.Uint16;
124 import org.opendaylight.yangtools.yang.common.Uint32;
125 import org.slf4j.Logger;
126 import org.slf4j.LoggerFactory;
127
128 public class TapiNetworkModelServiceImpl implements TapiNetworkModelService {
129
130     private static final Logger LOG = LoggerFactory.getLogger(TapiNetworkModelServiceImpl.class);
131     private final Uuid tapiTopoUuid = new Uuid(UUID.nameUUIDFromBytes(TapiStringConstants.T0_FULL_MULTILAYER
132             .getBytes(StandardCharsets.UTF_8)).toString());
133     private final NetworkTransactionService networkTransactionService;
134     private Map<ServiceInterfacePointKey, ServiceInterfacePoint> sipMap;
135     private final R2RTapiLinkDiscovery linkDiscovery;
136     private final TapiLink tapiLink;
137
138     public TapiNetworkModelServiceImpl(final R2RTapiLinkDiscovery linkDiscovery,
139                                        NetworkTransactionService networkTransactionService, TapiLink tapiLink) {
140         this.networkTransactionService = networkTransactionService;
141         this.sipMap = new HashMap<>();
142         this.linkDiscovery = linkDiscovery;
143         this.tapiLink = tapiLink;
144     }
145
146     @Override
147     public void createTapiNode(String orNodeId, int orNodeVersion, Nodes node) {
148         // TODO -> Implementation with PortMappingListener
149         // check if port mapping exists or not...
150         if (node.getMapping() == null) {
151             LOG.warn("Could not generate port mapping for {} skipping network model creation", orNodeId);
152             return;
153         }
154         this.sipMap.clear();
155         LOG.info("Mapping of node {}: {}", orNodeId, node.getMapping().values());
156
157         // check type of device, check version and create node mapping
158         if (NodeTypes.Rdm.getIntValue() == node.getNodeInfo().getNodeType().getIntValue()) {
159             // ROADM device
160             // transform flat mapping list to per degree and per srg mapping lists
161             Map<String, List<Mapping>> mapDeg = new HashMap<>();
162             Map<String, List<Mapping>> mapSrg = new HashMap<>();
163             List<Mapping> mappingList = new ArrayList<>(node.nonnullMapping().values());
164             mappingList.sort(Comparator.comparing(Mapping::getLogicalConnectionPoint));
165
166             List<String> nodeShardList = getRoadmNodelist(mappingList);
167
168             // populate degree and srg LCP map
169             for (String str : nodeShardList) {
170                 List<Mapping> interList = mappingList.stream().filter(x -> x.getLogicalConnectionPoint().contains(str))
171                         .collect(Collectors.toList());
172                 if (str.contains("DEG")) {
173                     mapDeg.put(str, interList);
174                 } else if (str.contains("SRG")) {
175                     mapSrg.put(str, interList);
176                 } else {
177                     LOG.error("unknown element");
178                 }
179             }
180             // Transform LCPs into ONEP
181             Map<OwnedNodeEdgePointKey, OwnedNodeEdgePoint> onepMap =
182                 new HashMap<>(transformDegToOnep(orNodeId, mapDeg));
183             onepMap.putAll(transformSrgToOnep(orNodeId, mapSrg));
184
185             // create tapi Node
186             Node roadmNode = createRoadmTapiNode(orNodeId, onepMap);
187             mergeNodeinTopology(Map.of(roadmNode.key(), roadmNode));
188             mergeSipsinContext(this.sipMap);
189             // TODO add states corresponding to device config -> based on mapping.
190             //  This should be possible after Gilles work is merged
191
192             // rdm to rdm link creation if neighbour roadm is mounted
193             LOG.info("checking if neighbor roadm exists");
194             Map<LinkKey, Link> rdm2rdmLinks = this.linkDiscovery.readLLDP(new NodeId(orNodeId), orNodeVersion,
195                 this.tapiTopoUuid);
196             if (!rdm2rdmLinks.isEmpty()) {
197                 mergeLinkinTopology(rdm2rdmLinks);
198             }
199             LOG.info("TAPI node for or node {} successfully merged", orNodeId);
200         } else if (NodeTypes.Xpdr.getIntValue() ==  node.getNodeInfo().getNodeType().getIntValue()) {
201             List<Mapping> networkMappings = node.nonnullMapping().values()
202                     .stream().filter(k -> k.getLogicalConnectionPoint()
203                             .contains("NETWORK")).collect(Collectors.toList());
204             Map<Integer, String> xpdrMap = new HashMap<>();
205             for (Mapping mapping : networkMappings) {
206                 Integer xpdrNb = Integer.parseInt(mapping.getLogicalConnectionPoint().split("XPDR")[1].split("-")[0]);
207                 String nodeId = node.getNodeId() + TapiStringConstants.XPDR + xpdrNb;
208                 if (!xpdrMap.containsKey(xpdrNb)) {
209                     List<Mapping> xpdrNetMaps = node.nonnullMapping().values()
210                         .stream().filter(k -> k.getLogicalConnectionPoint()
211                             .contains("XPDR" + xpdrNb + TapiStringConstants.NETWORK)).collect(Collectors.toList());
212                     List<Mapping> xpdrClMaps = node.nonnullMapping().values()
213                         .stream().filter(k -> k.getLogicalConnectionPoint()
214                             .contains("XPDR" + xpdrNb + TapiStringConstants.CLIENT)).collect(Collectors.toList());
215                     xpdrMap.put(xpdrNb, node.getNodeId());
216
217                     // create switching pool
218                     OduSwitchingPools oorOduSwitchingPool = createSwitchPoolForXpdr(
219                         mapping.getXponderType().getIntValue(), xpdrClMaps, xpdrNetMaps, xpdrNb);
220
221                     // node transformation
222                     Map<NodeKey, Node> nodeMap = new HashMap<>(transformXpdrToTapiNode(
223                         nodeId, xpdrClMaps, xpdrNetMaps, mapping.getXponderType(), oorOduSwitchingPool));
224                     // add nodes and sips to tapi context
225                     mergeNodeinTopology(nodeMap);
226                     mergeSipsinContext(this.sipMap);
227                 }
228             }
229             LOG.info("TAPI node for or node {} successfully merged", orNodeId);
230         }
231         // Device not managed yet
232     }
233
234     @Override
235     public void updateTapiTopology(String nodeId, Mapping mapping) {
236         List<Uuid> uuids = getChangedNodeUuids(nodeId, mapping);
237
238         List<Uuid> changedOneps = updateNeps(mapping, uuids);
239         updateLinks(changedOneps, mapping);
240
241         LOG.info("Updated TAPI topology successfully.");
242     }
243
244     private void updateLinks(List<Uuid> changedOneps, Mapping mapping) {
245         try {
246             InstanceIdentifier<Topology> topoIID = InstanceIdentifier.builder(Context.class)
247                     .augmentation(Context1.class).child(TopologyContext.class)
248                     .child(Topology.class, new TopologyKey(tapiTopoUuid))
249                     .build();
250             Optional<Topology> optTopology = this.networkTransactionService
251                     .read(LogicalDatastoreType.OPERATIONAL, topoIID).get();
252             if (optTopology.isEmpty()) {
253                 LOG.error("Could not update TAPI links");
254                 return;
255             }
256             Map<LinkKey, Link> links = optTopology.get().getLink();
257             if (links != null) {
258                 for (Link link : links.values()) {
259                     List<Uuid> linkNeps = Objects.requireNonNull(link.getNodeEdgePoint()).values().stream()
260                             .map(NodeEdgePointRef::getNodeEdgePointUuid).collect(Collectors.toList());
261                     if (!Collections.disjoint(changedOneps, linkNeps)) {
262                         InstanceIdentifier<Link> linkIID = InstanceIdentifier.builder(Context.class)
263                                 .augmentation(Context1.class).child(TopologyContext.class)
264                                 .child(Topology.class, new TopologyKey(tapiTopoUuid))
265                                 .child(Link.class, new LinkKey(link.getUuid())).build();
266                         Link linkblr = new LinkBuilder().setUuid(link.getUuid())
267                                 .setAdministrativeState(transformAdminState(mapping.getPortAdminState()))
268                                 .setOperationalState(transformOperState(mapping.getPortOperState())).build();
269                         this.networkTransactionService.merge(LogicalDatastoreType.OPERATIONAL, linkIID, linkblr);
270                     }
271                 }
272             }
273             this.networkTransactionService.commit().get();
274         } catch (InterruptedException | ExecutionException e) {
275             LOG.error("Could not update TAPI links");
276         }
277     }
278
279     private List<Uuid> updateNeps(Mapping mapping, List<Uuid> uuids) {
280         List<Uuid> changedOneps = new ArrayList<>();
281         for (Uuid nodeUuid : uuids) {
282             try {
283                 InstanceIdentifier<Node> nodeIID = InstanceIdentifier.builder(Context.class)
284                         .augmentation(Context1.class).child(TopologyContext.class)
285                         .child(Topology.class, new TopologyKey(tapiTopoUuid)).child(Node.class, new NodeKey(nodeUuid))
286                         .build();
287                 Optional<Node> optionalNode = this.networkTransactionService.read(
288                         LogicalDatastoreType.OPERATIONAL, nodeIID).get();
289                 if (optionalNode.isPresent()) {
290                     Node node = optionalNode.get();
291                     List<OwnedNodeEdgePoint> oneps = node.getOwnedNodeEdgePoint().values().stream()
292                             .filter(onep -> ((Name) onep.getName().values().toArray()[0]).getValue()
293                                     .contains(mapping.getLogicalConnectionPoint())).collect(Collectors.toList());
294                     for (OwnedNodeEdgePoint onep : oneps) {
295                         changedOneps.add(onep.getUuid());
296                         updateSips(mapping, onep);
297                         InstanceIdentifier<OwnedNodeEdgePoint> onepIID = InstanceIdentifier.builder(Context.class)
298                                 .augmentation(Context1.class).child(TopologyContext.class)
299                                 .child(Topology.class, new TopologyKey(tapiTopoUuid))
300                                 .child(Node.class, new NodeKey(nodeUuid))
301                                 .child(OwnedNodeEdgePoint.class, new OwnedNodeEdgePointKey(onep.getUuid()))
302                                 .build();
303                         OwnedNodeEdgePoint onepblr = new OwnedNodeEdgePointBuilder().setUuid(onep.getUuid())
304                                 .setAdministrativeState(transformAdminState(mapping.getPortAdminState()))
305                                 .setOperationalState(transformOperState(mapping.getPortOperState())).build();
306                         this.networkTransactionService.merge(LogicalDatastoreType.OPERATIONAL, onepIID, onepblr);
307                     }
308                     this.networkTransactionService.commit().get();
309                 }
310             } catch (InterruptedException | ExecutionException e) {
311                 LOG.error("Could not update TAPI NEP");
312             }
313         }
314         return changedOneps;
315     }
316
317     private List<Uuid> getChangedNodeUuids(String nodeId, Mapping mapping) {
318         List<Uuid> uuids = new ArrayList<>();
319         if (nodeId.contains("ROADM")) {
320             uuids.add(new Uuid(UUID.nameUUIDFromBytes((String.join("+", nodeId, TapiStringConstants.PHTNC_MEDIA))
321                     .getBytes(StandardCharsets.UTF_8)).toString()));
322         } else if (nodeId.contains("PDR") && mapping.getLogicalConnectionPoint().contains("CLIENT")) {
323             int xpdrNb = Integer.parseInt(mapping.getLogicalConnectionPoint().split("XPDR")[1].split("-")[0]);
324             String xpdrNodeId = nodeId + TapiStringConstants.XPDR + xpdrNb;
325             uuids.add(new Uuid(UUID.nameUUIDFromBytes((String.join("+", xpdrNodeId, TapiStringConstants.DSR))
326                     .getBytes(StandardCharsets.UTF_8)).toString()));
327         } else if (nodeId.contains("PDR") && mapping.getLogicalConnectionPoint().contains("NETWORK")) {
328             int xpdrNb = Integer.parseInt(mapping.getLogicalConnectionPoint().split("XPDR")[1].split("-")[0]);
329             String xpdrNodeId = nodeId + TapiStringConstants.XPDR + xpdrNb;
330             uuids.add(new Uuid(UUID.nameUUIDFromBytes((String.join("+", xpdrNodeId, TapiStringConstants.DSR))
331                     .getBytes(StandardCharsets.UTF_8)).toString()));
332             uuids.add(new Uuid(UUID.nameUUIDFromBytes((String.join("+", xpdrNodeId, TapiStringConstants.OTSI))
333                     .getBytes(StandardCharsets.UTF_8)).toString()));
334         } else {
335             LOG.error("Updating this device is currently not supported");
336             return uuids;
337         }
338         return uuids;
339     }
340
341     private void updateSips(Mapping mapping, OwnedNodeEdgePoint onep) {
342         if (onep.getMappedServiceInterfacePoint() == null
343                 || onep.getMappedServiceInterfacePoint().size() == 0) {
344             return;
345         }
346         for (MappedServiceInterfacePoint msip : onep.getMappedServiceInterfacePoint().values()) {
347             InstanceIdentifier<ServiceInterfacePoint> sipIID = InstanceIdentifier
348                     .builder(Context.class)
349                     .child(ServiceInterfacePoint.class,
350                             new ServiceInterfacePointKey(msip.getServiceInterfacePointUuid()))
351                     .build();
352             ServiceInterfacePoint sipblr = new ServiceInterfacePointBuilder()
353                     .setUuid(msip.getServiceInterfacePointUuid())
354                     .setAdministrativeState(transformAdminState(mapping.getPortAdminState()))
355                     .setOperationalState(transformOperState(mapping.getPortOperState())).build();
356             this.networkTransactionService.merge(LogicalDatastoreType.OPERATIONAL, sipIID, sipblr);
357         }
358
359     }
360
361     private Map<NodeKey, Node> transformXpdrToTapiNode(String nodeId, List<Mapping> xpdrClMaps,
362                                                        List<Mapping> xpdrNetMaps, XpdrNodeTypes xponderType,
363                                                        OduSwitchingPools oorOduSwitchingPool) {
364         Map<NodeKey, Node> nodeMap = new HashMap<>();
365         LOG.info("creation of a DSR/ODU node for {}", nodeId);
366         Uuid nodeUuidDsr = new Uuid(UUID.nameUUIDFromBytes((String.join("+", nodeId, TapiStringConstants.DSR))
367             .getBytes(StandardCharsets.UTF_8)).toString());
368         Name nameDsr = new NameBuilder().setValueName("dsr/odu node name").setValue(
369             String.join("+", nodeId, TapiStringConstants.DSR)).build();
370         Name nameNodeType = new NameBuilder().setValueName("Node Type")
371             .setValue(getNodeType(xponderType)).build();
372         Set<LayerProtocolName> dsrLayerProtocols = Set.of(LayerProtocolName.DSR, LayerProtocolName.ODU);
373         Node dsrNode = createTapiXpdrNode(Map.of(nameDsr.key(), nameDsr, nameNodeType.key(), nameNodeType),
374             dsrLayerProtocols, nodeId, nodeUuidDsr, xpdrClMaps, xpdrNetMaps, xponderType, oorOduSwitchingPool);
375
376         nodeMap.put(dsrNode.key(), dsrNode);
377
378         // node creation [otsi]
379         LOG.info("creation of an OTSi node for {}", nodeId);
380         Uuid nodeUuidOtsi = new Uuid(UUID.nameUUIDFromBytes((String.join("+", nodeId, TapiStringConstants.OTSI))
381             .getBytes(StandardCharsets.UTF_8)).toString());
382         Name nameOtsi =  new NameBuilder().setValueName("otsi node name").setValue(
383             String.join("+", nodeId, TapiStringConstants.OTSI)).build();
384         Set<LayerProtocolName> otsiLayerProtocols = Set.of(LayerProtocolName.PHOTONICMEDIA);
385         Node otsiNode = createTapiXpdrNode(Map.of(nameOtsi.key(), nameOtsi, nameNodeType.key(), nameNodeType),
386             otsiLayerProtocols, nodeId, nodeUuidOtsi, xpdrClMaps, xpdrNetMaps, xponderType, null);
387
388         nodeMap.put(otsiNode.key(), otsiNode);
389
390         // transitional link cration between network nep of DSR/ODU node and iNep of otsi node
391         LOG.info("creation of transitional links between DSR/ODU and OTSi nodes");
392         Map<LinkKey, Link> linkMap = createTapiTransitionalLinks(nodeId, xpdrNetMaps);
393         mergeLinkinTopology(linkMap);
394
395         return nodeMap;
396     }
397
398     private OduSwitchingPools createSwitchPoolForXpdr(int xpdrType, List<Mapping> xpdrClMaps, List<Mapping> xpdrNetMaps,
399                                                       Integer xpdrNb) {
400         // todo: are switching pool correct here??
401         switch (xpdrType) {
402             case 1:
403                 // Tpdr
404                 return createTpdrSwitchPool(xpdrNetMaps);
405             case 2:
406                 // Mux
407                 return createMuxSwitchPool(xpdrClMaps, xpdrNetMaps, xpdrNb);
408             case 3:
409                 // Switch
410                 return createSwtchSwitchPool(xpdrClMaps, xpdrNetMaps, xpdrNb);
411             default:
412                 LOG.warn("Xpdr type {} not supported", xpdrType);
413         }
414         return null;
415     }
416
417     private Map<OwnedNodeEdgePointKey, OwnedNodeEdgePoint> transformSrgToOnep(String orNodeId,
418                                                                               Map<String, List<Mapping>> mapSrg) {
419         Map<OwnedNodeEdgePointKey, OwnedNodeEdgePoint> onepMap = new HashMap<>();
420         for (Map.Entry<String, List<Mapping>> entry : mapSrg.entrySet()) {
421             // For each srg node. Loop through the LCPs and create neps and sips for PP
422             for (Mapping m:entry.getValue()) {
423                 if (!m.getLogicalConnectionPoint().contains("PP")) {
424                     LOG.info("LCP {} is not an external TP of SRG node", m.getLogicalConnectionPoint());
425                     continue;
426                 }
427                 Map<OwnedNodeEdgePointKey, OwnedNodeEdgePoint> srgNeps =
428                     createRoadmNeps(orNodeId, m.getLogicalConnectionPoint(), true,
429                             transformOperState(m.getPortOperState()), transformAdminState(m.getPortAdminState()));
430                 onepMap.putAll(srgNeps);
431             }
432         }
433         return onepMap;
434     }
435
436     private Map<OwnedNodeEdgePointKey, OwnedNodeEdgePoint> transformDegToOnep(String orNodeId,
437                                                                               Map<String, List<Mapping>> mapDeg) {
438         Map<OwnedNodeEdgePointKey, OwnedNodeEdgePoint> onepMap = new HashMap<>();
439         for (Map.Entry<String, List<Mapping>> entry : mapDeg.entrySet()) {
440             // For each degree node. Loop through the LCPs and create neps and sips for TTP
441             for (Mapping m:entry.getValue()) {
442                 if (!m.getLogicalConnectionPoint().contains("TTP")) {
443                     LOG.info("LCP {} is not an external TP of DEGREE node", m.getLogicalConnectionPoint());
444                     continue;
445                 }
446                 Map<OwnedNodeEdgePointKey, OwnedNodeEdgePoint> degNeps =
447                     createRoadmNeps(orNodeId, m.getLogicalConnectionPoint(), false,
448                             transformOperState(m.getPortOperState()), transformAdminState(m.getPortAdminState()));
449                 onepMap.putAll(degNeps);
450             }
451         }
452         return onepMap;
453     }
454
455     private List<String> getRoadmNodelist(List<Mapping> mappingList) {
456         List<String> nodeShardList = new ArrayList<>();
457         for (Mapping mapping : mappingList) {
458             // TODO -> maybe we need to check the id based on the version
459             String str = mapping.getLogicalConnectionPoint().split("-")[0];
460             LOG.info("LCP = {}", str);
461             if (!nodeShardList.contains(str)) {
462                 nodeShardList.add(str);
463             }
464         }
465         return nodeShardList;
466     }
467
468     @Override
469     public void deleteTapinode(String nodeId) {
470         // TODO: check for null objects
471         // Check if it is ROADM or XPDR --> create the uuids of the node and delete from topology the node.
472         // This will delete NEPs. Then check for links that have this node and delete them.
473         // Then check SIPs and delete them. Then services and connections with SIPs and put them to another state.
474         LOG.info("Deleting node {} from TAPI topology", nodeId);
475         InstanceIdentifier<Topology> topologyIID = InstanceIdentifier.builder(Context.class)
476                 .augmentation(Context1.class).child(TopologyContext.class).child(Topology.class,
477                         new TopologyKey(tapiTopoUuid)).build();
478         Topology topology = null;
479         try {
480             Optional<Topology> optTopology =
481                     this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL, topologyIID).get();
482             if (!optTopology.isPresent()) {
483                 LOG.error("No topology object present. Error deleting node {}", nodeId);
484                 return;
485             }
486             topology = optTopology.get();
487         } catch (InterruptedException | ExecutionException e) {
488             LOG.error("Couldnt read tapi topology from datastore", e);
489         }
490         if (topology == null) {
491             LOG.error("Topology is null, nothing to delete");
492             return;
493         }
494         if (topology.getNode() == null) {
495             LOG.error("No nodes in topology");
496             return;
497         }
498         if (nodeId.contains("ROADM")) {
499             // Node is in photonic media layer and UUID can be built from nodeId + PHTN_MEDIA
500             Uuid nodeUuid = new Uuid(UUID.nameUUIDFromBytes((String.join("+", nodeId,
501                 TapiStringConstants.PHTNC_MEDIA)).getBytes(StandardCharsets.UTF_8)).toString());
502             deleteNodeFromTopo(nodeUuid);
503         }
504         if (nodeId.contains("XPDR") || nodeId.contains("SPDR") || nodeId.contains("MXPDR")) {
505             // Node is either XPDR, MXPDR or SPDR. Retrieve nodes from topology and check names
506             for (Node tapiNode:topology.getNode().values()) {
507                 if (tapiNode.getName().values().stream().anyMatch(name -> name.getValue().contains(nodeId))) {
508                     // Found node we need to delete
509                     deleteNodeFromTopo(tapiNode.getUuid());
510                 }
511             }
512         }
513         // Delete links of topology
514         Map<LinkKey, Link> linkMap = topology.getLink();
515         if (linkMap != null) {
516             for (Link link:linkMap.values()) {
517                 if (link.getName().values().stream().anyMatch(name -> name.getValue().contains(nodeId))) {
518                     deleteLinkFromTopo(link.getUuid());
519                 }
520             }
521         }
522         // Delete sips of sip map
523         InstanceIdentifier<Context> contextIID = InstanceIdentifier.builder(Context.class).build();
524         Context context = null;
525         try {
526             Optional<Context> optContext = this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL,
527                     contextIID).get();
528             if (!optContext.isPresent()) {
529                 LOG.error("No context object present in datastore.");
530                 return;
531             }
532             context = optContext.get();
533         } catch (InterruptedException | ExecutionException e) {
534             LOG.error("Couldnt read tapi context from datastore", e);
535         }
536         if (context == null) {
537             LOG.error("Context is null, nothing to delete");
538             return;
539         }
540         Map<ServiceInterfacePointKey, ServiceInterfacePoint> sips = context.getServiceInterfacePoint();
541         if (sips != null) {
542             for (ServiceInterfacePoint sip:sips.values()) {
543                 if (sip.getName().values().stream().anyMatch(name -> name.getValue().contains(nodeId))) {
544                     // Update state of services that have this sip as an endpoint and also connections
545                     updateConnectivityServicesState(sip.getUuid(), nodeId);
546                     deleteSipFromTopo(sip.getUuid());
547                 }
548             }
549         }
550     }
551
552     private Node createTapiXpdrNode(Map<NameKey, Name> nameMap, Set<LayerProtocolName> layerProtocols,
553                                     String nodeId, Uuid nodeUuid, List<Mapping> xpdrClMaps, List<Mapping> xpdrNetMaps,
554                                     XpdrNodeTypes xponderType, OduSwitchingPools oorOduSwitchingPool) {
555         Map<OwnedNodeEdgePointKey, OwnedNodeEdgePoint> onepl = new HashMap<>();
556         Map<NodeRuleGroupKey, NodeRuleGroup> nodeRuleGroupList = new HashMap<>();
557         Map<RuleKey, Rule> ruleList = new HashMap<>();
558         Rule rule = new RuleBuilder()
559                 .setLocalId("forward")
560                 .setForwardingRule(ForwardingRule.MAYFORWARDACROSSGROUP)
561                 .setRuleType(RuleType.FORWARDING)
562                 .build();
563         ruleList.put(rule.key(), rule);
564         if (layerProtocols.contains(LayerProtocolName.DSR)) {
565             // neps for dsr/odu layer
566             Map<OwnedNodeEdgePointKey, OwnedNodeEdgePoint> dsroduNeps =
567                     createXpdrDsrOduNeps(nodeId, xpdrClMaps, xpdrNetMaps, xponderType);
568             onepl.putAll(dsroduNeps);
569             nodeRuleGroupList = createNodeRuleGroupForDsrNode(nodeId, oorOduSwitchingPool, ruleList, onepl);
570         } else if (layerProtocols.contains(LayerProtocolName.PHOTONICMEDIA)) {
571             // neps for photonic layer
572             Map<OwnedNodeEdgePointKey, OwnedNodeEdgePoint> phtmdNeps =
573                     createXpdrPhtnMdNeps(nodeId, xpdrNetMaps);
574             onepl.putAll(phtmdNeps);
575             nodeRuleGroupList = createNodeRuleGroupForOtsiNode(nodeId, xpdrNetMaps, ruleList);
576         } else {
577             LOG.error("Undefined LayerProtocolName for {} node {}", nameMap.get(nameMap.keySet().iterator().next())
578                     .getValueName(), nameMap.get(nameMap.keySet().iterator().next()).getValue());
579         }
580         // Empty random creation of mandatory fields for avoiding errors....
581         CostCharacteristic costCharacteristic = new CostCharacteristicBuilder()
582             .setCostAlgorithm("Restricted Shortest Path - RSP")
583             .setCostName("HOP_COUNT")
584             .setCostValue(TapiStringConstants.COST_HOP_VALUE)
585             .build();
586         LatencyCharacteristic latencyCharacteristic = new LatencyCharacteristicBuilder()
587             .setFixedLatencyCharacteristic(TapiStringConstants.FIXED_LATENCY_VALUE)
588             .setQueingLatencyCharacteristic(TapiStringConstants.QUEING_LATENCY_VALUE)
589             .setJitterCharacteristic(TapiStringConstants.JITTER_VALUE)
590             .setWanderCharacteristic(TapiStringConstants.WANDER_VALUE)
591             .setTrafficPropertyName("FIXED_LATENCY")
592             .build();
593         return new NodeBuilder()
594             .setUuid(nodeUuid)
595             .setName(nameMap)
596             .setLayerProtocolName(layerProtocols)
597             .setAdministrativeState(AdministrativeState.UNLOCKED)
598             .setOperationalState(OperationalState.ENABLED)
599             .setLifecycleState(LifecycleState.INSTALLED)
600             .setOwnedNodeEdgePoint(onepl)
601             .setNodeRuleGroup(nodeRuleGroupList)
602             .setCostCharacteristic(Map.of(costCharacteristic.key(), costCharacteristic))
603             .setLatencyCharacteristic(Map.of(latencyCharacteristic.key(), latencyCharacteristic))
604             .setErrorCharacteristic("error")
605             .setLossCharacteristic("loss")
606             .setRepeatDeliveryCharacteristic("repeat delivery")
607             .setDeliveryOrderCharacteristic("delivery order")
608             .setUnavailableTimeCharacteristic("unavailable time")
609             .setServerIntegrityProcessCharacteristic("server integrity process")
610             .build();
611     }
612
613     private Map<OwnedNodeEdgePointKey, OwnedNodeEdgePoint> createXpdrPhtnMdNeps(String nodeId,
614                                                                                 List<Mapping> xpdrNetMaps) {
615         Map<OwnedNodeEdgePointKey, OwnedNodeEdgePoint> onepl = new HashMap<>();
616
617         // iNep creation on otsi node
618         for (int i = 0; i < xpdrNetMaps.size(); i++) {
619             Uuid nepUuid1 = new Uuid(UUID.nameUUIDFromBytes(
620                 (String.join("+", nodeId, TapiStringConstants.I_OTSI,
621                     xpdrNetMaps.get(i).getLogicalConnectionPoint())).getBytes(StandardCharsets.UTF_8)).toString());
622             Name onedName = new NameBuilder()
623                 .setValueName("iNodeEdgePoint")
624                 .setValue(String.join("+", nodeId, TapiStringConstants.I_OTSI,
625                     xpdrNetMaps.get(i).getLogicalConnectionPoint()))
626                 .build();
627
628             List<Class<? extends SupportedIfCapability>> newSupIfCapList =
629                     new ArrayList<>(xpdrNetMaps.get(i).getSupportedInterfaceCapability());
630
631             OwnedNodeEdgePoint onep = createNep(nepUuid1, xpdrNetMaps.get(i).getLogicalConnectionPoint(),
632                 Map.of(onedName.key(), onedName), LayerProtocolName.PHOTONICMEDIA, LayerProtocolName.PHOTONICMEDIA,
633                 true, String.join("+", nodeId, TapiStringConstants.I_OTSI), newSupIfCapList,
634                 transformOperState(xpdrNetMaps.get(i).getPortOperState()),
635                 transformAdminState(xpdrNetMaps.get(i).getPortAdminState()));
636             onepl.put(onep.key(), onep);
637         }
638         // eNep creation on otsi node
639         for (int i = 0; i < xpdrNetMaps.size(); i++) {
640             Uuid nepUuid2 = new Uuid(UUID.nameUUIDFromBytes(
641                 (String.join("+", nodeId, TapiStringConstants.E_OTSI,
642                     xpdrNetMaps.get(i).getLogicalConnectionPoint())).getBytes(StandardCharsets.UTF_8)).toString());
643             Name onedName = new NameBuilder()
644                 .setValueName("eNodeEdgePoint")
645                 .setValue(String.join("+", nodeId, TapiStringConstants.E_OTSI,
646                     xpdrNetMaps.get(i).getLogicalConnectionPoint()))
647                 .build();
648
649             List<Class<? extends SupportedIfCapability>> newSupIfCapList =
650                 new ArrayList<>(xpdrNetMaps.get(i).getSupportedInterfaceCapability());
651
652             OwnedNodeEdgePoint onep = createNep(nepUuid2, xpdrNetMaps.get(i).getLogicalConnectionPoint(),
653                 Map.of(onedName.key(), onedName), LayerProtocolName.PHOTONICMEDIA, LayerProtocolName.PHOTONICMEDIA,
654                 false, String.join("+", nodeId, TapiStringConstants.E_OTSI), newSupIfCapList,
655                 transformOperState(xpdrNetMaps.get(i).getPortOperState()),
656                 transformAdminState(xpdrNetMaps.get(i).getPortAdminState()));
657             onepl.put(onep.key(), onep);
658         }
659         // Photonic Media Nep creation on otsi node
660         for (int i = 0; i < xpdrNetMaps.size(); i++) {
661             Uuid nepUuid3 = new Uuid(UUID.nameUUIDFromBytes(
662                 (String.join("+", nodeId, TapiStringConstants.PHTNC_MEDIA,
663                     xpdrNetMaps.get(i).getLogicalConnectionPoint())).getBytes(StandardCharsets.UTF_8)).toString());
664             Name onedName = new NameBuilder()
665                 .setValueName("PhotMedNodeEdgePoint")
666                 .setValue(String.join("+", nodeId, TapiStringConstants.PHTNC_MEDIA,
667                     xpdrNetMaps.get(i).getLogicalConnectionPoint()))
668                 .build();
669
670             List<Class<? extends SupportedIfCapability>> newSupIfCapList =
671                     new ArrayList<>(xpdrNetMaps.get(i).getSupportedInterfaceCapability());
672
673             OwnedNodeEdgePoint onep = createNep(nepUuid3, xpdrNetMaps.get(i).getLogicalConnectionPoint(),
674                 Map.of(onedName.key(), onedName), LayerProtocolName.PHOTONICMEDIA, LayerProtocolName.PHOTONICMEDIA,
675                 false, String.join("+", nodeId, TapiStringConstants.PHTNC_MEDIA), newSupIfCapList,
676                 transformOperState(xpdrNetMaps.get(i).getPortOperState()),
677                 transformAdminState(xpdrNetMaps.get(i).getPortAdminState()));
678             onepl.put(onep.key(), onep);
679         }
680         return onepl;
681     }
682
683     private Map<OwnedNodeEdgePointKey, OwnedNodeEdgePoint> createXpdrDsrOduNeps(String nodeId, List<Mapping> xpdrClMaps,
684                                                                                 List<Mapping> xpdrNetMaps,
685                                                                                 XpdrNodeTypes xponderType) {
686         Map<OwnedNodeEdgePointKey, OwnedNodeEdgePoint> onepl = new HashMap<>();
687         // client nep creation on DSR node
688         for (int i = 0; i < xpdrClMaps.size(); i++) {
689             LOG.info("Client NEP = {}", String.join("+", nodeId, TapiStringConstants.DSR,
690                 xpdrClMaps.get(i).getLogicalConnectionPoint()));
691             Uuid nepUuid = new Uuid(UUID.nameUUIDFromBytes(
692                 (String.join("+", nodeId, TapiStringConstants.DSR,
693                     xpdrClMaps.get(i).getLogicalConnectionPoint())).getBytes(StandardCharsets.UTF_8)).toString());
694             NameBuilder nameBldr = new NameBuilder().setValue(String.join("+", nodeId,
695                 TapiStringConstants.DSR, xpdrClMaps.get(i).getLogicalConnectionPoint()));
696             Name name;
697             if (OpenroadmNodeType.TPDR.getName().equalsIgnoreCase(xponderType.getName())) {
698                 name = nameBldr.setValueName("100G-tpdr").build();
699             } else {
700                 name = nameBldr.setValueName("NodeEdgePoint_C").build();
701             }
702
703             List<Class<? extends SupportedIfCapability>> newSupIfCapList =
704                     new ArrayList<>(xpdrClMaps.get(i).getSupportedInterfaceCapability());
705
706             OwnedNodeEdgePoint onep = createNep(nepUuid, xpdrClMaps.get(i).getLogicalConnectionPoint(),
707                 Map.of(name.key(), name), LayerProtocolName.DSR, LayerProtocolName.DSR, true,
708                 String.join("+", nodeId, TapiStringConstants.DSR), newSupIfCapList,
709                 transformOperState(xpdrClMaps.get(i).getPortOperState()),
710                 transformAdminState(xpdrClMaps.get(i).getPortAdminState()));
711             onepl.put(onep.key(), onep);
712         }
713         // network nep creation on I_ODU node
714         for (int i = 0; i < xpdrNetMaps.size(); i++) {
715             LOG.info("iODU NEP = {}", String.join("+", nodeId, TapiStringConstants.I_ODU,
716                 xpdrNetMaps.get(i).getLogicalConnectionPoint()));
717             Uuid nepUuid = new Uuid(UUID.nameUUIDFromBytes(
718                 (String.join("+", nodeId, TapiStringConstants.I_ODU,
719                     xpdrNetMaps.get(i).getLogicalConnectionPoint())).getBytes(StandardCharsets.UTF_8)).toString());
720             Name onedName = new NameBuilder()
721                 .setValueName("iNodeEdgePoint_N")
722                 .setValue(String.join("+", nodeId, TapiStringConstants.I_ODU,
723                     xpdrNetMaps.get(i).getLogicalConnectionPoint()))
724                 .build();
725
726             List<Class<? extends SupportedIfCapability>> newSupIfCapList =
727                     new ArrayList<>(xpdrNetMaps.get(i).getSupportedInterfaceCapability());
728
729             OwnedNodeEdgePoint onep = createNep(nepUuid, xpdrNetMaps.get(i).getLogicalConnectionPoint(),
730                 Map.of(onedName.key(), onedName),
731                 LayerProtocolName.ODU, LayerProtocolName.DSR, true,
732                 String.join("+", nodeId, TapiStringConstants.I_ODU), newSupIfCapList,
733                 transformOperState(xpdrNetMaps.get(i).getPortOperState()),
734                 transformAdminState(xpdrNetMaps.get(i).getPortAdminState()));
735             onepl.put(onep.key(), onep);
736         }
737         // network nep creation on E_ODU node
738         for (int i = 0; i < xpdrClMaps.size(); i++) {
739             LOG.info("eODU NEP = {}", String.join("+", nodeId, TapiStringConstants.E_ODU,
740                 xpdrClMaps.get(i).getLogicalConnectionPoint()));
741             Uuid nepUuid = new Uuid(UUID.nameUUIDFromBytes(
742                 (String.join("+", nodeId, TapiStringConstants.E_ODU,
743                     xpdrClMaps.get(i).getLogicalConnectionPoint())).getBytes(StandardCharsets.UTF_8)).toString());
744             Name onedName = new NameBuilder()
745                 .setValueName("eNodeEdgePoint_N")
746                 .setValue(String.join("+", nodeId, TapiStringConstants.E_ODU,
747                     xpdrClMaps.get(i).getLogicalConnectionPoint()))
748                 .build();
749
750             List<Class<? extends SupportedIfCapability>> newSupIfCapList =
751                     new ArrayList<>(xpdrClMaps.get(i).getSupportedInterfaceCapability());
752
753             OwnedNodeEdgePoint onep = createNep(nepUuid, xpdrClMaps.get(i).getLogicalConnectionPoint(),
754                 Map.of(onedName.key(), onedName),
755                 LayerProtocolName.ODU, LayerProtocolName.DSR, false,
756                 String.join("+", nodeId, TapiStringConstants.E_ODU), newSupIfCapList,
757                 transformOperState(xpdrClMaps.get(i).getPortOperState()),
758                 transformAdminState(xpdrClMaps.get(i).getPortAdminState()));
759             onepl.put(onep.key(), onep);
760         }
761         return onepl;
762     }
763
764     private OperationalState transformOperState(String operString) {
765         State operState = org.opendaylight.transportpce.networkmodel.util.TopologyUtils.setNetworkOperState(operString);
766         return operState.equals(State.InService) ? OperationalState.ENABLED : OperationalState.DISABLED;
767     }
768
769     private AdministrativeState transformAdminState(String adminString) {
770         AdminStates adminState = org.opendaylight.transportpce.networkmodel.util.TopologyUtils
771             .setNetworkAdminState(adminString);
772         return adminState.equals(AdminStates.InService) ? AdministrativeState.UNLOCKED : AdministrativeState.LOCKED;
773     }
774
775     private OwnedNodeEdgePoint createNep(Uuid nepUuid, String tpid, Map<NameKey, Name> nepNames,
776                                          LayerProtocolName nepProtocol, LayerProtocolName nodeProtocol, boolean withSip,
777                                          String keyword,
778                                          List<Class<? extends SupportedIfCapability>> supportedInterfaceCapability,
779                                          OperationalState operState, AdministrativeState adminState) {
780         OwnedNodeEdgePointBuilder onepBldr = new OwnedNodeEdgePointBuilder()
781                 .setUuid(nepUuid)
782                 .setLayerProtocolName(nepProtocol)
783                 .setName(nepNames);
784         if (withSip) {
785             onepBldr.setMappedServiceInterfacePoint(createMSIP(1, nepProtocol, tpid, keyword,
786                     supportedInterfaceCapability, operState, adminState));
787         }
788         LOG.debug("Node layer {}", nodeProtocol.getName());
789         onepBldr.setSupportedCepLayerProtocolQualifier(createSupportedLayerProtocolQualifier(
790                 supportedInterfaceCapability, nepProtocol));
791         onepBldr.setLinkPortDirection(PortDirection.BIDIRECTIONAL).setLinkPortRole(PortRole.SYMMETRIC)
792                 .setAdministrativeState(adminState).setOperationalState(operState)
793                 .setLifecycleState(LifecycleState.INSTALLED).setTerminationDirection(TerminationDirection.BIDIRECTIONAL)
794                 .setTerminationState(TerminationState.TERMINATEDBIDIRECTIONAL);
795         return onepBldr.build();
796     }
797
798     private Map<OwnedNodeEdgePointKey, OwnedNodeEdgePoint> createRoadmNeps(String orNodeId, String tpId,
799                                                                            boolean withSip, OperationalState operState,
800                                                                            AdministrativeState adminState) {
801         Map<OwnedNodeEdgePointKey, OwnedNodeEdgePoint> onepMap = new HashMap<>();
802         // PHOTONIC MEDIA nep
803         Uuid nepUuid = new Uuid(UUID.nameUUIDFromBytes((String.join("+", orNodeId,
804                 TapiStringConstants.PHTNC_MEDIA, tpId)).getBytes(StandardCharsets.UTF_8)).toString());
805         Name nepName = new NameBuilder()
806                 .setValueName(TapiStringConstants.PHTNC_MEDIA + "NodeEdgePoint")
807                 .setValue(String.join("+", orNodeId, TapiStringConstants.PHTNC_MEDIA, tpId))
808                 .build();
809         OwnedNodeEdgePoint onep = new OwnedNodeEdgePointBuilder()
810             .setUuid(nepUuid)
811             .setLayerProtocolName(LayerProtocolName.PHOTONICMEDIA)
812             .setName(Map.of(nepName.key(), nepName))
813             .setSupportedCepLayerProtocolQualifier(Set.of(PHOTONICLAYERQUALIFIEROMS.class))
814             .setLinkPortDirection(PortDirection.BIDIRECTIONAL).setLinkPortRole(PortRole.SYMMETRIC)
815             .setAdministrativeState(adminState).setOperationalState(operState)
816             .setLifecycleState(LifecycleState.INSTALLED).setTerminationDirection(TerminationDirection.BIDIRECTIONAL)
817             .setTerminationState(TerminationState.TERMINATEDBIDIRECTIONAL)
818             .build();
819         onepMap.put(onep.key(), onep);
820
821         // MC nep
822         Uuid nepUuid1 = new Uuid(UUID.nameUUIDFromBytes((String.join("+", orNodeId,
823                 TapiStringConstants.MC, tpId)).getBytes(StandardCharsets.UTF_8)).toString());
824         Name nepName1 = new NameBuilder()
825                 .setValueName(TapiStringConstants.MC + "NodeEdgePoint")
826                 .setValue(String.join("+", orNodeId, TapiStringConstants.MC, tpId))
827                 .build();
828         OwnedNodeEdgePointBuilder onepBldr1 = new OwnedNodeEdgePointBuilder()
829                 .setUuid(nepUuid1)
830                 .setLayerProtocolName(LayerProtocolName.PHOTONICMEDIA)
831                 .setName(Map.of(nepName1.key(), nepName1))
832                 .setSupportedCepLayerProtocolQualifier(Set.of(PHOTONICLAYERQUALIFIEROMS.class))
833                 .setLinkPortDirection(PortDirection.BIDIRECTIONAL).setLinkPortRole(PortRole.SYMMETRIC)
834                 .setAdministrativeState(adminState).setOperationalState(operState)
835                 .setLifecycleState(LifecycleState.INSTALLED).setTerminationDirection(TerminationDirection.BIDIRECTIONAL)
836                 .setTerminationState(TerminationState.TERMINATEDBIDIRECTIONAL);
837         if (withSip) {
838             onepBldr1.setMappedServiceInterfacePoint(createMSIP(1, LayerProtocolName.PHOTONICMEDIA,
839                 tpId, String.join("+", orNodeId, TapiStringConstants.MC), null,
840                 operState, adminState));
841         }
842         OwnedNodeEdgePoint onep1 = onepBldr1.build();
843         onepMap.put(onep1.key(), onep1);
844
845         // OTSiMC nep
846         Uuid nepUuid2 = new Uuid(UUID.nameUUIDFromBytes((String.join("+", orNodeId, TapiStringConstants.OTSI_MC,
847                 tpId)).getBytes(StandardCharsets.UTF_8)).toString());
848         Name nepName2 = new NameBuilder()
849                 .setValueName(TapiStringConstants.OTSI_MC + "NodeEdgePoint")
850                 .setValue(String.join("+", orNodeId, TapiStringConstants.OTSI_MC, tpId))
851                 .build();
852
853         OwnedNodeEdgePoint onep2 = new OwnedNodeEdgePointBuilder()
854             .setUuid(nepUuid2)
855             .setLayerProtocolName(LayerProtocolName.PHOTONICMEDIA)
856             .setName(Map.of(nepName2.key(), nepName2))
857             .setSupportedCepLayerProtocolQualifier(Set.of(PHOTONICLAYERQUALIFIEROMS.class))
858             .setLinkPortDirection(PortDirection.BIDIRECTIONAL).setLinkPortRole(PortRole.SYMMETRIC)
859             .setAdministrativeState(adminState).setOperationalState(operState)
860             .setLifecycleState(LifecycleState.INSTALLED).setTerminationDirection(TerminationDirection.BIDIRECTIONAL)
861             .setTerminationState(TerminationState.TERMINATEDBIDIRECTIONAL)
862             .build();
863         onepMap.put(onep2.key(), onep2);
864         return onepMap;
865     }
866
867     private Map<MappedServiceInterfacePointKey, MappedServiceInterfacePoint>
868             createMSIP(int nb, LayerProtocolName layerProtocol, String tpid, String nodeid,
869                    List<Class<? extends SupportedIfCapability>> supportedInterfaceCapability,
870                    OperationalState operState, AdministrativeState adminState) {
871         Map<MappedServiceInterfacePointKey, MappedServiceInterfacePoint> msipl = new HashMap<>();
872         for (int i = 0; i < nb; i++) {
873             Uuid sipUuid = new Uuid(UUID.nameUUIDFromBytes((String.join("+", "SIP", nodeid,
874                     tpid)).getBytes(StandardCharsets.UTF_8)).toString());
875             MappedServiceInterfacePoint msip = new MappedServiceInterfacePointBuilder()
876                     .setServiceInterfacePointUuid(sipUuid).build();
877             ServiceInterfacePoint sip = createSIP(sipUuid, layerProtocol, tpid, nodeid, supportedInterfaceCapability,
878                 operState, adminState);
879             this.sipMap.put(sip.key(), sip);
880             LOG.info("SIP created {}", sip.getUuid());
881             // this.tapiSips.put(sip.key(), sip);
882             msipl.put(msip.key(), msip);
883         }
884         return msipl;
885     }
886
887     private ServiceInterfacePoint createSIP(Uuid sipUuid, LayerProtocolName layerProtocol, String tpid, String nodeid,
888                                             List<Class<? extends SupportedIfCapability>> supportedInterfaceCapability,
889                                             OperationalState operState, AdministrativeState adminState) {
890         // TODO: what value should be set in total capacity and available capacity
891         LOG.info("SIP name = {}", String.join("+", nodeid, tpid));
892         Name sipName = new NameBuilder()
893                 .setValueName("SIP name")
894                 .setValue(String.join("+", nodeid, tpid))
895                 .build();
896         return new ServiceInterfacePointBuilder()
897                 .setUuid(sipUuid)
898                 .setName(Map.of(sipName.key(), sipName))
899                 .setLayerProtocolName(layerProtocol)
900                 .setAdministrativeState(adminState)
901                 .setOperationalState(operState)
902                 .setLifecycleState(LifecycleState.INSTALLED)
903                 .setAvailableCapacity(new AvailableCapacityBuilder().build())
904                 .setTotalPotentialCapacity(new TotalPotentialCapacityBuilder().build())
905                 .setSupportedLayerProtocolQualifier(createSupportedLayerProtocolQualifier(supportedInterfaceCapability,
906                         layerProtocol))
907                 .build();
908     }
909
910     private Node createRoadmTapiNode(String orNodeId, Map<OwnedNodeEdgePointKey, OwnedNodeEdgePoint> oneplist) {
911         // UUID
912         Uuid nodeUuid = new Uuid(UUID.nameUUIDFromBytes((String.join("+", orNodeId,
913             TapiStringConstants.PHTNC_MEDIA)).getBytes(StandardCharsets.UTF_8)).toString());
914         // Names
915         Name nodeNames =  new NameBuilder().setValueName("roadm node name")
916             .setValue(String.join("+", orNodeId, TapiStringConstants.PHTNC_MEDIA)).build();
917         Name nameNodeType = new NameBuilder().setValueName("Node Type")
918             .setValue(OpenroadmNodeType.ROADM.getName()).build();
919         // Protocol Layer
920         Set<LayerProtocolName> layerProtocols = Set.of(LayerProtocolName.PHOTONICMEDIA);
921         // Empty random creation of mandatory fields for avoiding errors....
922         CostCharacteristic costCharacteristic = new CostCharacteristicBuilder()
923             .setCostAlgorithm("Restricted Shortest Path - RSP")
924             .setCostName("HOP_COUNT")
925             .setCostValue(TapiStringConstants.COST_HOP_VALUE)
926             .build();
927         LatencyCharacteristic latencyCharacteristic = new LatencyCharacteristicBuilder()
928             .setFixedLatencyCharacteristic(TapiStringConstants.COST_HOP_VALUE)
929             .setQueingLatencyCharacteristic(TapiStringConstants.QUEING_LATENCY_VALUE)
930             .setJitterCharacteristic(TapiStringConstants.JITTER_VALUE)
931             .setWanderCharacteristic(TapiStringConstants.WANDER_VALUE)
932             .setTrafficPropertyName("FIXED_LATENCY")
933             .build();
934         return new NodeBuilder()
935             .setUuid(nodeUuid)
936             .setName(Map.of(nodeNames.key(), nodeNames, nameNodeType.key(), nameNodeType))
937             .setLayerProtocolName(layerProtocols)
938             .setAdministrativeState(AdministrativeState.UNLOCKED)
939             .setOperationalState(OperationalState.ENABLED)
940             .setLifecycleState(LifecycleState.INSTALLED)
941             .setOwnedNodeEdgePoint(oneplist)
942             .setNodeRuleGroup(createNodeRuleGroupForRdmNode(orNodeId, nodeUuid, oneplist.values()))
943             .setCostCharacteristic(Map.of(costCharacteristic.key(), costCharacteristic))
944             .setLatencyCharacteristic(Map.of(latencyCharacteristic.key(), latencyCharacteristic))
945             .setErrorCharacteristic("error")
946             .setLossCharacteristic("loss")
947             .setRepeatDeliveryCharacteristic("repeat delivery")
948             .setDeliveryOrderCharacteristic("delivery order")
949             .setUnavailableTimeCharacteristic("unavailable time")
950             .setServerIntegrityProcessCharacteristic("server integrity process")
951             .build();
952     }
953
954     private Map<NodeRuleGroupKey, NodeRuleGroup> createNodeRuleGroupForRdmNode(String orNodeId, Uuid nodeUuid,
955                                                                                Collection<OwnedNodeEdgePoint> onepl) {
956         Map<NodeEdgePointKey, NodeEdgePoint>
957                 nepMap = new HashMap<>();
958         for (OwnedNodeEdgePoint onep : onepl) {
959             NodeEdgePoint nep = new NodeEdgePointBuilder()
960                 .setTopologyUuid(this.tapiTopoUuid)
961                 .setNodeUuid(nodeUuid)
962                 .setNodeEdgePointUuid(onep.key().getUuid())
963                 .build();
964             nepMap.put(nep.key(), nep);
965         }
966         Map<NodeRuleGroupKey, NodeRuleGroup> nodeRuleGroupMap = new HashMap<>();
967         Map<RuleKey, Rule> ruleList = new HashMap<>();
968         Rule rule = new RuleBuilder()
969                 .setLocalId("forward")
970                 .setForwardingRule(ForwardingRule.MAYFORWARDACROSSGROUP)
971                 .setRuleType(RuleType.FORWARDING)
972                 .build();
973         ruleList.put(rule.key(), rule);
974         NodeRuleGroup nodeRuleGroup = new NodeRuleGroupBuilder()
975                 .setUuid(new Uuid(UUID.nameUUIDFromBytes((orNodeId + " node rule group")
976                         .getBytes(StandardCharsets.UTF_8)).toString()))
977                 .setRule(ruleList)
978                 .setNodeEdgePoint(nepMap)
979                 .build();
980         nodeRuleGroupMap.put(nodeRuleGroup.key(), nodeRuleGroup);
981         return nodeRuleGroupMap;
982     }
983
984     private Map<LinkKey, Link> createTapiTransitionalLinks(String nodeId, List<Mapping> xpdrNetMaps) {
985         Map<LinkKey, Link> linkMap = new HashMap<>();
986         for (Mapping mapping : xpdrNetMaps) {
987             Link transiLink = tapiLink.createTapiLink(nodeId, mapping.getLogicalConnectionPoint(), nodeId,
988                 mapping.getLogicalConnectionPoint(), TapiStringConstants.TRANSITIONAL_LINK, TapiStringConstants.DSR,
989                 TapiStringConstants.OTSI, TapiStringConstants.I_ODU, TapiStringConstants.I_OTSI,
990                 "inService", "inService", Set.of(LayerProtocolName.ODU, LayerProtocolName.PHOTONICMEDIA),
991                 Set.of(LayerProtocolName.ODU.getName(), LayerProtocolName.PHOTONICMEDIA.getName()),
992                 this.tapiTopoUuid);
993             linkMap.put(transiLink.key(), transiLink);
994         }
995         // return a map of links and then we can do merge the corresponding link map into the topology context
996         return linkMap;
997     }
998
999     private OduSwitchingPools createTpdrSwitchPool(List<Mapping> xpdrNetMaps) {
1000         Map<NonBlockingListKey, NonBlockingList> nblMap = new HashMap<>();
1001         int count = 1;
1002         for (int i = 1; i <= xpdrNetMaps.size(); i++) {
1003             LOG.info("XPDr net LCP = {}", xpdrNetMaps.get(i - 1).getLogicalConnectionPoint());
1004             LOG.info("XPDr net associated LCP = {}", xpdrNetMaps.get(i - 1).getConnectionMapLcp());
1005             TpId tpid1 = new TpId(xpdrNetMaps.get(i - 1).getLogicalConnectionPoint());
1006             TpId tpid2 = new TpId(xpdrNetMaps.get(i - 1).getConnectionMapLcp());
1007             Set<TpId> tpList = new HashSet<>();
1008             tpList.add(tpid1);
1009             tpList.add(tpid2);
1010             NonBlockingList nbl = new NonBlockingListBuilder()
1011                 .setNblNumber(Uint16.valueOf(count))
1012                 .setTpList(tpList)
1013                 .build();
1014             nblMap.put(nbl.key(), nbl);
1015             count++;
1016         }
1017         return new OduSwitchingPoolsBuilder()
1018             .setNonBlockingList(nblMap)
1019             .setSwitchingPoolNumber(Uint16.valueOf(1))
1020             .build();
1021     }
1022
1023     private OduSwitchingPools createSwtchSwitchPool(List<Mapping> xpdrClMaps, List<Mapping> xpdrNetMaps,
1024                                                     Integer xpdrNb) {
1025         Set<TpId> tpl = new HashSet<>();
1026         TpId tpId = null;
1027         for (int i = 1; i <= xpdrClMaps.size(); i++) {
1028             tpId = new TpId("XPDR" + xpdrNb + TapiStringConstants.CLIENT + i);
1029             tpl.add(tpId);
1030         }
1031         for (int i = 1; i <= xpdrNetMaps.size(); i++) {
1032             tpId = new TpId("XPDR" + xpdrNb + TapiStringConstants.NETWORK + i);
1033             tpl.add(tpId);
1034         }
1035         Map<NonBlockingListKey, NonBlockingList> nbMap = new HashMap<>();
1036         NonBlockingList nbl = new NonBlockingListBuilder()
1037             .setNblNumber(Uint16.valueOf(1))
1038             .setTpList(tpl)
1039             .build();
1040         nbMap.put(nbl.key(),nbl);
1041
1042         return new OduSwitchingPoolsBuilder()
1043             .setSwitchingPoolNumber(Uint16.valueOf(1))
1044             .setSwitchingPoolType(SwitchingPoolTypes.NonBlocking)
1045             .setNonBlockingList(nbMap)
1046             .build();
1047     }
1048
1049     private OduSwitchingPools createMuxSwitchPool(List<Mapping> xpdrClMaps, List<Mapping> xpdrNetMaps, Integer xpdrNb) {
1050         Map<NonBlockingListKey, NonBlockingList> nbMap = new HashMap<>();
1051         for (int i = 1; i <= xpdrClMaps.size(); i++) {
1052             Set<TpId> tpList = new HashSet<>();
1053             TpId tpId = new TpId("XPDR" + xpdrNb + TapiStringConstants.CLIENT + i);
1054             tpList.add(tpId);
1055             tpId = new TpId("XPDR" + xpdrNb + "-NETWORK1");
1056             tpList.add(tpId);
1057             NonBlockingList nbl = new NonBlockingListBuilder()
1058                 .setNblNumber(Uint16.valueOf(i))
1059                 .setTpList(tpList)
1060                 .setAvailableInterconnectBandwidth(Uint32.valueOf(xpdrNetMaps.size() * 10L))
1061                 .setInterconnectBandwidthUnit(Uint32.valueOf(1000000000))
1062                 .build();
1063             nbMap.put(nbl.key(),nbl);
1064         }
1065         return new OduSwitchingPoolsBuilder()
1066                 .setSwitchingPoolNumber(Uint16.valueOf(1))
1067                 .setSwitchingPoolType(SwitchingPoolTypes.NonBlocking)
1068                 .setNonBlockingList(nbMap)
1069                 .build();
1070     }
1071
1072     private Map<NodeRuleGroupKey, NodeRuleGroup> createNodeRuleGroupForOtsiNode(String nodeId,
1073                                                                                 List<Mapping> xpdrNetMaps,
1074                                                                                 Map<RuleKey, Rule> ruleList) {
1075         Map<NodeRuleGroupKey, NodeRuleGroup> nodeRuleGroupMap = new HashMap<>();
1076         // create NodeRuleGroup
1077         int count = 1;
1078         for (Mapping tpMapping : xpdrNetMaps) {
1079             Map<NodeEdgePointKey, NodeEdgePoint> nepList = new HashMap<>();
1080             NodeEdgePoint inep = new NodeEdgePointBuilder()
1081                 .setTopologyUuid(this.tapiTopoUuid)
1082                 .setNodeUuid(new Uuid(UUID.nameUUIDFromBytes((String.join("+", nodeId,
1083                         TapiStringConstants.OTSI)).getBytes(StandardCharsets.UTF_8)).toString()))
1084                 .setNodeEdgePointUuid(new Uuid(UUID.nameUUIDFromBytes((String.join("+", nodeId,
1085                     TapiStringConstants.I_OTSI, tpMapping.getLogicalConnectionPoint()))
1086                     .getBytes(StandardCharsets.UTF_8)).toString()))
1087                 .build();
1088             NodeEdgePoint enep = new NodeEdgePointBuilder()
1089                 .setTopologyUuid(this.tapiTopoUuid)
1090                 .setNodeUuid(new Uuid(UUID.nameUUIDFromBytes((String.join("+", nodeId,
1091                     TapiStringConstants.OTSI)).getBytes(StandardCharsets.UTF_8)).toString()))
1092                 .setNodeEdgePointUuid(new Uuid(UUID.nameUUIDFromBytes(
1093                     (String.join("+", nodeId, TapiStringConstants.E_OTSI,
1094                         tpMapping.getLogicalConnectionPoint())).getBytes(StandardCharsets.UTF_8)).toString()))
1095                 .build();
1096             nepList.put(inep.key(), inep);
1097             nepList.put(enep.key(), enep);
1098             // Empty random creation of mandatory fields for avoiding errors....
1099             CostCharacteristic costCharacteristic = new CostCharacteristicBuilder()
1100                 .setCostAlgorithm("Restricted Shortest Path - RSP")
1101                 .setCostName("HOP_COUNT")
1102                 .setCostValue(TapiStringConstants.COST_HOP_VALUE)
1103                 .build();
1104             LatencyCharacteristic latencyCharacteristic = new LatencyCharacteristicBuilder()
1105                 .setFixedLatencyCharacteristic(TapiStringConstants.FIXED_LATENCY_VALUE)
1106                 .setQueingLatencyCharacteristic(TapiStringConstants.QUEING_LATENCY_VALUE)
1107                 .setJitterCharacteristic(TapiStringConstants.JITTER_VALUE)
1108                 .setWanderCharacteristic(TapiStringConstants.WANDER_VALUE)
1109                 .setTrafficPropertyName("FIXED_LATENCY")
1110                 .build();
1111             RiskCharacteristic riskCharacteristic = new RiskCharacteristicBuilder()
1112                 .setRiskCharacteristicName("risk characteristic")
1113                 .setRiskIdentifierList(Set.of("risk identifier1", "risk identifier2"))
1114                 .build();
1115             NodeRuleGroup nodeRuleGroup = new NodeRuleGroupBuilder()
1116                 .setUuid(new Uuid(
1117                     UUID.nameUUIDFromBytes(("otsi node rule group " + count).getBytes(StandardCharsets.UTF_8))
1118                         .toString()))
1119                 .setRule(ruleList)
1120                 .setNodeEdgePoint(nepList)
1121                 .setRiskCharacteristic(Map.of(riskCharacteristic.key(), riskCharacteristic))
1122                 .setCostCharacteristic(Map.of(costCharacteristic.key(), costCharacteristic))
1123                 .setLatencyCharacteristic(Map.of(latencyCharacteristic.key(), latencyCharacteristic))
1124                 .build();
1125             nodeRuleGroupMap.put(nodeRuleGroup.key(), nodeRuleGroup);
1126             count++;
1127         }
1128         return nodeRuleGroupMap;
1129     }
1130
1131     private Map<NodeRuleGroupKey, NodeRuleGroup> createNodeRuleGroupForDsrNode(String nodeId,
1132                                                                                OduSwitchingPools oorOduSwitchingPool,
1133                                                                                Map<RuleKey, Rule> ruleList,
1134                                                                                Map<OwnedNodeEdgePointKey,
1135                                                                                        OwnedNodeEdgePoint> onepl) {
1136         // create NodeRuleGroup
1137         if (oorOduSwitchingPool == null) {
1138             LOG.info("No switching pool created for node = {}", nodeId);
1139             return new HashMap<>();
1140         }
1141         LOG.info("ONEPL = {}", onepl.values());
1142         Map<NodeRuleGroupKey, NodeRuleGroup> nodeRuleGroupMap = new HashMap<>();
1143         int count = 1;
1144         for (NonBlockingList nbl : oorOduSwitchingPool.nonnullNonBlockingList().values()) {
1145             LOG.info("Non blocking list = {}", nbl);
1146             Map<NodeEdgePointKey, NodeEdgePoint> nepList = new HashMap<>();
1147             for (TpId tp : nbl.getTpList()) {
1148                 LOG.info("EDOU TP = {}", String.join("+", nodeId, TapiStringConstants.E_ODU, tp.getValue()));
1149                 LOG.info("DSR TP = {}", String.join("+", nodeId, TapiStringConstants.DSR, tp.getValue()));
1150                 Uuid tpUuid = new Uuid(UUID.nameUUIDFromBytes((String.join("+", nodeId,
1151                     TapiStringConstants.E_ODU, tp.getValue())).getBytes(StandardCharsets.UTF_8)).toString());
1152                 Uuid tp1Uuid = new Uuid(UUID.nameUUIDFromBytes((String.join("+", nodeId,
1153                     TapiStringConstants.DSR, tp.getValue())).getBytes(StandardCharsets.UTF_8)).toString());
1154                 if (onepl.containsKey(new OwnedNodeEdgePointKey(tpUuid))
1155                         && onepl.containsKey(new OwnedNodeEdgePointKey(tp1Uuid))) {
1156                     NodeEdgePoint nep1 = new NodeEdgePointBuilder()
1157                         .setTopologyUuid(this.tapiTopoUuid)
1158                         .setNodeUuid(new Uuid(UUID.nameUUIDFromBytes(
1159                             (String.join("+", nodeId,TapiStringConstants. DSR))
1160                                 .getBytes(StandardCharsets.UTF_8)).toString()))
1161                         .setNodeEdgePointUuid(tp1Uuid)
1162                         .build();
1163                     NodeEdgePoint nep2 = new NodeEdgePointBuilder()
1164                         .setTopologyUuid(this.tapiTopoUuid)
1165                         .setNodeUuid(new Uuid(UUID.nameUUIDFromBytes(
1166                             (String.join("+", nodeId,TapiStringConstants. DSR))
1167                                 .getBytes(StandardCharsets.UTF_8)).toString()))
1168                         .setNodeEdgePointUuid(tpUuid)
1169                         .build();
1170                     nepList.put(nep1.key(), nep1);
1171                     nepList.put(nep2.key(), nep2);
1172                 }
1173             }
1174             // Empty random creation of mandatory fields for avoiding errors....
1175             CostCharacteristic costCharacteristic = new CostCharacteristicBuilder()
1176                 .setCostAlgorithm("Restricted Shortest Path - RSP")
1177                 .setCostName("HOP_COUNT")
1178                 .setCostValue(TapiStringConstants.COST_HOP_VALUE)
1179                 .build();
1180             LatencyCharacteristic latencyCharacteristic = new LatencyCharacteristicBuilder()
1181                 .setFixedLatencyCharacteristic(TapiStringConstants.FIXED_LATENCY_VALUE)
1182                 .setQueingLatencyCharacteristic(TapiStringConstants.QUEING_LATENCY_VALUE)
1183                 .setJitterCharacteristic(TapiStringConstants.JITTER_VALUE)
1184                 .setWanderCharacteristic(TapiStringConstants.WANDER_VALUE)
1185                 .setTrafficPropertyName("FIXED_LATENCY")
1186                 .build();
1187             RiskCharacteristic riskCharacteristic = new RiskCharacteristicBuilder()
1188                 .setRiskCharacteristicName("risk characteristic")
1189                 .setRiskIdentifierList(Set.of("risk identifier1", "risk identifier2"))
1190                 .build();
1191             NodeRuleGroup nodeRuleGroup = new NodeRuleGroupBuilder()
1192                 .setUuid(new Uuid(
1193                     UUID.nameUUIDFromBytes(("dsr node rule group " + count).getBytes(StandardCharsets.UTF_8))
1194                         .toString()))
1195                 .setRule(ruleList)
1196                 .setNodeEdgePoint(nepList)
1197                 .setRiskCharacteristic(Map.of(riskCharacteristic.key(), riskCharacteristic))
1198                 .setCostCharacteristic(Map.of(costCharacteristic.key(), costCharacteristic))
1199                 .setLatencyCharacteristic(Map.of(latencyCharacteristic.key(), latencyCharacteristic))
1200                 .build();
1201             nodeRuleGroupMap.put(nodeRuleGroup.key(), nodeRuleGroup);
1202             count++;
1203         }
1204         return nodeRuleGroupMap;
1205     }
1206
1207     private Set<Class<? extends LAYERPROTOCOLQUALIFIER>> createSupportedLayerProtocolQualifier(
1208             List<Class<? extends SupportedIfCapability>> sicList, LayerProtocolName lpn) {
1209         if (sicList == null) {
1210             return Set.of(PHOTONICLAYERQUALIFIEROMS.class);
1211         }
1212         Map<SupportedInterfaceCapabilityKey, SupportedInterfaceCapability> supIfMap = new HashMap<>();
1213         LOG.info("SIC list = {}", sicList);
1214         for (Class<? extends SupportedIfCapability> supInterCapa : sicList) {
1215             SupportedInterfaceCapability supIfCapa = new SupportedInterfaceCapabilityBuilder()
1216                     .withKey(new SupportedInterfaceCapabilityKey(supInterCapa))
1217                     .setIfCapType(supInterCapa)
1218                     .build();
1219             supIfMap.put(supIfCapa.key(), supIfCapa);
1220         }
1221         Set<Class<? extends LAYERPROTOCOLQUALIFIER>> sclpqList = new HashSet<>();
1222         for (SupportedInterfaceCapability sic : supIfMap.values()) {
1223             switch (lpn.getName()) {
1224                 case "DSR":
1225                     switch (sic.getIfCapType().getSimpleName()) {
1226                         // TODO: it may be needed to add more cases clauses if the interface capabilities of a
1227                         //  port are extended in the config file
1228                         case "If1GEODU0":
1229                             sclpqList.add(ODUTYPEODU0.class);
1230                             sclpqList.add(DIGITALSIGNALTYPEGigE.class);
1231                             break;
1232                         case "If10GEODU2e":
1233                             sclpqList.add(ODUTYPEODU2E.class);
1234                             sclpqList.add(DIGITALSIGNALTYPE10GigELAN.class);
1235                             break;
1236                         case "If10GEODU2":
1237                             sclpqList.add(ODUTYPEODU2.class);
1238                             sclpqList.add(DIGITALSIGNALTYPE10GigELAN.class);
1239                             break;
1240                         case "If10GE":
1241                             sclpqList.add(DIGITALSIGNALTYPE10GigELAN.class);
1242                             break;
1243                         case "If100GEODU4":
1244                             sclpqList.add(DIGITALSIGNALTYPE100GigE.class);
1245                             sclpqList.add(ODUTYPEODU4.class);
1246                             break;
1247                         case "If100GE":
1248                             sclpqList.add(DIGITALSIGNALTYPE100GigE.class);
1249                             break;
1250                         case "IfOCHOTU4ODU4":
1251                         case "IfOCH":
1252                             sclpqList.add(ODUTYPEODU4.class);
1253                             break;
1254                         default:
1255                             LOG.error("IfCapability type not managed");
1256                             break;
1257                     }
1258                     break;
1259                 case "ODU":
1260                     switch (sic.getIfCapType().getSimpleName()) {
1261                         // TODO: it may be needed to add more cases clauses if the interface capabilities of a
1262                         //  port are extended in the config file
1263                         case "If1GEODU0":
1264                             sclpqList.add(ODUTYPEODU0.class);
1265                             break;
1266                         case "If10GEODU2e":
1267                             sclpqList.add(ODUTYPEODU2E.class);
1268                             break;
1269                         case "If10GEODU2":
1270                         case "If10GE":
1271                             sclpqList.add(ODUTYPEODU2.class);
1272                             break;
1273                         case "If100GEODU4":
1274                         case "If100GE":
1275                         case "IfOCHOTU4ODU4":
1276                         case "IfOCH":
1277                             sclpqList.add(ODUTYPEODU4.class);
1278                             break;
1279                         default:
1280                             LOG.error("IfCapability type not managed");
1281                             break;
1282                     }
1283                     break;
1284                 case "PHOTONIC_MEDIA":
1285                     if (sic.getIfCapType().getSimpleName().equals("IfOCHOTU4ODU4")
1286                             || sic.getIfCapType().getSimpleName().equals("IfOCH")) {
1287                         sclpqList.add(PHOTONICLAYERQUALIFIEROTSi.class);
1288                         sclpqList.add(PHOTONICLAYERQUALIFIEROMS.class);
1289                     }
1290                     break;
1291                 default:
1292                     LOG.error("Layer Protocol Name is unknown {}", lpn.getName());
1293                     break;
1294             }
1295         }
1296         return sclpqList;
1297     }
1298
1299     private String getNodeType(XpdrNodeTypes xponderType) {
1300         switch (xponderType.getIntValue()) {
1301             case 1:
1302                 return OpenroadmNodeType.TPDR.getName();
1303             case 2:
1304                 return OpenroadmNodeType.MUXPDR.getName();
1305             case 3:
1306                 return OpenroadmNodeType.SWITCH.getName();
1307             default:
1308                 LOG.info("XpdrType {} not supported", xponderType);
1309                 break;
1310         }
1311         return null;
1312     }
1313
1314     private void mergeNodeinTopology(Map<NodeKey, Node> nodeMap) {
1315         // TODO is this merge correct? Should we just merge topology by changing the nodes map??
1316         // TODO: verify this is correct. Should we identify the context IID with the context UUID??
1317         LOG.info("Creating tapi node in TAPI topology context");
1318         InstanceIdentifier<Topology> topoIID = InstanceIdentifier.builder(Context.class)
1319             .augmentation(Context1.class).child(TopologyContext.class)
1320             .child(Topology.class, new TopologyKey(this.tapiTopoUuid))
1321             .build();
1322
1323         Topology topology = new TopologyBuilder().setUuid(this.tapiTopoUuid).setNode(nodeMap).build();
1324
1325         // merge in datastore
1326         this.networkTransactionService.merge(LogicalDatastoreType.OPERATIONAL, topoIID,
1327                 topology);
1328         try {
1329             this.networkTransactionService.commit().get();
1330         } catch (InterruptedException | ExecutionException e) {
1331             LOG.error("Error populating TAPI topology: ", e);
1332         }
1333         LOG.info("Node added succesfully.");
1334     }
1335
1336     private void mergeLinkinTopology(Map<LinkKey, Link> linkMap) {
1337         // TODO is this merge correct? Should we just merge topology by changing the nodes map??
1338         // TODO: verify this is correct. Should we identify the context IID with the context UUID??
1339         LOG.info("Creating tapi node in TAPI topology context");
1340         InstanceIdentifier<Topology> topoIID = InstanceIdentifier.builder(Context.class)
1341             .augmentation(Context1.class).child(TopologyContext.class)
1342             .child(Topology.class, new TopologyKey(this.tapiTopoUuid))
1343             .build();
1344
1345         Topology topology = new TopologyBuilder().setUuid(this.tapiTopoUuid).setLink(linkMap).build();
1346
1347         // merge in datastore
1348         this.networkTransactionService.merge(LogicalDatastoreType.OPERATIONAL, topoIID,
1349                 topology);
1350         try {
1351             this.networkTransactionService.commit().get();
1352         } catch (InterruptedException | ExecutionException e) {
1353             LOG.error("Error populating TAPI topology: ", e);
1354         }
1355         LOG.info("Roadm Link added succesfully.");
1356     }
1357
1358     private void mergeSipsinContext(Map<ServiceInterfacePointKey, ServiceInterfacePoint> sips) {
1359         // TODO is this merge correct? Should we just merge topology by changing the nodes map??
1360         // TODO: verify this is correct. Should we identify the context IID with the context UUID??
1361         try {
1362             ContextBuilder contextBuilder = new ContextBuilder();
1363             contextBuilder.setServiceInterfacePoint(sips);
1364             InstanceIdentifier<Context> contextIID = InstanceIdentifier.builder(Context.class).build();
1365             // merge in datastore
1366             this.networkTransactionService.merge(LogicalDatastoreType.OPERATIONAL, contextIID,
1367                     contextBuilder.build());
1368             this.networkTransactionService.commit().get();
1369             LOG.info("TAPI SIPs merged successfully.");
1370         } catch (InterruptedException | ExecutionException e) {
1371             LOG.error("Failed to merge TAPI Sips", e);
1372         }
1373     }
1374
1375     private void deleteLinkFromTopo(Uuid linkUuid) {
1376         // TODO: check if this IID is correct
1377         try {
1378             InstanceIdentifier<Link> linkIID = InstanceIdentifier.builder(Context.class)
1379                 .augmentation(Context1.class).child(TopologyContext.class).child(Topology.class,
1380                     new TopologyKey(this.tapiTopoUuid)).child(Link.class, new LinkKey(linkUuid)).build();
1381             this.networkTransactionService.delete(LogicalDatastoreType.OPERATIONAL, linkIID);
1382             this.networkTransactionService.commit().get();
1383             LOG.info("TAPI link deleted successfully.");
1384         } catch (InterruptedException | ExecutionException e) {
1385             LOG.error("Failed to delete TAPI link", e);
1386         }
1387     }
1388
1389     private void deleteNodeFromTopo(Uuid nodeUuid) {
1390         // TODO: check if this IID is correct
1391         try {
1392             InstanceIdentifier<Node> nodeIDD = InstanceIdentifier.builder(Context.class)
1393                 .augmentation(Context1.class).child(TopologyContext.class).child(Topology.class,
1394                     new TopologyKey(this.tapiTopoUuid)).child(Node.class, new NodeKey(nodeUuid)).build();
1395             this.networkTransactionService.delete(LogicalDatastoreType.OPERATIONAL, nodeIDD);
1396             this.networkTransactionService.commit().get();
1397             LOG.info("TAPI Node deleted successfully.");
1398         } catch (InterruptedException | ExecutionException e) {
1399             LOG.error("Failed to delete TAPI Node", e);
1400         }
1401     }
1402
1403     private void deleteSipFromTopo(Uuid sipUuid) {
1404         // TODO: check if this IID is correct
1405         try {
1406             InstanceIdentifier<ServiceInterfacePoint> sipIID = InstanceIdentifier.builder(Context.class)
1407                     .child(ServiceInterfacePoint.class, new ServiceInterfacePointKey(sipUuid)).build();
1408             this.networkTransactionService.delete(LogicalDatastoreType.OPERATIONAL, sipIID);
1409             this.networkTransactionService.commit().get();
1410             LOG.info("TAPI SIP deleted successfully.");
1411         } catch (InterruptedException | ExecutionException e) {
1412             LOG.error("Failed to delete TAPI SIP", e);
1413         }
1414     }
1415
1416     private void updateConnectivityServicesState(Uuid sipUuid, String nodeId) {
1417         // TODO: check if this IID is correct
1418         InstanceIdentifier<ConnectivityContext> connectivitycontextIID = InstanceIdentifier.builder(Context.class)
1419             .augmentation(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.Context1.class)
1420             .child(ConnectivityContext.class)
1421             .build();
1422         ConnectivityContext connContext = null;
1423         try {
1424             Optional<ConnectivityContext> optConnContext =
1425                     this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL, connectivitycontextIID)
1426                             .get();
1427             if (!optConnContext.isPresent()) {
1428                 LOG.error("Couldnt retrieve connectivity context from datastore");
1429                 return;
1430             }
1431             connContext = optConnContext.get();
1432         } catch (InterruptedException | ExecutionException e) {
1433             LOG.error("Couldnt read connectivity context from datastore", e);
1434         }
1435         if (connContext == null) {
1436             LOG.error("Connectivity context is empty");
1437             return;
1438         }
1439         // Loop through services, check if the endpoint uuid is equal to the sip.
1440         // If so update state.
1441         Map<ConnectivityServiceKey, ConnectivityService> connServMap = connContext.getConnectivityService();
1442         Map<ConnectionKey, Connection> connMap = connContext.getConnection();
1443         if (connServMap != null) {
1444             for (ConnectivityService service:connServMap.values()) {
1445                 Map<EndPointKey, EndPoint> serviceEndPoints = service.getEndPoint();
1446                 if (serviceEndPoints.values().stream().anyMatch(endPoint -> endPoint.getServiceInterfacePoint()
1447                     .getServiceInterfacePointUuid().equals(sipUuid))) {
1448                     LOG.info("Service using SIP of node {} identified. Update state of service", nodeId);
1449                     ConnectivityService updService = new ConnectivityServiceBuilder(service)
1450                         .setAdministrativeState(AdministrativeState.LOCKED)
1451                         .setOperationalState(OperationalState.DISABLED)
1452                         .setLifecycleState(LifecycleState.PENDINGREMOVAL)
1453                         .build();
1454                     updateConnectivityService(updService);
1455                 }
1456             }
1457         }
1458         // Update state of connections
1459         if (connMap != null) {
1460             for (Connection connection:connMap.values()) {
1461                 if (connection.getName().values().stream().anyMatch(name -> name.getValue().contains(nodeId))) {
1462                     Connection updConn = new ConnectionBuilder(connection)
1463                         .setLifecycleState(LifecycleState.PENDINGREMOVAL)
1464                         .setOperationalState(OperationalState.DISABLED)
1465                         .build();
1466                     updateConnection(updConn);
1467                 }
1468             }
1469         }
1470     }
1471
1472     private void updateConnection(Connection updConn) {
1473         // TODO: check if this IID is correct
1474         InstanceIdentifier<Connection> connectionIID = InstanceIdentifier.builder(Context.class)
1475                 .augmentation(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.Context1.class)
1476                 .child(ConnectivityContext.class).child(Connection.class,
1477                         new ConnectionKey(updConn.getUuid())).build();
1478         this.networkTransactionService.merge(LogicalDatastoreType.OPERATIONAL, connectionIID, updConn);
1479         try {
1480             this.networkTransactionService.commit().get();
1481         } catch (InterruptedException | ExecutionException e) {
1482             LOG.error("Error committing into datastore", e);
1483         }
1484     }
1485
1486     private void updateConnectivityService(ConnectivityService updService) {
1487         // TODO: check if this IID is correct
1488         InstanceIdentifier<ConnectivityService> connectivityserviceIID = InstanceIdentifier.builder(Context.class)
1489                 .augmentation(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.Context1.class)
1490                 .child(ConnectivityContext.class).child(ConnectivityService.class,
1491                         new ConnectivityServiceKey(updService.getUuid())).build();
1492         this.networkTransactionService.merge(LogicalDatastoreType.OPERATIONAL, connectivityserviceIID, updService);
1493         try {
1494             this.networkTransactionService.commit().get();
1495         } catch (InterruptedException | ExecutionException e) {
1496             LOG.error("Error committing into datastore", e);
1497         }
1498     }
1499 }