Fix spotbugs issues of the PCE module 99/89199/1
authoratriki <ahmed.triki.tn@gmail.com>
Thu, 19 Mar 2020 22:26:29 +0000 (23:26 +0100)
committerChristophe Betoule <christophe.betoule@orange.com>
Tue, 21 Apr 2020 07:56:13 +0000 (09:56 +0200)
Fix issues related to:
- reliance on default encoding
- format and Logger Factory
- unused parameters
- bigDecimal constructor
- comparison operators
- serialization/deserialization issues
- check for null fields
- dead store for local variable
- inner static class

JIRA: TRNSPRTPCE-212
Change-Id: I82838dd72f1e42e434b9062e0166b61d22ff4c6a
Signed-off-by: atriki <ahmed.triki.tn@gmail.com>
20 files changed:
pce/src/main/java/org/opendaylight/transportpce/pce/PcePathDescription.java
pce/src/main/java/org/opendaylight/transportpce/pce/PceSendingPceRPCs.java
pce/src/main/java/org/opendaylight/transportpce/pce/SortPortsByName.java
pce/src/main/java/org/opendaylight/transportpce/pce/constraints/PceConstraints.java
pce/src/main/java/org/opendaylight/transportpce/pce/constraints/PceConstraintsCalc.java
pce/src/main/java/org/opendaylight/transportpce/pce/gnpy/ConnectToGnpyServer.java
pce/src/main/java/org/opendaylight/transportpce/pce/gnpy/GnpyResult.java
pce/src/main/java/org/opendaylight/transportpce/pce/gnpy/GnpyServiceImpl.java
pce/src/main/java/org/opendaylight/transportpce/pce/gnpy/GnpyTopoImpl.java
pce/src/main/java/org/opendaylight/transportpce/pce/gnpy/GnpyUtilitiesImpl.java
pce/src/main/java/org/opendaylight/transportpce/pce/gnpy/ServiceDataStoreOperationsImpl.java
pce/src/main/java/org/opendaylight/transportpce/pce/graph/InAlgoPathValidator.java
pce/src/main/java/org/opendaylight/transportpce/pce/graph/PceGraph.java
pce/src/main/java/org/opendaylight/transportpce/pce/graph/PostAlgoPathValidator.java
pce/src/main/java/org/opendaylight/transportpce/pce/networkanalyzer/MapUtils.java
pce/src/main/java/org/opendaylight/transportpce/pce/networkanalyzer/PceCalculation.java
pce/src/main/java/org/opendaylight/transportpce/pce/networkanalyzer/PceLink.java
pce/src/main/java/org/opendaylight/transportpce/pce/networkanalyzer/PceOpticalNode.java
pce/src/main/java/org/opendaylight/transportpce/pce/networkanalyzer/PceOtnNode.java
pce/src/main/java/org/opendaylight/transportpce/pce/service/PathComputationServiceImpl.java

index bb29feb6d4f49f9b474aa18c492af47f74f49943..ff38b749685fe29d7721622b403a41b03a7b2f4b 100644 (file)
@@ -8,9 +8,11 @@
 package org.opendaylight.transportpce.pce;
 
 import com.google.common.collect.ImmutableList;
+
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
+
 import org.opendaylight.transportpce.common.ResponseCodes;
 import org.opendaylight.transportpce.pce.networkanalyzer.PceLink;
 import org.opendaylight.transportpce.pce.networkanalyzer.PceResult;
@@ -37,16 +39,10 @@ public class PcePathDescription {
     private static final Logger LOG = LoggerFactory.getLogger(PcePathDescription.class);
 
     private List<PceLink> pathAtoZ = null;
+    private List<PceLink> pathZtoA = null;
     private PceResult rc;
-
-    public PceResult getReturnStructure() {
-        return rc;
-    }
-
     private Map<LinkId, PceLink> allPceLinks = null;
 
-    private List<PceLink> pathZtoA = null;
-
     public PcePathDescription(List<PceLink> pathAtoZ, Map<LinkId, PceLink> allPceLinks, PceResult rc) {
         super();
         this.allPceLinks = allPceLinks;
@@ -55,8 +51,8 @@ public class PcePathDescription {
     }
 
     public PceResult buildDescriptions() {
-        LOG.info("In buildDescriptions: AtoZ =  {}", pathAtoZ.toString());
-        List<AToZ> atozList = new ArrayList<AToZ>();
+        LOG.info("In buildDescriptions: AtoZ =  {}", pathAtoZ);
+        List<AToZ> atozList = new ArrayList<>();
         if (pathAtoZ == null) {
             rc.setRC(ResponseCodes.RESPONSE_FAILED);
             LOG.error("In buildDescriptions: there is empty AtoZ path");
@@ -75,9 +71,9 @@ public class PcePathDescription {
         }
         rc.setAtoZDirection(atoZDirectionBldr.build());
         pathZtoA = ImmutableList.copyOf(pathAtoZ).reverse();
-        LOG.info("In buildDescriptions: ZtoA {}", pathZtoA.toString());
+        LOG.info("In buildDescriptions: ZtoA {}", pathZtoA);
 
-        List<ZToA> ztoaList = new ArrayList<ZToA>();
+        List<ZToA> ztoaList = new ArrayList<>();
         if (pathZtoA == null) {
             rc.setRC(ResponseCodes.RESPONSE_FAILED);
             LOG.error("In buildDescriptions: there is empty ZtoA path");
@@ -114,7 +110,7 @@ public class PcePathDescription {
         Resource clientResource = new ResourceBuilder().setResource(stp).build();
         AToZ firstResource = new AToZBuilder().setId(tpName).withKey(clientKey).setResource(clientResource).build();
         etoeList.add(firstResource);
-        index++;
+        index += 1;
         for (PceLink pcelink : path) {
             String srcName = pcelink.getSourceId().getValue();
             // Nodes
@@ -127,7 +123,7 @@ public class PcePathDescription {
             AToZKey sourceKey = new AToZKey(index.toString());
             Resource nodeResource1 = new ResourceBuilder().setResource(sourceNode).build();
             AToZ srcResource = new AToZBuilder().setId(srcName).withKey(sourceKey).setResource(nodeResource1).build();
-            index++;
+            index += 1;
             etoeList.add(srcResource);
 
             // source TP
@@ -140,7 +136,7 @@ public class PcePathDescription {
             AToZKey srcTPKey = new AToZKey(index.toString());
             Resource tpResource1 = new ResourceBuilder().setResource(stp).build();
             AToZ stpResource = new AToZBuilder().setId(tpName).withKey(srcTPKey).setResource(tpResource1).build();
-            index++;
+            index += 1;
             etoeList.add(stpResource);
 
             String linkName = pcelink.getLinkId().getValue();
@@ -154,7 +150,7 @@ public class PcePathDescription {
             AToZKey linkKey = new AToZKey(index.toString());
             Resource nodeResource2 = new ResourceBuilder().setResource(atozLink).build();
             AToZ linkResource = new AToZBuilder().setId(linkName).withKey(linkKey).setResource(nodeResource2).build();
-            index++;
+            index += 1;
             etoeList.add(linkResource);
 
             String destName = pcelink.getDestId().getValue();
@@ -168,7 +164,7 @@ public class PcePathDescription {
             AToZKey destTPKey = new AToZKey(index.toString());
             Resource tpResource2 = new ResourceBuilder().setResource(dtp).build();
             AToZ ttpResource = new AToZBuilder().setId(tpName).withKey(destTPKey).setResource(tpResource2).build();
-            index++;
+            index += 1;
             etoeList.add(ttpResource);
 
             org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev171017.pce
@@ -193,8 +189,7 @@ public class PcePathDescription {
                 .setTpNodeId(xname).setTpId(tpName)
                 .build();
 
-
-        index++;
+        index += 1;
         clientKey = new AToZKey(index.toString());
         clientResource = new ResourceBuilder().setResource(stp).build();
         lastResource = new AToZBuilder().setId(tpName).withKey(clientKey).setResource(clientResource).build();
@@ -219,12 +214,12 @@ public class PcePathDescription {
         Resource clientResource = new ResourceBuilder().setResource(stp).build();
         ZToA firstResource = new ZToABuilder().setId(tpName).withKey(clientKey).setResource(clientResource).build();
         etoelist.add(firstResource);
-        index++;
+        index += 1;
 
         for (PceLink pcelinkAtoZ : path) {
 
             pcelink = this.allPceLinks.get(pcelinkAtoZ.getOppositeLink());
-            LOG.debug("link to oppsite: {} to {}", pcelinkAtoZ.toString(), pcelink.toString());
+            LOG.debug("link to oppsite: {} to {}", pcelinkAtoZ, pcelink);
 
             String srcName = pcelink.getSourceId().getValue();
 
@@ -239,7 +234,7 @@ public class PcePathDescription {
             ZToAKey sourceKey = new ZToAKey(index.toString());
             Resource nodeResource1 = new ResourceBuilder().setResource(sourceNode).build();
             ZToA srcResource = new ZToABuilder().setId(srcName).withKey(sourceKey).setResource(nodeResource1).build();
-            index++;
+            index += 1;
             etoelist.add(srcResource);
 
             // source TP
@@ -252,7 +247,7 @@ public class PcePathDescription {
             ZToAKey srcTPKey = new ZToAKey(index.toString());
             Resource tpResource1 = new ResourceBuilder().setResource(stp).build();
             ZToA stpResource = new ZToABuilder().setId(tpName).withKey(srcTPKey).setResource(tpResource1).build();
-            index++;
+            index += 1;
             etoelist.add(stpResource);
 
             String linkName = pcelink.getLinkId().getValue();
@@ -265,7 +260,7 @@ public class PcePathDescription {
             ZToAKey linkKey = new ZToAKey(index.toString());
             Resource nodeResource2 = new ResourceBuilder().setResource(ztoaLink).build();
             ZToA linkResource = new ZToABuilder().setId(linkName).withKey(linkKey).setResource(nodeResource2).build();
-            index++;
+            index += 1;
             etoelist.add(linkResource);
 
             String destName = pcelink.getDestId().getValue();
@@ -278,7 +273,7 @@ public class PcePathDescription {
             ZToAKey destTPKey = new ZToAKey(index.toString());
             Resource tpResource2 = new ResourceBuilder().setResource(ttp).build();
             ZToA ttpResource = new ZToABuilder().setId(tpName).withKey(destTPKey).setResource(tpResource2).build();
-            index++;
+            index += 1;
             etoelist.add(ttpResource);
 
 
@@ -300,13 +295,14 @@ public class PcePathDescription {
         stp = new TerminationPointBuilder()
                 .setTpNodeId(xname).setTpId(tpName).build();
 
-
-        index++;
+        index += 1;
         clientKey = new ZToAKey(index.toString());
         clientResource = new ResourceBuilder().setResource(stp).build();
         lastResource = new ZToABuilder().setId(tpName).withKey(clientKey).setResource(clientResource).build();
         etoelist.add(lastResource);
-
     }
 
+    public PceResult getReturnStructure() {
+        return rc;
+    }
 }
index 76fb7144f7808cd2a90f5c9e010fa0fe4641fccf..9ff32153d7c849105754e04b8821e631bc2372ce 100644 (file)
@@ -81,7 +81,7 @@ public class PceSendingPceRPCs {
             // sleep for 10s
             Thread.sleep(10000);
         } catch (InterruptedException e) {
-            LOG.error(e.toString());
+            LOG.error("in PCESendingPceRPC: ",e);
         }
         success = true;
         LOG.info("cancelResourceReserve ...");
@@ -95,7 +95,7 @@ public class PceSendingPceRPCs {
         rc = nwAnalizer.getReturnStructure();
         String serviceType = nwAnalizer.getServiceType();
         if (!rc.getStatus()) {
-            LOG.error("In pathComputationWithConstraints, nwAnalizer: result = {}", rc.toString());
+            LOG.error("In pathComputationWithConstraints, nwAnalizer: result = {}", rc);
             return;
         }
         LOG.info("PceGraph ...");
@@ -120,7 +120,7 @@ public class PceSendingPceRPCs {
             }
 
             if (!rc.getStatus()) {
-                LOG.error("In pathComputationWithConstraints, graph.calcPath: result = {}", rc.toString());
+                LOG.error("In pathComputationWithConstraints, graph.calcPath: result = {}", rc);
                 return;
             }
         }
@@ -129,8 +129,7 @@ public class PceSendingPceRPCs {
         description.buildDescriptions();
         rc = description.getReturnStructure();
         if (!rc.getStatus()) {
-            LOG.error("In pathComputationWithConstraints, description: result = {}", rc.toString());
-            return;
+            LOG.error("In pathComputationWithConstraints, description: result = {}", rc);
         }
     }
 
@@ -163,15 +162,12 @@ public class PceSendingPceRPCs {
                 callGnpyToComputeNewPath(gnpy);
             } else {
                 setPathDescription(new PathDescriptionBuilder().setAToZDirection(atoz).setZToADirection(ztoa));
-                return;
             }
         }
         catch (GnpyException e) {
             LOG.error("Exception raised by GNPy {}",e.getMessage());
             setPathDescription(new PathDescriptionBuilder().setAToZDirection(atoz).setZToADirection(ztoa));
-            return;
         }
-        return;
     }
 
     private boolean gnpyToCheckFeasiblity(AToZDirection atoz, ZToADirection ztoa, GnpyUtilitiesImpl gnpy)
@@ -192,7 +188,7 @@ public class PceSendingPceRPCs {
         //Call GNPy in the case of non feasibility
         LOG.info("In pceSendingPceRPC: the path is not feasible according to Gnpy");
         HardConstraints gnpyPathAsHC = null;
-        gnpyPathAsHC = gnpy.askNewPathFromGnpy(gnpyPathAsHC, pceHardConstraints);
+        gnpyPathAsHC = gnpy.askNewPathFromGnpy(pceHardConstraints);
         if (gnpyPathAsHC == null) {
             LOG.info("In pceSendingPceRPC: GNPy failed to find another path");
             this.success = false;
index 51cc05a85526d44c177fafcb00c07d644b00d817..642df21a07103f397bf825036de5986a13efcb27 100644 (file)
@@ -7,6 +7,7 @@
  */
 package org.opendaylight.transportpce.pce;
 
+import java.io.Serializable;
 import java.util.Comparator;
 
 /**
@@ -15,7 +16,9 @@ import java.util.Comparator;
  * @author Martial Coulibaly ( martial.coulibaly@gfi.com ) on behalf of Orange
  *
  */
-public class SortPortsByName implements Comparator<String> {
+public class SortPortsByName implements Comparator<String>, Serializable {
+
+    private static final long serialVersionUID = 1L;
 
     @Override
     public int compare(String port1, String port2) {
index cc05a3747d4803a97a417c6a5727bac25026c741..cfa9fd55e6c6f013da5982e48b051074ac81bc3a 100644 (file)
@@ -22,28 +22,28 @@ public class PceConstraints {
 
     // TODO. for now metrics are set into hard structure
     private RoutingConstraintsSp.PceMetric pceMetrics = RoutingConstraintsSp.PceMetric.HopCount;
-    private Long maxLatency = (long) -1;
+    private Long maxLatency = -1L;
 
     // Structure related to  EXCLUDE constraints
     // Nodes/CLLI/SRLG lists might consist of two types of elements : (1)from diversity constraints (2)from exclude list
     // e.g.: nodesToExclude - topo-level nodes IDs - comes from diversity constraints
     //     : supNodesToExclude - supporting nodes IDs - comes from exclude list
     // "mapConstraints" class converts diversity elements into correct names
-    private List<String> nodesToExclude = new ArrayList<String>();
-    private List<String> supNodesToExclude = new ArrayList<String>();
+    private List<String> nodesToExclude = new ArrayList<>();
+    private List<String> supNodesToExclude = new ArrayList<>();
 
-    private List<Long> srlgToExclude = new ArrayList<Long>();
-    private List<String> srlgLinksToExclude = new ArrayList<String>();
+    private List<Long> srlgToExclude = new ArrayList<>();
+    private List<String> srlgLinksToExclude = new ArrayList<>();
 
-    private List<String> clliToExclude = new ArrayList<String>();
-    private List<String> clliNodesToExclude = new ArrayList<String>();
+    private List<String> clliToExclude = new ArrayList<>();
+    private List<String> clliNodesToExclude = new ArrayList<>();
 
     ///Structures related to INCLUDE constraints
-    private List<String> nodesToInclude = new ArrayList<String>();
-    private List<PceOpticalNode> pceNodesToInclude = new ArrayList<PceOpticalNode>();
-    private List<ResourcePair> listToInclude = new ArrayList<ResourcePair>();
+    private List<String> nodesToInclude = new ArrayList<>();
+    private List<PceOpticalNode> pceNodesToInclude = new ArrayList<>();
+    private List<ResourcePair> listToInclude = new ArrayList<>();
 
-    private List<String> srlgNames = new ArrayList<String>();
+    private List<String> srlgNames = new ArrayList<>();
 
     public enum ResourceType {
         NONE, NODE, SRLG, CLLI;
@@ -151,11 +151,12 @@ public class PceConstraints {
     }
 
     public void setIncludePceNode(PceOpticalNode node) {
-        LOG.info("in Pceconstraints setIncludePceNode new node = {}", node.toString());
+        LOG.info("in Pceconstraints setIncludePceNode new node = {}", node);
         this.pceNodesToInclude.add(node);
     }
 
-    public class ResourcePair {
+    public static class ResourcePair {
+
         public ResourcePair(ResourceType type, String name) {
             super();
             this.type = type;
@@ -163,7 +164,6 @@ public class PceConstraints {
         }
 
         private ResourceType type = ResourceType.NODE;
-
         private String name = "";
 
         public ResourceType getType() {
index e79aa84ca859568233cc107b09cba724c995146b..0c3cc109220160edfd56c2dd5b744c6438259674 100644 (file)
@@ -14,6 +14,7 @@ import java.util.concurrent.ExecutionException;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
 import java.util.stream.Collectors;
+
 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
 import org.opendaylight.transportpce.common.Timeouts;
 import org.opendaylight.transportpce.common.network.NetworkTransactionService;
@@ -39,7 +40,6 @@ import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.service
 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.servicepath.rev171017.service.path.list.ServicePaths;
 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.servicepath.rev171017.service.path.list.ServicePathsKey;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -60,7 +60,7 @@ public class PceConstraintsCalc {
         this.networkTransactionService = networkTransactionService;
 
         // TODO. for now metrics are set into hard structure
-        LOG.info("In PceConstraintsCalc: read PceMetric {}", pceMetrics.toString());
+        LOG.info("In PceConstraintsCalc: read PceMetric {}", pceMetrics);
         pceHardConstraints.setPceMetrics(pceMetrics);
 
         calcHardconstraints(input);
@@ -103,21 +103,17 @@ public class PceConstraintsCalc {
         CoRouting tmpCoRouting = null;
 
         if (coRoutingOrGeneral instanceof General) {
-            LOG.info("In readconstraints General {}", coRoutingOrGeneral.toString());
+            LOG.info("In readconstraints General {}", coRoutingOrGeneral);
             tmpGeneral = (General) coRoutingOrGeneral;
             readGeneralContrains(tmpGeneral, constraints);
             return;
         }
 
         if (coRoutingOrGeneral instanceof CoRouting) {
-            LOG.info("In readconstraints CoRouting {}", coRoutingOrGeneral.toString());
+            LOG.info("In readconstraints CoRouting {}", coRoutingOrGeneral);
             tmpCoRouting = (CoRouting) coRoutingOrGeneral;
             readCoRoutingContrains(tmpCoRouting, constraints);
-            return;
         }
-
-        return;
-
     }
 
     private void readGeneralContrains(General tmpGeneral, PceConstraints constraints) {
@@ -131,7 +127,7 @@ public class PceConstraintsCalc {
         Latency latency = tmpGeneral.getLatency();
         if (latency != null) {
             constraints.setMaxLatency(latency.getMaxLatency().toJava());
-            LOG.info("In readGeneralContrains: read latency {}", latency.toString());
+            LOG.info("In readGeneralContrains: read latency {}", latency);
         }
 
         Exclude exclude = tmpGeneral.getExclude();
@@ -144,7 +140,7 @@ public class PceConstraintsCalc {
 
             elementsToExclude = exclude.getSRLG();
             if (elementsToExclude != null) {
-                List<Long> srlgToExclude = new ArrayList<Long>();
+                List<Long> srlgToExclude = new ArrayList<>();
                 for (String str : elementsToExclude) {
                     srlgToExclude.add(Long.parseLong(str));
                 }
@@ -163,7 +159,7 @@ public class PceConstraintsCalc {
             if (listHops != null) {
                 readIncludeNodes(listHops, constraints);
             }
-            LOG.debug("in readGeneralContrains INCLUDE {} ", include.toString());
+            LOG.debug("in readGeneralContrains INCLUDE {} ", include);
         }
 
         Diversity diversity = tmpGeneral.getDiversity();
@@ -173,16 +169,16 @@ public class PceConstraintsCalc {
             if (temp == null) {
                 return;
             }
-            if (temp.isNode()) {
+            if (Boolean.TRUE.equals(temp.isNode())) {
                 rt = PceConstraints.ResourceType.NODE;
             }
-            if (temp.isSrlg()) {
+            if (Boolean.TRUE.equals(temp.isSrlg())) {
                 rt = PceConstraints.ResourceType.SRLG;
             }
-            if (temp.isClli()) {
+            if (Boolean.TRUE.equals(temp.isClli())) {
                 rt = PceConstraints.ResourceType.CLLI;
             }
-            LOG.info("in readGeneralContrains {} list is :{}", rt, diversity.toString());
+            LOG.info("in readGeneralContrains {} list is :{}", rt, diversity);
             readDiversity(diversity.getExistingService(), constraints, rt);
         }
 
@@ -200,7 +196,7 @@ public class PceConstraintsCalc {
                             .rev171017.ordered.constraints.sp.hop.type.hop.type.Node
                             node = (org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing
                             .constraints.rev171017.ordered.constraints.sp.hop.type.hop.type.Node) hoptype;
-                    constraints.setListToInclude(constraints.new ResourcePair(PceConstraints.ResourceType.NODE,
+                    constraints.setListToInclude(new PceConstraints.ResourcePair(PceConstraints.ResourceType.NODE,
                             node.getNodeId()));
                     break;
                 case "SRLG":
@@ -208,7 +204,7 @@ public class PceConstraintsCalc {
                             .rev171017.ordered.constraints.sp.hop.type.hop.type.SRLG
                             srlg = (org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing
                             .constraints.rev171017.ordered.constraints.sp.hop.type.hop.type.SRLG) hoptype;
-                    constraints.setListToInclude(constraints.new ResourcePair(PceConstraints.ResourceType.SRLG,
+                    constraints.setListToInclude(new PceConstraints.ResourcePair(PceConstraints.ResourceType.SRLG,
                             srlg.getSRLG()));
                     break;
                 case "Clli":
@@ -216,7 +212,7 @@ public class PceConstraintsCalc {
                             .rev171017.ordered.constraints.sp.hop.type.hop.type.Clli
                             clli = (org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing
                             .constraints.rev171017.ordered.constraints.sp.hop.type.hop.type.Clli) hoptype;
-                    constraints.setListToInclude(constraints.new ResourcePair(PceConstraints.ResourceType.CLLI,
+                    constraints.setListToInclude(new PceConstraints.ResourcePair(PceConstraints.ResourceType.CLLI,
                             clli.getClli()));
                     break;
                 default:
@@ -227,25 +223,23 @@ public class PceConstraintsCalc {
 
     private void readDiversity(List<String> srvList, PceConstraints constraints, PceConstraints.ResourceType rt) {
 
-        List<String> elementsToExclude = new ArrayList<String>();
-        LOG.info("in readDiversity {}", srvList.toString());
+        List<String> elementsToExclude = new ArrayList<>();
+        LOG.info("in readDiversity {}", srvList);
 
         for (String srv : srvList) {
             Optional<PathDescription> service = getPathDescriptionFromDatastore(srv);
             if (service.isPresent()) {
-                LOG.info("in readDiversity service list {}", service.toString());
+                LOG.info("in readDiversity service list {}", service);
                 switch (rt) {
                     case NODE:
-                        elementsToExclude
-                                .addAll(getAToZNodeList(service.get()));
+                        elementsToExclude.addAll(getAToZNodeList(service.get()));
                         LOG.info("readDiversity NODE : {}", elementsToExclude);
                         if (elementsToExclude != null) {
                             constraints.setExcludeNodes(elementsToExclude);
                         }
                         break;
                     case SRLG:
-                        elementsToExclude
-                                .addAll(getSRLGList(service.get()));
+                        elementsToExclude.addAll(getSRLGList(service.get()));
                         LOG.info("readDiversity SRLG : {}", elementsToExclude);
                         if (elementsToExclude != null) {
                             constraints.setExcludeSrlgLinks(elementsToExclude);
@@ -254,8 +248,7 @@ public class PceConstraintsCalc {
                     case CLLI:
                         /// Retrieve nodes into dedicated CLLI list
                         /// during node validation check their CLLI and build CLLI exclude list
-                        elementsToExclude
-                                .addAll(getAToZNodeList(service.get()));
+                        elementsToExclude.addAll(getAToZNodeList(service.get()));
                         LOG.info("readDiversity CLLI : {}", elementsToExclude);
                         if (elementsToExclude != null) {
                             constraints.setExcludeClliNodes(elementsToExclude);
@@ -343,7 +336,6 @@ public class PceConstraintsCalc {
 
         if (tmpcoRouting == null) {
             LOG.info("In readCoRoutingContrains: no General constraints.");
-            return;
         }
 
     }
index 5c88fab8c469ecfdff93f97cda3800ca561a52ce..42365f99c6dbb89ed3b568f3b1caaa7ca41a3649 100644 (file)
@@ -16,6 +16,8 @@ import java.io.InputStreamReader;
 import java.io.OutputStream;
 import java.net.HttpURLConnection;
 import java.net.URL;
+import java.nio.charset.StandardCharsets;
+
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -30,31 +32,23 @@ public class ConnectToGnpyServer {
 
     private static final Logger LOG = LoggerFactory.getLogger(ConnectToGnpyServer.class);
     static final String URL_GNPY = "http://127.0.0.1:8008/gnpy/api/v1.0/files";
+    static final String USER_CRED = "gnpy:gnpy";
 
-    public String gnpyCnx(String jsonTxt) throws GnpyException  {
+    public String returnGnpyResponse(String jsonTxt) throws GnpyException  {
         String jsonRespTxt = null;
 
         try {
-            URL url = new URL(URL_GNPY);
-            String userCredentials = "gnpy:gnpy";
-            String basicAuth = "Basic " + new String(java.util.Base64.getEncoder().encode(userCredentials.getBytes()));
-
-            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
-            conn.setDoOutput(true);
-            conn.setRequestMethod("POST");
-            conn.setRequestProperty("Authorization", basicAuth);
-            conn.setRequestProperty("Content-Type", "application/json");
-
             // Send the request to the GNPy
+            HttpURLConnection conn = connectToGNPy("POST");
             OutputStream os = conn.getOutputStream();
-            os.write(jsonTxt.getBytes());
+            os.write(jsonTxt.getBytes(StandardCharsets.UTF_8));
             os.flush();
             if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
                 throw new GnpyException(String.format(
                     "In connectToGnpyServer: could not connect to GNPy - response code: %s",conn.getResponseCode()));
             }
-            InputStreamReader response = new InputStreamReader((conn.getInputStream()));
-            if (response != null) {
+            InputStreamReader response = new InputStreamReader((conn.getInputStream()),StandardCharsets.UTF_8);
+            if (response.ready()) {
                 jsonRespTxt = CharStreams.toString(response);
             }
             conn.disconnect();
@@ -67,14 +61,7 @@ public class ConnectToGnpyServer {
     public boolean isGnpyURLExist() {
         boolean exist = false;
         try {
-            URL url = new URL(URL_GNPY);
-            String userCredentials = "gnpy:gnpy";
-            String basicAuth = "Basic " + new String(java.util.Base64.getEncoder().encode(userCredentials.getBytes()));
-            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
-            conn.setDoOutput(true);
-            conn.setRequestMethod("HEAD");
-            conn.setRequestProperty("Authorization", basicAuth);
-            conn.setRequestProperty("Content-Type", "application/json");
+            HttpURLConnection conn = connectToGNPy("HEAD");
             conn.connect();
             if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                 LOG.info("In connectToGnpyServer: Gnpy instance is connected to T-PCE");
@@ -89,6 +76,19 @@ public class ConnectToGnpyServer {
         return exist;
     }
 
+    private HttpURLConnection connectToGNPy(String action) throws IOException {
+        URL url = new URL(URL_GNPY);
+        String basicAuth = "Basic " + new String(java.util.Base64.getEncoder()
+            .encode(USER_CRED.getBytes(StandardCharsets.UTF_8)),StandardCharsets.UTF_8);
+        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+        conn.setDoOutput(true);
+        conn.setRequestMethod(action);
+        conn.setRequestProperty("Authorization", basicAuth);
+        conn.setRequestProperty("Content-Type", "application/json");
+        conn.connect();
+        return conn;
+    }
+
     public String readResponse(InputStreamReader response) throws GnpyException {
         String output = null;
         BufferedReader br = new BufferedReader(response);
index df797ed837a7574e778194c623a0afc531001a92..829c50df41cefbecb9b3a40dee73ebeac1f01715 100644 (file)
@@ -23,8 +23,8 @@ import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Optional;
-import java.util.Set;
 
 import javax.annotation.Nonnull;
 
@@ -67,7 +67,6 @@ import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -82,8 +81,7 @@ public class GnpyResult {
 
     private static final Logger LOG = LoggerFactory.getLogger(GnpyResult.class);
     private Response response = null;
-    private Map<String, IpAddress> mapNodeRefIp = new HashMap<String, IpAddress>();
-    //private Map<String, IpAddress> mapFiberIp = new HashMap<String, IpAddress>();
+    private Map<String, IpAddress> mapNodeRefIp = new HashMap<>();
 
     public GnpyResult(String gnpyResponseString, GnpyTopoImpl gnpyTopo) throws GnpyException, Exception {
         this.mapNodeRefIp = gnpyTopo.getMapNodeRefIp();
@@ -93,7 +91,6 @@ public class GnpyResult {
 
         moduleInfos = Collections.singleton(BindingReflections.getModuleInfo(Result.class));
         moduleContext.addModuleInfos(moduleInfos);
-
         SchemaContext schemaContext = moduleContext.tryToCreateSchemaContext().get();
 
         // Create the binding binding normalized node codec registry
@@ -103,22 +100,26 @@ public class GnpyResult {
 
         // Create the data object
         QName pathQname = QName.create("gnpy:path", "2020-02-02", "result");
-        LOG.debug("the Qname is {} / namesapce {} ; module {}; ", pathQname.toString(), pathQname.getNamespace(),
+        LOG.debug("the Qname is {} / namesapce {} ; module {}; ", pathQname, pathQname.getNamespace(),
             pathQname.getModule());
         YangInstanceIdentifier yangId = YangInstanceIdentifier.of(pathQname);
         DataObject dataObject = null;
 
         // Create the object response
         InputStream streamGnpyRespnse = new ByteArrayInputStream(gnpyResponseString.getBytes(StandardCharsets.UTF_8));
-        InputStreamReader gnpyResultReader = new InputStreamReader(streamGnpyRespnse);
+        InputStreamReader gnpyResultReader = new InputStreamReader(streamGnpyRespnse,StandardCharsets.UTF_8);
         JsonReader jsonReader = new JsonReader(gnpyResultReader);
         Optional<NormalizedNode<? extends PathArgument, ?>> transformIntoNormalizedNode = parseInputJSON(jsonReader,
             Result.class);
+        if (!transformIntoNormalizedNode.isPresent()) {
+            throw new GnpyException("In GnpyResult: the Normalized Node is not present");
+        }
         NormalizedNode<? extends PathArgument, ?> normalizedNode = transformIntoNormalizedNode.get();
+
         if (codecRegistry.fromNormalizedNode(yangId, normalizedNode) != null) {
             dataObject = codecRegistry.fromNormalizedNode(yangId, normalizedNode).getValue();
         } else {
-            throw new GnpyException("In GnpyResult: the codec registry from the normalized node is null!");
+            throw new GnpyException("In GnpyResult: the codec registry from the normalized node is null");
         }
         List<Response> responses = null;
         responses = ((Result) dataObject).getResponse();
@@ -134,7 +135,6 @@ public class GnpyResult {
         boolean isFeasible = false;
         if (response != null) {
             if (response.getResponseType() instanceof NoPathCase) {
-                isFeasible = false;
                 LOG.info("In GnpyResult: The path is not feasible ");
             } else if (response.getResponseType() instanceof PathCase) {
                 isFeasible = true;
@@ -217,13 +217,11 @@ public class GnpyResult {
     }
 
     private String findOrdNetworkNodeId(IpAddress nodeIpAddress) {
-        String nodeId;
-        Set<String> keySet = this.mapNodeRefIp.keySet();
-        Iterator<String> it = keySet.iterator();
+        Iterator<Map.Entry<String,IpAddress>> it = this.mapNodeRefIp.entrySet().iterator();
         while (it.hasNext()) {
-            nodeId = it.next();
-            if (this.mapNodeRefIp.get(nodeId).equals(nodeIpAddress)) {
-                return nodeId;
+            Entry<String, IpAddress> entry = it.next();
+            if (entry.getValue().equals(nodeIpAddress)) {
+                return entry.getKey();
             }
         }
         return null;
@@ -274,7 +272,7 @@ public class GnpyResult {
     public <T extends DataObject> Optional<T> getDataObject(@Nonnull NormalizedNode<?, ?> normalizedNode,
         @Nonnull QName rootNode, BindingNormalizedNodeSerializer codecRegistry) {
         if (normalizedNode != null) {
-            LOG.debug("GNPy: The codecRegistry is {}", codecRegistry.toString());
+            LOG.debug("GNPy: The codecRegistry is {}", codecRegistry);
         } else {
             LOG.warn("GNPy: The codecRegistry is null");
         }
@@ -291,7 +289,7 @@ public class GnpyResult {
             LOG.debug("GNPy: the normalized node is {}", normalizedNode.getNodeType());
         }
         YangInstanceIdentifier rootNodeYangInstanceIdentifier = YangInstanceIdentifier.of(rootNode);
-        LOG.debug("GNPy: the root Node Yang Instance Identifier is {}", rootNodeYangInstanceIdentifier.toString());
+        LOG.debug("GNPy: the root Node Yang Instance Identifier is {}", rootNodeYangInstanceIdentifier);
         Map.Entry<?, ?> bindingNodeEntry = codecRegistry.fromNormalizedNode(rootNodeYangInstanceIdentifier,
             normalizedNode);
         if (bindingNodeEntry == null) {
index 2bf8dfb6586bb7221b8681ac018b7d87bc06a0c5..a1ccc29f733d049f5e9bf27a380ffa8ef4a5d7d3 100644 (file)
@@ -9,6 +9,7 @@
 package org.opendaylight.transportpce.pce.gnpy;
 
 import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Iterator;
@@ -63,23 +64,28 @@ import org.slf4j.LoggerFactory;
 
 public class GnpyServiceImpl {
     private static final Logger LOG = LoggerFactory.getLogger(GnpyServiceImpl.class);
-    private static final double FIX_CH = 0.05; //Fix-grid channel width (THz)
-    private static final int NB_SLOT_BW = 4; //Number of slot in 50GHz channel (THz)
-    private static final double SLOT_BW = 0.00625; //Nominal central frequency granularity (THz)
-    private static final double MAX_CENTRAL_FREQ = 196.1; //Minimum channel center frequency (openRoadm spec) (THz)
-    private static final double FLEX_CENTRAL_FREQ = 193.1; //Flex-grid reference channel frequency (THz)
-    private static final double CONVERT_TH_HZ = 1e12; //Convert THz to Hz
+  //Fix-grid channel width (THz)
+    private static final double FIX_CH = 0.05;
+  //Number of slot in 50GHz channel (THz)
+    private static final int NB_SLOT_BW = 4;
+  //Nominal central frequency granularity (THz)
+    private static final double SLOT_BW = 0.00625;
+  //Minimum channel center frequency (openRoadm spec) (THz)
+    private static final double MAX_CENTRAL_FREQ = 196.1;
+  //Flex-grid reference channel frequency (THz)
+    private static final double FLEX_CENTRAL_FREQ = 193.1;
+  //Convert THz to Hz
+    private static final double CONVERT_TH_HZ = 1e12;
 
     private List<PathRequest> pathRequest = new ArrayList<>();
     private List<Synchronization> synchronization = new ArrayList<>();
-    private Map<String, String> mapDisgNodeRefNode = new HashMap<String, String>();
-    private Map<String, IpAddress> mapNodeRefIp = new HashMap<String, IpAddress>();
-    private Map<String, List<String>> mapLinkFiber = new HashMap<String, List<String>>();
-    private Map<String, IpAddress> mapFiberIp = new HashMap<String, IpAddress>();
+    private Map<String, String> mapDisgNodeRefNode = new HashMap<>();
+    private Map<String, IpAddress> mapNodeRefIp = new HashMap<>();
+    private Map<String, List<String>> mapLinkFiber = new HashMap<>();
+    private Map<String, IpAddress> mapFiberIp = new HashMap<>();
     private List<String> trxList = new ArrayList<>();
     private List<Elements> elements = new ArrayList<>();
     private List<RouteObjectIncludeExclude> routeObjectIncludeExcludes = new ArrayList<>();
-    private Long index = (long) 0; //index of the element in the path
     private IpAddress currentNodeIpAddress = null;
 
     /*
@@ -147,7 +153,8 @@ public class GnpyServiceImpl {
         List<PathRequest> pathRequestList = new ArrayList<>();
         PathRequest pathRequestEl = new PathRequestBuilder().setRequestId(requestId)
             .setSource(this.mapNodeRefIp.get(sourceNode)).setDestination(this.mapNodeRefIp.get(destNode))
-            .setSrcTpId("srcTpId".getBytes()).setDstTpId("dstTpId".getBytes())
+            .setSrcTpId("srcTpId".getBytes(StandardCharsets.UTF_8))
+            .setDstTpId("dstTpId".getBytes(StandardCharsets.UTF_8))
             .setBidirectional(false).setPathConstraints(pathConstraints).setPathConstraints(pathConstraints)
             .setExplicitRouteObjects(explicitRouteObjects).build();
         pathRequestList.add(pathRequestEl);
@@ -183,7 +190,8 @@ public class GnpyServiceImpl {
         List<PathRequest> pathRequestList = new ArrayList<>();
         PathRequest pathRequestEl = new PathRequestBuilder().setRequestId(requestId)
             .setSource(this.mapNodeRefIp.get(sourceNode)).setDestination(this.mapNodeRefIp.get(destNode))
-            .setSrcTpId("srcTpId".getBytes()).setDstTpId("dstTpId".getBytes())
+            .setSrcTpId("srcTpId".getBytes(StandardCharsets.UTF_8))
+            .setDstTpId("dstTpId".getBytes(StandardCharsets.UTF_8))
             .setBidirectional(false).setPathConstraints(pathConstraints)
             .setExplicitRouteObjects(explicitRouteObjects).build();
         pathRequestList.add(pathRequestEl);
@@ -193,20 +201,23 @@ public class GnpyServiceImpl {
 
     //Extract RouteObjectIncludeExclude list in the case of pre-computed path A-to-Z
     private void extractRouteObjectIcludeAtoZ(List<AToZ> listAtoZ) throws GnpyException {
+        Long index = 0L;
         for (int i = 0; i < listAtoZ.size(); i++) {
-            createResource(listAtoZ.get(i).getResource().getResource());
+            index = createResource(listAtoZ.get(i).getResource().getResource(),index);
         }
     }
 
     //Extract RouteObjectIncludeExclude list in the case of pre-computed path Z-to-A
     private void extractRouteObjectIcludeZtoA(List<ZToA> listZtoA) throws GnpyException {
+        Long index = 0L;
         for (int i = 0; i < listZtoA.size(); i++) {
-            createResource(listZtoA.get(i).getResource().getResource());
+            index = createResource(listZtoA.get(i).getResource().getResource(),index);
         }
     }
 
     //Create a new resource node or link
-    private void createResource(@Nullable Resource resource) throws GnpyException {
+    private Long createResource(@Nullable Resource resource, Long index) throws GnpyException {
+        Long idx = index;
         if (resource
             instanceof
                 org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev171017
@@ -218,8 +229,7 @@ public class GnpyServiceImpl {
             if (node.getNodeId() == null) {
                 throw new GnpyException("In gnpyServiceImpl: nodeId is null");
             }
-            addNodeToRouteObject(this.mapDisgNodeRefNode.get(node.getNodeId()));
-            return;
+            idx = addNodeToRouteObject(this.mapDisgNodeRefNode.get(node.getNodeId()),idx);
         }
 
         if (resource
@@ -230,18 +240,19 @@ public class GnpyServiceImpl {
                 .pce.resource.resource.resource.Link link =
                 (org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev171017
                     .pce.resource.resource.resource.Link) resource;
-            addLinkToRouteObject(link.getLinkId());
-            return;
+            idx = addLinkToRouteObject(link.getLinkId(),idx);
         }
+        return idx;
     }
 
     //Create RouteObjectIncludeExclude list in the case of hard constraint
     private void extractHardConstraints(PceConstraints pceHardConstraints) throws GnpyException {
         List<String> listNodeToInclude = getListToInclude(pceHardConstraints);
-        if (listNodeToInclude != null) {
+        if (!listNodeToInclude.isEmpty()) {
+            Long index = 0L;
             for (int i = 0; i < listNodeToInclude.size(); i++) {
                 String nodeId = listNodeToInclude.get(i);
-                addNodeToRouteObject(nodeId);
+                index = addNodeToRouteObject(nodeId, index);
             }
         }
     }
@@ -263,8 +274,8 @@ public class GnpyServiceImpl {
     }
 
     //Add a node to the route object
-    private void addNodeToRouteObject(String nodeRef) throws GnpyException {
-        boolean found = false;
+    private Long addNodeToRouteObject(String nodeRef, Long index) throws GnpyException {
+        Long idx = index;
         IpAddress ipAddress = this.mapNodeRefIp.get(nodeRef);
         if (ipAddress == null) {
             throw new GnpyException(String.format("In gnpyServiceImpl : NodeRef %s does not exist", nodeRef));
@@ -272,30 +283,28 @@ public class GnpyServiceImpl {
 
         for (Elements element : this.elements) {
             if (element.getUid().contains(ipAddress.getIpv4Address().getValue())) {
-                if ((this.currentNodeIpAddress == null) || (this.currentNodeIpAddress != ipAddress)) {
+                if ((this.currentNodeIpAddress == null) || (!this.currentNodeIpAddress.equals(ipAddress))) {
                     this.currentNodeIpAddress = ipAddress;
                     RouteObjectIncludeExclude routeObjectIncludeExclude =
-                        addRouteObjectIncludeExclude(ipAddress, Uint32.valueOf(1));
+                        addRouteObjectIncludeExclude(ipAddress, Uint32.valueOf(1),idx);
                     routeObjectIncludeExcludes.add(routeObjectIncludeExclude);
-                    index++;
-                    found = true;
+                    idx += 1;
                 }
-                return;
+                return idx;
             }
         }
-        if (!found) {
-            throw new GnpyException(String.format("In gnpyServiceImpl : NodeRef %s does not exist",nodeRef));
-        }
+        throw new GnpyException(String.format("In gnpyServiceImpl : NodeRef %s does not exist",nodeRef));
     }
 
     //Add a link to the route object
-    private void addLinkToRouteObject(String linkId) throws GnpyException {
+    private Long addLinkToRouteObject(String linkId, Long index) throws GnpyException {
+        Long idx = index;
         if (linkId == null) {
-            throw new GnpyException(String.format("In GnpyServiceImpl: the linkId does not exist"));
+            throw new GnpyException("In GnpyServiceImpl: the linkId is null");
         }
         //Only the ROADM-to-ROADM link are included in the route object
         if (!mapLinkFiber.containsKey(linkId)) {
-            return;
+            return idx;
         }
         List<String> listSubLink = this.mapLinkFiber.get(linkId);
         if (listSubLink == null) {
@@ -308,14 +317,15 @@ public class GnpyServiceImpl {
                     subLink));
             }
             RouteObjectIncludeExclude routeObjectIncludeExclude =
-                addRouteObjectIncludeExclude(fiberIp, Uint32.valueOf(1));
+                addRouteObjectIncludeExclude(fiberIp, Uint32.valueOf(1),idx);
             routeObjectIncludeExcludes.add(routeObjectIncludeExclude);
-            index++;
+            idx += 1;
         }
+        return idx;
     }
 
     // Add routeObjectIncludeExclude
-    private RouteObjectIncludeExclude addRouteObjectIncludeExclude(IpAddress ipAddress, Uint32 teTpValue) {
+    private RouteObjectIncludeExclude addRouteObjectIncludeExclude(IpAddress ipAddress, Uint32 teTpValue, Long index) {
         TeNodeId teNodeId = new TeNodeId(ipAddress);
         TeTpId teTpId = new TeTpId(teTpValue);
         NumUnnumHop numUnnumHop = new org.opendaylight.yang.gen.v1.gnpy.path.rev200202.explicit.route.hop.type.num
@@ -325,9 +335,8 @@ public class GnpyServiceImpl {
                 .setHopType(TeHopType.STRICT).build();
         Type type1 = new NumUnnumHopBuilder().setNumUnnumHop(numUnnumHop).build();
         // Create routeObjectIncludeExclude element
-        RouteObjectIncludeExclude routeObjectIncludeExclude = new RouteObjectIncludeExcludeBuilder()
-            .setIndex(this.index).setExplicitRouteUsage(RouteIncludeEro.class).setType(type1).build();
-        return routeObjectIncludeExclude;
+        return new RouteObjectIncludeExcludeBuilder()
+            .setIndex(index).setExplicitRouteUsage(RouteIncludeEro.class).setType(type1).build();
     }
 
     //Create the path constraints
@@ -345,9 +354,8 @@ public class GnpyServiceImpl {
         TeBandwidth teBandwidth = new TeBandwidthBuilder().setPathBandwidth(new BigDecimal(rate))
             .setTechnology("flexi-grid").setTrxType("openroadm-beta1")
             .setTrxMode("W100G").setEffectiveFreqSlot(effectiveFreqSlot)
-            .setSpacing(new BigDecimal(FIX_CH * CONVERT_TH_HZ)).build();
-        PathConstraints pathConstraints = new PathConstraintsBuilder().setTeBandwidth(teBandwidth).build();
-        return pathConstraints;
+            .setSpacing(BigDecimal.valueOf(FIX_CH * CONVERT_TH_HZ)).build();
+        return new PathConstraintsBuilder().setTeBandwidth(teBandwidth).build();
     }
 
     //Create the synchronization
index 1b3c41e9249f1c432971f29cd19058617a95812d..d880ab9439032074c2ab1841f2918e966ee374f0 100644 (file)
@@ -81,13 +81,13 @@ public class GnpyTopoImpl {
     private List<Connections> connections = new ArrayList<>();
     //Mapping elements
     //Mapping between the ord-topo and ord-ntw node
-    private Map<String, String> mapDisgNodeRefNode = new HashMap<String, String>();
+    private Map<String, String> mapDisgNodeRefNode = new HashMap<>();
     //Mapping between the ord-ntw and node ip
-    private Map<String, IpAddress> mapNodeRefIp = new HashMap<String, IpAddress>();
+    private Map<String, IpAddress> mapNodeRefIp = new HashMap<>();
     //Mapping between the ROADM-ROADM linkId/secElement and the linkId
-    private Map<String, List<String>> mapLinkFiber = new HashMap<String, List<String>>();
+    private Map<String, List<String>> mapLinkFiber = new HashMap<>();
     //Mapping between the ROADM-ROADM linkId/secElement and ipAddress
-    private Map<String, IpAddress> mapFiberIp = new HashMap<String, IpAddress>();
+    private Map<String, IpAddress> mapFiberIp = new HashMap<>();
     //List of Xponders
     private List<String> trxList = new ArrayList<>();
     //Initialize the 32 bit identifiers for the edfa and the fiber.
@@ -141,7 +141,7 @@ public class GnpyTopoImpl {
                     .read(LogicalDatastoreType.CONFIGURATION, insIdrOpenRoadmNet).get();
             if (openRoadmNet.isPresent() && openRoadmTopo.isPresent()) {
                 extractElements(openRoadmTopo,openRoadmNet);
-                extractConnections(openRoadmTopo,openRoadmNet);
+                extractConnections(openRoadmTopo);
                 LOG.debug("In GnpyTopoImpl : elements and connections are well extracted");
             }
             else {
@@ -157,6 +157,9 @@ public class GnpyTopoImpl {
 
     private void extractElements(java.util.Optional<Network> openRoadmTopo,
             java.util.Optional<Network> openRoadmNet) throws GnpyException {
+        if ((!openRoadmNet.isPresent()) || (!openRoadmTopo.isPresent())) {
+            throw new GnpyException("In gnpyTopoImpl: openRoadmNet or openRoadmTopo is not present");
+        }
         // Create the list of nodes
         List<Node> openRoadmNetNodeList = openRoadmNet.get().getNode();
         List<Node> openRoadmTopoNodeList = openRoadmTopo.get().getNode();
@@ -176,6 +179,9 @@ public class GnpyTopoImpl {
                 }
                 IpAddress ipAddress = null;
                 String nodeRef = supportingNode.getNodeRef().getValue();
+                if (nodeRef == null) {
+                    throw new GnpyException("In gnpyTopoImpl: nodeRef is null");
+                }
                 // Retrieve the mapping between the openRoadm topology and openRoadm network
                 mapDisgNodeRefNode.put(openRoadmTopoNode.getNodeId().getValue(), nodeRef);
                 Node1 openRoadmNetNode1 = null;
@@ -187,10 +193,17 @@ public class GnpyTopoImpl {
                         commonNetworkNode1 = openRoadmNetNode.augmentation(org.opendaylight.yang.gen.v1
                             .http.org.openroadm.common.network.rev181130.Node1.class);
                         ipAddress = openRoadmNetNode1.getIp();
+                        if (ipAddress == null) {
+                            throw new GnpyException(String.format(
+                                "In gnpyTopoImpl: ipAddress of node %s is null",nodeRef));
+                        }
                         mapNodeRefIp.put(nodeRef, ipAddress);
                         break;
                     }
                 }
+                if (commonNetworkNode1 == null) {
+                    throw new GnpyException(String.format("In gnpyTopoImpl: the node type of %s is null",nodeRef));
+                }
                 if (commonNetworkNode1.getNodeType().getName().equals("ROADM")) {
                     if (!nodesList.contains(nodeRef)) {
                         Elements element = createElementsRoadm(LATITUDE, LONGITUTE, nodeRef,
@@ -213,9 +226,11 @@ public class GnpyTopoImpl {
         }
     }
 
-    private void extractConnections(java.util.Optional<Network> openRoadmTopo,
-            java.util.Optional<Network> openRoadmNet) throws GnpyException {
+    private void extractConnections(java.util.Optional<Network> openRoadmTopo) throws GnpyException {
         // Create the list of connections
+        if (!openRoadmTopo.isPresent()) {
+            throw new GnpyException("In gnpyTopoImpl: openroadmTopo is not present");
+        }
         Network1 nw1 = openRoadmTopo.get().augmentation(Network1.class);
         List<Link> linksList = nw1.getLink();
         // 1:EXPRESS-LINK    2:ADD-LINK       3:DROP-LINK
@@ -232,6 +247,9 @@ public class GnpyTopoImpl {
             org.opendaylight.yang.gen.v1.http.org.openroadm.network.topology.rev181130
                 .Link1 openroadmNetworkLink1 = link.augmentation(org.opendaylight.yang.gen.v1.http.org
                 .openroadm.network.topology.rev181130.Link1.class);
+            if (link1.getLinkType() == null) {
+                throw new GnpyException("In gnpyTopoImpl: the link type is null");
+            }
             int linkType = link1.getLinkType().getIntValue();
             if (! IntStream.of(externalLink).anyMatch(x -> x == linkType)) {
                 continue;
@@ -281,7 +299,7 @@ public class GnpyTopoImpl {
                 //Case of Span
                 if (amplifiedLink.getSectionElement().getSectionElement() instanceof Span) {
                     Span span = (Span) amplifiedLink.getSectionElement().getSectionElement();
-                    destIp = extractSpan((SpanAttributes) span.getSpan(), linkId, secElt);
+                    destIp = extractSpan(span.getSpan(), linkId, secElt);
                 }
                 // Create a new link
                 if (createNewConnection(srcIp,destIp)) {
@@ -296,7 +314,7 @@ public class GnpyTopoImpl {
         throws GnpyException {
 
         SpanAttributes span = omsAttributes.getSpan();
-        IpAddress destIp = extractSpan((SpanAttributes) span, linkId, linkId);
+        IpAddress destIp = extractSpan(span, linkId, linkId);
         if (createNewConnection(srcIp, destIp)) {
             return destIp;
         }
@@ -338,6 +356,10 @@ public class GnpyTopoImpl {
             //convert to kilometer
             length += srlgLength / CONVERT_KM_M;
         }
+        if (length == 0) {
+            throw new GnpyException(String.format(
+                "In gnpyTopoImpl: length of the link %s is equal to zero",linkId));
+        }
         double lossCoef = span.getSpanlossCurrent().getValue().doubleValue() / length;
         Elements element = createElementsFiber(LATITUDE, LONGITUTE, REGION, CITY,
             ipFiber.getIpv4Address().getValue(), length, attIn, lossCoef, connIn, connOut, typeVariety);
@@ -352,20 +374,20 @@ public class GnpyTopoImpl {
     private Elements createElementsFiber(double latitude, double longitude, String region, String city, String uidFiber,
             double length, double attIn, double lossCoef, double connIn, double connOut, String typeVariety) {
         // Create an amplifier after the ROADM
-        Coordinate c1 = new Coordinate(new BigDecimal(latitude));
-        Coordinate c2 = new Coordinate(new BigDecimal(longitude));
+        Coordinate c1 = new Coordinate(BigDecimal.valueOf(latitude));
+        Coordinate c2 = new Coordinate(BigDecimal.valueOf(longitude));
         Location location1 = new LocationBuilder().setRegion(region).setCity(city).setLatitude(c1).setLongitude(c2)
                 .build();
         Metadata metadata1 = new MetadataBuilder().setLocation(location1).build();
-        Fiber fiber = new FiberBuilder().setLength(new BigDecimal(length)).setLengthUnits(Km.class)
-                .setAttIn(new BigDecimal(attIn)).setLossCoef(new BigDecimal(lossCoef)).setConIn(new BigDecimal(connIn))
-                .setConOut(new BigDecimal(connOut)).build();
+        Fiber fiber = new FiberBuilder().setLength(BigDecimal.valueOf(length)).setLengthUnits(Km.class)
+                .setAttIn(BigDecimal.valueOf(attIn)).setLossCoef(BigDecimal.valueOf(lossCoef))
+                .setConIn(BigDecimal.valueOf(connIn))
+                .setConOut(BigDecimal.valueOf(connOut)).build();
         Params params1 = new ParamsBuilder().setFiberroadm(fiber).build();
-        Elements element1 = new ElementsBuilder().setUid(uidFiber)
+        return new ElementsBuilder().setUid(uidFiber)
                 .setType(org.opendaylight.yang.gen.v1.gnpy.gnpy.network.topology.rev181214.Fiber.class)
                 .setTypeVariety(typeVariety).setMetadata(metadata1)
                 .setElementType(new FiberRoadmBuilder().setParams(params1).build()).build();
-        return element1;
     }
 
     /*
@@ -374,8 +396,8 @@ public class GnpyTopoImpl {
     private Elements createElementsEdfa(double latitude, double longitude, String region, String city,
             BigDecimal gainTarget, BigDecimal tiltTarget, BigDecimal outVoa, String typeVariety, String uidEdfa) {
         // Create an amplifier after the ROADM
-        Coordinate c1 = new Coordinate(new BigDecimal(latitude));
-        Coordinate c2 = new Coordinate(new BigDecimal(longitude));
+        Coordinate c1 = new Coordinate(BigDecimal.valueOf(latitude));
+        Coordinate c2 = new Coordinate(BigDecimal.valueOf(longitude));
         Location location1 = new LocationBuilder().setRegion(region).setCity(city).setLatitude(c1).setLongitude(c2)
                 .build();
         Metadata metadata1 = new MetadataBuilder().setLocation(location1).build();
@@ -383,10 +405,9 @@ public class GnpyTopoImpl {
                 .setOutVoa(outVoa).build();
         Edfa edfa = new EdfaBuilder()
                 .setOperational(operational).build();
-        Elements element1 = new ElementsBuilder().setUid(uidEdfa)
+        return new ElementsBuilder().setUid(uidEdfa)
                 .setType(org.opendaylight.yang.gen.v1.gnpy.gnpy.network.topology.rev181214.Edfa.class)
                 .setMetadata(metadata1).setElementType(edfa).setTypeVariety(typeVariety).build();
-        return element1;
     }
 
     /*
@@ -395,17 +416,16 @@ public class GnpyTopoImpl {
     private Elements createElementsRoadm(double latitude, double longitude, String region, String city,
             double targetPchOutDb, String uidRoadm) {
 
-        Coordinate c1 = new Coordinate(new BigDecimal(latitude));
-        Coordinate c2 = new Coordinate(new BigDecimal(longitude));
+        Coordinate c1 = new Coordinate(BigDecimal.valueOf(latitude));
+        Coordinate c2 = new Coordinate(BigDecimal.valueOf(longitude));
         Location location1 = new LocationBuilder().setRegion(region).setCity(city).setLatitude(c1).setLongitude(c2)
                 .build();
         Metadata metadata1 = new MetadataBuilder().setLocation(location1).build();
-        Roadm roadm = new RoadmBuilder().setTargetPchOutDb(new BigDecimal(targetPchOutDb)).build();
+        Roadm roadm = new RoadmBuilder().setTargetPchOutDb(BigDecimal.valueOf(targetPchOutDb)).build();
         Params params1 = new ParamsBuilder().setFiberroadm(roadm).build();
-        Elements element1 = new ElementsBuilder().setUid(uidRoadm)
+        return new ElementsBuilder().setUid(uidRoadm)
                 .setType(org.opendaylight.yang.gen.v1.gnpy.gnpy.network.topology.rev181214.Roadm.class)
                 .setMetadata(metadata1).setElementType(new FiberRoadmBuilder().setParams(params1).build()).build();
-        return element1;
     }
 
     /*
@@ -413,16 +433,15 @@ public class GnpyTopoImpl {
      */
     private Elements createElementsTransceiver(double latitude, double longitude, String region, String city,
             String uidTrans) {
-        Coordinate c1 = new Coordinate(new BigDecimal(latitude));
-        Coordinate c2 = new Coordinate(new BigDecimal(longitude));
+        Coordinate c1 = new Coordinate(BigDecimal.valueOf(latitude));
+        Coordinate c2 = new Coordinate(BigDecimal.valueOf(longitude));
         Location location1 = new LocationBuilder().setRegion(region).setCity(city).setLatitude(c1).setLongitude(c2)
                 .build();
         Metadata metadata1 = new MetadataBuilder().setLocation(location1).build();
         Transceiver transceiver = new TransceiverBuilder().build();
-        Elements element1 = new ElementsBuilder().setUid(uidTrans)
+        return new ElementsBuilder().setUid(uidTrans)
                 .setType(org.opendaylight.yang.gen.v1.gnpy.gnpy.network.topology.rev181214.Transceiver.class)
                 .setMetadata(metadata1).setElementType(transceiver).build();
-        return element1;
     }
 
     /*
@@ -434,7 +453,7 @@ public class GnpyTopoImpl {
         }
         String fromNode = srcIp.getIpv4Address().getValue();
         String toNode = destIp.getIpv4Address().getValue();
-        if (fromNode == toNode) {
+        if (fromNode.equals(toNode)) {
             return false;
         }
         Connections connection = new ConnectionsBuilder().setFromNode(fromNode).setToNode(toNode).build();
@@ -471,8 +490,7 @@ public class GnpyTopoImpl {
         }
         fields[3] = Integer.toString(intF3);
         String nidString = fields[0] + "." + fields[1] + "." + fields[2] + "." + fields[3];
-        Ipv4Address nid = new Ipv4Address(nidString);
-        return nid;
+        return new Ipv4Address(nidString);
     }
 
     public List<Elements> getElements() {
index 744882f637aad1b806c6880d76eaad509347b2e2..42541b749028b46a3729aef89948fdb7ec7b225e 100644 (file)
@@ -40,7 +40,7 @@ import org.slf4j.LoggerFactory;
 
 public class GnpyUtilitiesImpl {
 
-    private static final Logger LOG = LoggerFactory.getLogger(GnpyResult.class);
+    private static final Logger LOG = LoggerFactory.getLogger(GnpyUtilitiesImpl.class);
     private NetworkTransactionService networkTransaction;
     private PathComputationRequestInput input;
     private GnpyTopoImpl gnpyTopo = null;
@@ -87,14 +87,14 @@ public class GnpyUtilitiesImpl {
             synchronizationList);
         // Analyze the response
         if (gnpyResponse == null) {
-            throw new GnpyException("In GnpyUtilities: no respnse from GNPy server");
+            throw new GnpyException("In GnpyUtilities: no response from GNPy server");
         }
         GnpyResult result = new GnpyResult(gnpyResponse, gnpyTopo);
         result.analyzeResult();
         return result;
     }
 
-    public HardConstraints askNewPathFromGnpy(HardConstraints gnpyPathAsHC, PceConstraints pceHardConstraints)
+    public HardConstraints askNewPathFromGnpy(PceConstraints pceHardConstraints)
             throws GnpyException, Exception {
 
         AToZDirection atoztmp = new AToZDirectionBuilder()
@@ -105,16 +105,14 @@ public class GnpyUtilitiesImpl {
         GnpyResult result = gnpyResponseOneDirection(gnpySvc);
 
         if (result == null) {
-            throw new GnpyException("In GnpyUtilities: no response from the GNPy server");
+            throw new GnpyException("In GnpyUtilities: no result from the GNPy server");
         }
 
         if (!result.getPathFeasibility()) {
             return null;
         }
         List<PathRouteObjects> pathRouteObjectList = result.analyzeResult();
-        gnpyPathAsHC = result.computeHardConstraintsFromGnpyPath(pathRouteObjectList);
-
-        return gnpyPathAsHC;
+        return result.computeHardConstraintsFromGnpyPath(pathRouteObjectList);
     }
 
     public String getGnpyResponse(List<Elements> elementsList, List<Connections> connectionsList,
@@ -136,8 +134,7 @@ public class GnpyUtilitiesImpl {
             .replace("gnpy-path-computation-simplified:", "")
             .replace("gnpy-network-topology:", "");
 
-        String gnpyResponse = connect.gnpyCnx(gnpyJsonModified);
-        return gnpyResponse;
+        return connect.returnGnpyResponse(gnpyJsonModified);
     }
 
     public GnpyResult getGnpyAtoZ() {
index b282b7d37b45cf25404b6d24fdd1c9934735d15f..596c7025b67e28228b05ce12369872d0402392fe 100644 (file)
@@ -8,7 +8,6 @@
 
 package org.opendaylight.transportpce.pce.gnpy;
 
-import com.google.common.base.Function;
 //false positive in SpotBug -> cannot be used with FluentIterable...
 import com.google.common.collect.FluentIterable;
 
@@ -17,6 +16,7 @@ import java.io.FileWriter;
 import java.io.IOException;
 import java.io.StringWriter;
 import java.io.Writer;
+import java.nio.charset.StandardCharsets;
 import java.util.Collections;
 import java.util.Optional;
 
@@ -30,9 +30,7 @@ import org.opendaylight.transportpce.common.network.NetworkTransactionService;
 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.OrgOpenroadmDevice;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
-import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
@@ -40,8 +38,6 @@ import org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamW
 import org.opendaylight.yangtools.yang.data.codec.gson.JsonWriterFactory;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -52,6 +48,7 @@ public class ServiceDataStoreOperationsImpl implements ServiceDataStoreOperation
     public ServiceDataStoreOperationsImpl(NetworkTransactionService networkTransactionService) {
     }
 
+    @Override
     public void createXMLFromDevice(DataStoreContext dataStoreContextUtil, OrgOpenroadmDevice device, String output)
         throws GnpyException {
 
@@ -66,68 +63,59 @@ public class ServiceDataStoreOperationsImpl implements ServiceDataStoreOperation
             }
             Writer writerFromDataObject =
                 cwDsU.writerFromDataObject(device, OrgOpenroadmDevice.class,cwDsU.dataContainer());
-            try {
-                BufferedWriter writer = new BufferedWriter(new FileWriter(output));
+            try (BufferedWriter writer = new BufferedWriter(new FileWriter(output,StandardCharsets.UTF_8))) {
                 writer.write(writerFromDataObject.toString());
-                writer.close();
             } catch (IOException e) {
                 throw new GnpyException(
-                    String.format("In ServiceDataStoreOperationsImpl : Bufferwriter error"),e);
+                    String.format("In ServiceDataStoreOperationsImpl : Bufferwriter error %s",e));
             }
-            LOG.debug("GNPy: device xml : {}", writerFromDataObject.toString());
+            LOG.debug("GNPy: device xml : {}", writerFromDataObject);
         }
     }
 
+    @Override
     public String createJsonStringFromDataObject(final InstanceIdentifier<?> id, DataObject object)
         throws GnpyException, Exception {
 
-        final SchemaPath scPath = SchemaPath
-                .create(FluentIterable.from(id.getPathArguments()).transform(new Function<PathArgument, QName>() {
-                    @Override
-                    public QName apply(final PathArgument input) {
-                        return BindingReflections.findQName(input.getType());
-                    }
-                }), true);
-        final Writer writer = new StringWriter();
-        NormalizedNodeStreamWriter domWriter;
+        final SchemaPath scPath = SchemaPath.create(FluentIterable
+                .from(id.getPathArguments())
+                .transform(input -> BindingReflections.findQName(input.getType())), true);
+
+        // Prepare the variables
+        final ModuleInfoBackedContext moduleContext = ModuleInfoBackedContext.create();
+        Iterable<? extends YangModuleInfo> moduleInfos = Collections
+                .singleton(BindingReflections.getModuleInfo(object.getClass()));
+        moduleContext.addModuleInfos(moduleInfos);
+        SchemaContext schemaContext = moduleContext.tryToCreateSchemaContext().get();
+        BindingRuntimeContext bindingContext;
+        bindingContext = BindingRuntimeContext.create(moduleContext, schemaContext);
+        final BindingNormalizedNodeCodecRegistry codecRegistry =
+            new BindingNormalizedNodeCodecRegistry(bindingContext);
 
-        try {
-            // Prepare the variables
-            final ModuleInfoBackedContext moduleContext = ModuleInfoBackedContext.create();
-            Iterable<? extends YangModuleInfo> moduleInfos = Collections
-                    .singleton(BindingReflections.getModuleInfo(object.getClass()));
-            moduleContext.addModuleInfos(moduleInfos);
-            SchemaContext schemaContext = moduleContext.tryToCreateSchemaContext().get();
-            BindingRuntimeContext bindingContext;
-            bindingContext = BindingRuntimeContext.create(moduleContext, schemaContext);
-            final BindingNormalizedNodeCodecRegistry codecRegistry =
-                new BindingNormalizedNodeCodecRegistry(bindingContext);
+        /*
+         * This function needs : - context - scPath.getParent() -
+         * scPath.getLastComponent().getNamespace(), -
+         * JsonWriterFactory.createJsonWriter(writer)
+         */
+        final Writer writer = new StringWriter();
 
-            /*
-             * This function needs : - context - scPath.getParent() -
-             * scPath.getLastComponent().getNamespace(), -
-             * JsonWriterFactory.createJsonWriter(writer)
-             */
-            domWriter = JSONNormalizedNodeStreamWriter.createExclusiveWriter(
+        try (NormalizedNodeStreamWriter domWriter = JSONNormalizedNodeStreamWriter.createExclusiveWriter(
                 JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.createSimple(schemaContext),
                 scPath.getParent(), scPath.getLastComponent().getNamespace(),
-                JsonWriterFactory.createJsonWriter(writer, 2));
+                JsonWriterFactory.createJsonWriter(writer, 2));) {
             // The write part
             codecRegistry.getSerializer(id.getTargetType()).serialize(object, codecRegistry.newWriter(id, domWriter));
-            domWriter.close();
-            writer.close();
-        } catch (IOException | YangSyntaxErrorException | ReactorException e) {
+        } catch (IOException e) {
             throw new GnpyException("In ServiceDataStoreOperationsImpl: exception during json file creation",e);
         }
         return writer.toString();
     }
 
     // Write the json as a string in a file
+    @Override
     public void writeStringFile(String jsonString, String fileName) throws GnpyException {
-        try {
-            FileWriter file = new FileWriter(fileName);
+        try (FileWriter file = new FileWriter(fileName,StandardCharsets.UTF_8)) {
             file.write(jsonString);
-            file.close();
         } catch (IOException e) {
             throw new GnpyException("In ServiceDataStoreOperationsImpl : exception during file writing",e);
         }
index 92ffaea23da8a9e5fe3cbe6f8a818ce1fadefea5..39ee022defd9faa8b754733422211f5532f8b39c 100644 (file)
@@ -11,13 +11,12 @@ package org.opendaylight.transportpce.pce.graph;
 import org.jgrapht.GraphPath;
 import org.jgrapht.alg.shortestpath.PathValidator;
 import org.opendaylight.yang.gen.v1.http.org.openroadm.network.types.rev181130.OpenroadmLinkType;
-//import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.topology.rev180226.networks.network.Link;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 public class InAlgoPathValidator implements PathValidator<String, PceGraphEdge> {
     /* Logging. */
-    private static final Logger LOG = LoggerFactory.getLogger(PceGraph.class);
+    private static final Logger LOG = LoggerFactory.getLogger(InAlgoPathValidator.class);
 
     public InAlgoPathValidator() {
         super();
@@ -32,11 +31,7 @@ public class InAlgoPathValidator implements PathValidator<String, PceGraphEdge>
         LOG.debug("InAlgoPathValidator: partialPath size: {} prev edge {} new edge {}",
             size, edge.link().getlinkType(), partialPath.getEdgeList().get(size - 1).link().getlinkType());
 
-        if ((!checkTurn(partialPath.getEdgeList().get(size - 1).link().getlinkType(), edge.link().getlinkType()))) {
-            return false;
-        } else {
-            return true;
-        }
+        return (checkTurn(partialPath.getEdgeList().get(size - 1).link().getlinkType(), edge.link().getlinkType()));
     }
 
     private boolean checkTurn(OpenroadmLinkType prevType, OpenroadmLinkType nextType) {
index 279d23ef7be7748b18ad3a1b918a644db99364b3..b3dbae014e250d1bfaac3baea45cc046e5487a62 100644 (file)
@@ -25,7 +25,6 @@ import org.opendaylight.transportpce.pce.networkanalyzer.PceNode;
 import org.opendaylight.transportpce.pce.networkanalyzer.PceResult;
 import org.opendaylight.transportpce.pce.networkanalyzer.PceResult.LocalCause;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.NodeId;
-
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -41,7 +40,7 @@ public class PceGraph {
     private int mhopsPerPath = 50;
 
     // input
-    private Map<NodeId, PceNode> allPceNodes = new HashMap<NodeId, PceNode>();
+    private Map<NodeId, PceNode> allPceNodes = new HashMap<>();
     private PceNode apceNode = null;
     private PceNode zpceNode = null;
     private String serviceType = "";
@@ -56,7 +55,7 @@ public class PceGraph {
     // for path calculation
     List<GraphPath<String, PceGraphEdge>> allWPaths = null;
 
-    private List<PceLink> pathAtoZ = new ArrayList<PceLink>();
+    private List<PceLink> pathAtoZ = new ArrayList<>();
 
     public PceGraph(PceNode aendNode, PceNode zendNode, Map<NodeId, PceNode> allPceNodes,
             PceConstraints pceHardConstraints, PceConstraints pceSoftConstraints, PceResult pceResult,
@@ -70,8 +69,8 @@ public class PceGraph {
         this.pceSoftConstraints = pceSoftConstraints;
         this.serviceType = serviceType;
 
-        LOG.info("In GraphCalculator: A and Z = {} / {} ", aendNode.toString(), zendNode.toString());
-        LOG.debug("In GraphCalculator: allPceNodes size {}, nodes {} ", allPceNodes.size(), allPceNodes.toString());
+        LOG.info("In GraphCalculator: A and Z = {} / {} ", aendNode, zendNode);
+        LOG.debug("In GraphCalculator: allPceNodes size {}, nodes {} ", allPceNodes.size(), allPceNodes);
     }
 
     public boolean calcPath() {
@@ -79,12 +78,12 @@ public class PceGraph {
         LOG.info(" In PCE GRAPH calcPath : K SHORT PATHS algorithm ");
 
         DefaultDirectedWeightedGraph<String, PceGraphEdge> weightedGraph =
-                new DefaultDirectedWeightedGraph<String, PceGraphEdge>(PceGraphEdge.class);
+                new DefaultDirectedWeightedGraph<>(PceGraphEdge.class);
         populateWithNodes(weightedGraph);
         populateWithLinks(weightedGraph);
 
         if (!runKgraphs(weightedGraph)) {
-            LOG.info("In calcPath : pceResult {}", pceResult.toString());
+            LOG.info("In calcPath : pceResult {}", pceResult);
             return false;
         }
 
@@ -97,7 +96,7 @@ public class PceGraph {
                     pceResult.getResponseCode(), ResponseCodes.RESPONSE_OK);
 
             if (!pceResult.getResponseCode().equals(ResponseCodes.RESPONSE_OK)) {
-                LOG.info("In calcPath: post algo validations DROPPED the path {}", path.toString());
+                LOG.info("In calcPath: post algo validations DROPPED the path {}", path);
                 continue;
             }
 
@@ -110,12 +109,12 @@ public class PceGraph {
             shortestPathAtoZ = new ArrayList<>(pathAtoZ);
             if (("100GE".equals(serviceType)) || ("OTU4".equals(serviceType))) {
                 LOG.info("In calcPath Path FOUND path for wl [{}], hops {}, distance per metrics {}, path AtoZ {}",
-                        pceResult.getResultWavelength(), pathAtoZ.size(), path.getWeight(), pathAtoZ.toString());
+                        pceResult.getResultWavelength(), pathAtoZ.size(), path.getWeight(), pathAtoZ);
                 break;
             } else {
                 // Service is at OTN layer and is relying on a supporting wavelength service
                 LOG.info("In calcPath Path FOUND path for hops {}, distance per metrics {}, path AtoZ {}",
-                        pathAtoZ.size(), path.getWeight(), pathAtoZ.toString());
+                        pathAtoZ.size(), path.getWeight(), pathAtoZ);
                 break;
             }
 
@@ -123,9 +122,9 @@ public class PceGraph {
 
         if (shortestPathAtoZ != null) {
             LOG.info("In calcPath CHOOSEN PATH for wl [{}], hops {}, path AtoZ {}",
-                    pceResult.getResultWavelength(), shortestPathAtoZ.size(), shortestPathAtoZ.toString());
+                    pceResult.getResultWavelength(), shortestPathAtoZ.size(), shortestPathAtoZ);
         }
-        LOG.info("In calcPath : pceResult {}", pceResult.toString());
+        LOG.info("In calcPath : pceResult {}", pceResult);
         return (pceResult.getStatus());
     }
 
@@ -138,7 +137,7 @@ public class PceGraph {
 
         // KShortestPaths on weightedGraph
         KShortestSimplePaths<String, PceGraphEdge> swp =
-            new KShortestSimplePaths<String, PceGraphEdge>(weightedGraph, mhopsPerPath, wpv);
+            new KShortestSimplePaths<>(weightedGraph, mhopsPerPath, wpv);
         allWPaths = swp.getPaths(apceNode.getNodeId().getValue(), zpceNode.getNodeId().getValue(), kpathsToBring);
 
         if (allWPaths.isEmpty()) {
@@ -150,7 +149,7 @@ public class PceGraph {
 
         // debug print
         for (GraphPath<String, PceGraphEdge> path : allWPaths) {
-            LOG.debug("path Weight: {} : {}", path.getWeight(), path.getVertexList().toString());
+            LOG.debug("path Weight: {} : {}", path.getWeight(), path.getVertexList());
         }
 
         return true;
@@ -162,14 +161,14 @@ public class PceGraph {
         PceNode dest = allPceNodes.get(pcelink.getDestId());
 
         if (source == null) {
-            LOG.error("In addLinkToGraph link source node is null : {}", pcelink.toString());
+            LOG.error("In addLinkToGraph link source node is null : {}", pcelink);
             return false;
         }
         if (dest == null) {
-            LOG.error("In addLinkToGraph link dest node is null : {}", pcelink.toString());
+            LOG.error("In addLinkToGraph link dest node is null : {}", pcelink);
             return false;
         }
-        LOG.debug("In addLinkToGraph link to nodes : {}{} {}", pcelink.toString(), source.toString(), dest.toString());
+        LOG.debug("In addLinkToGraph link to nodes : {}{} {}", pcelink, source, dest);
         return true;
     }
 
@@ -178,7 +177,7 @@ public class PceGraph {
         while (nodes.hasNext()) {
             Map.Entry<NodeId, PceNode> node = nodes.next();
             weightedGraph.addVertex(node.getValue().getNodeId().getValue());
-            LOG.debug("In populateWithNodes in node :  {}", node.getValue().toString());
+            LOG.debug("In populateWithNodes in node :  {}", node.getValue());
         }
     }
 
@@ -192,10 +191,10 @@ public class PceGraph {
             PceNode pcenode = node.getValue();
             List<PceLink> links = pcenode.getOutgoingLinks();
 
-            LOG.debug("In populateGraph: use node for graph {}", pcenode.toString());
+            LOG.debug("In populateGraph: use node for graph {}", pcenode);
 
             for (PceLink link : links) {
-                LOG.debug("In populateGraph node {} : add edge to graph {}", pcenode.toString(), link.toString());
+                LOG.debug("In populateGraph node {} : add edge to graph {}", pcenode, link);
 
                 if (!validateLinkforGraph(link)) {
                     continue;
@@ -216,15 +215,15 @@ public class PceGraph {
         switch (pceHardConstraints.getPceMetrics()) {
             case HopCount :
                 weight = 1;
-                LOG.debug("In PceGraph HopCount is used as a metrics. {}", link.toString());
+                LOG.debug("In PceGraph HopCount is used as a metrics. {}", link);
                 break;
             case PropagationDelay :
                 weight = link.getLatency();
-                LOG.debug("In PceGraph PropagationDelay is used as a metrics. {}", link.toString());
+                LOG.debug("In PceGraph PropagationDelay is used as a metrics. {}", link);
                 if ((("1GE".equals(serviceType)) || ("10GE".equals(serviceType)) || ("ODU4".equals(serviceType)))
                         && (weight == 0)) {
                     LOG.warn("PropagationDelay set as metric, but latency is null: is latency set for OTN link {}?",
-                        link.toString());
+                        link);
                 }
                 break;
             // TODO implement IGPMetric and TEMetric - low priority.
index a0dd42d7184cdbea37ae4fa2700fa4b8ef8e7580..2aa455cb73951528cee6ee3c2e24d8e15a4c2d5c 100644 (file)
@@ -28,9 +28,8 @@ import org.slf4j.LoggerFactory;
 
 public class PostAlgoPathValidator {
     /* Logging. */
-    private static final Logger LOG = LoggerFactory.getLogger(PceGraph.class);
+    private static final Logger LOG = LoggerFactory.getLogger(PostAlgoPathValidator.class);
 
-    // TODO hard-coded 96
     private static final int MAX_WAWELENGTH = 96;
     private static final double MIN_OSNR_W100G = 17;
     private static final double TRX_OSNR = 33;
@@ -42,7 +41,7 @@ public class PostAlgoPathValidator {
         PceResult pceResult, PceConstraints pceHardConstraints, String serviceType) {
 
         // check if the path is empty
-        if (path.getEdgeList().size() == 0) {
+        if (path.getEdgeList().isEmpty()) {
             pceResult.setRC(ResponseCodes.RESPONSE_FAILED);
             return pceResult;
         }
@@ -62,7 +61,7 @@ public class PostAlgoPathValidator {
                     return pceResult;
                 }
                 pceResult.setResultWavelength(waveL);
-                LOG.info("In PostAlgoPathValidator: chooseWavelength WL found {} {}", waveL, path.toString());
+                LOG.info("In PostAlgoPathValidator: chooseWavelength WL found {} {}", waveL, path);
 
                 // Check the OSNR
                 if (!checkOSNR(path)) {
@@ -115,13 +114,13 @@ public class PostAlgoPathValidator {
 
             case "ODU4":
                 pceResult.setRC(ResponseCodes.RESPONSE_OK);
-                LOG.info("In PostAlgoPathValidator: ODU4 path found {}", path.toString());
+                LOG.info("In PostAlgoPathValidator: ODU4 path found {}", path);
                 break;
 
             default:
                 pceResult.setRC(ResponseCodes.RESPONSE_FAILED);
                 LOG.warn("In PostAlgoPathValidator checkPath: unsupported serviceType {} found {}",
-                    serviceType, path.toString());
+                    serviceType, path);
                 break;
         }
 
@@ -133,9 +132,9 @@ public class PostAlgoPathValidator {
         Long wavelength = -1L;
         for (long i = 1; i <= MAX_WAWELENGTH; i++) {
             boolean completed = true;
-            LOG.debug("In chooseWavelength: {} {}", path.getLength(), path.toString());
+            LOG.debug("In chooseWavelength: {} {}", path.getLength(), path);
             for (PceGraphEdge edge : path.getEdgeList()) {
-                LOG.debug("In chooseWavelength: source {} ", edge.link().getSourceId().toString());
+                LOG.debug("In chooseWavelength: source {} ", edge.link().getSourceId());
                 PceNode pceNode = allPceNodes.get(edge.link().getSourceId());
                 if (!pceNode.checkWL(i)) {
                     completed = false;
@@ -163,10 +162,7 @@ public class PostAlgoPathValidator {
                     edge.link().getLinkId().getValue());
             }
         }
-        if (latency > maxLatency) {
-            return false;
-        }
-        return true;
+        return (latency < maxLatency);
     }
 
     // Check the inclusion if it is defined in the hard constraints
@@ -179,17 +175,17 @@ public class PostAlgoPathValidator {
         List<PceGraphEdge> pathEdges = path.getEdgeList();
         LOG.debug(" in checkInclude vertex list: [{}]", path.getVertexList());
 
-        List<String> listOfElementsSubNode = new ArrayList<String>();
+        List<String> listOfElementsSubNode = new ArrayList<>();
         listOfElementsSubNode.add(pathEdges.get(0).link().getsourceNetworkSupNodeId());
         listOfElementsSubNode.addAll(listOfElementsBuild(pathEdges, PceConstraints.ResourceType.NODE,
             pceHardConstraintsInput));
 
-        List<String> listOfElementsCLLI = new ArrayList<String>();
+        List<String> listOfElementsCLLI = new ArrayList<>();
         listOfElementsCLLI.add(pathEdges.get(0).link().getsourceCLLI());
         listOfElementsCLLI.addAll(listOfElementsBuild(pathEdges, PceConstraints.ResourceType.CLLI,
             pceHardConstraintsInput));
 
-        List<String> listOfElementsSRLG = new ArrayList<String>();
+        List<String> listOfElementsSRLG = new ArrayList<>();
         // first link is XPONDEROUTPUT, no SRLG for it
         listOfElementsSRLG.add("NONE");
         listOfElementsSRLG.addAll(listOfElementsBuild(pathEdges, PceConstraints.ResourceType.SRLG,
@@ -237,7 +233,7 @@ public class PostAlgoPathValidator {
     private List<String> listOfElementsBuild(List<PceGraphEdge> pathEdges, PceConstraints.ResourceType type,
         PceConstraints pceHardConstraints) {
 
-        List<String> listOfElements = new ArrayList<String>();
+        List<String> listOfElements = new ArrayList<>();
         for (PceGraphEdge link : pathEdges) {
             switch (type) {
                 case NODE:
@@ -262,7 +258,6 @@ public class PostAlgoPathValidator {
                             listOfElements.add(srlgStr);
                             LOG.info("listOfElementsBuild. FOUND SRLG {} in link {}", srlgStr, link.link());
                             found = true;
-                            continue;
                         }
                     }
                     if (!found) {
@@ -279,7 +274,7 @@ public class PostAlgoPathValidator {
 
     private Map<String, Uint16> chooseTribPort(GraphPath<String,
         PceGraphEdge> path, Map<NodeId, PceNode> allPceNodes) {
-        LOG.info("In choosetribPort: edgeList = {} ", path.getEdgeList().toString());
+        LOG.info("In choosetribPort: edgeList = {} ", path.getEdgeList());
         Map<String, Uint16> tribPortMap = new HashMap<>();
 
         for (PceGraphEdge edge : path.getEdgeList()) {
@@ -308,7 +303,7 @@ public class PostAlgoPathValidator {
 
     private Map<String, List<Uint16>> chooseTribSlot(GraphPath<String,
         PceGraphEdge> path, Map<NodeId, PceNode> allPceNodes, int nbSlot) {
-        LOG.info("In choosetribSlot2: edgeList = {} ", path.getEdgeList().toString());
+        LOG.info("In choosetribSlot2: edgeList = {} ", path.getEdgeList());
         Map<String, List<Uint16>> tribSlotMap = new HashMap<>();
 
         for (PceGraphEdge edge : path.getEdgeList()) {
@@ -334,7 +329,7 @@ public class PostAlgoPathValidator {
                 discontinue = false;
                 Integer val = commonEdgeTsPool.get(index).toJava();
                 for (int i = 0; i < nbSlot; i++) {
-                    if (commonEdgeTsPool.get(index + i).equals(val + i)) {
+                    if (commonEdgeTsPool.get(index + i).equals(Uint16.valueOf(val + i))) {
                         tribSlotList.add(commonEdgeTsPool.get(index + i));
                     } else {
                         discontinue = true;
@@ -360,19 +355,17 @@ public class PostAlgoPathValidator {
             LOG.debug("In choosetribSlot: AllPceNodes contains PceNode instance, no trib port search");
             return tribSlot;
         } else if (nodeClass.getClass().isInstance(PceNode.class)) {
-            LOG.debug("In choosetribPort: {} {}", path.getLength(), path.toString());
+            LOG.debug("In choosetribPort: {} {}", path.getLength(), path);
         }
         for (PceGraphEdge edge : path.getEdgeList()) {
-            LOG.debug("In chooseTribSlot: source {} ", edge.link().getSourceId().toString());
+            LOG.debug("In chooseTribSlot: source {} ", edge.link().getSourceId());
             PceNode pceNode = allPceNodes.get(edge.link().getSourceId());
             Object tps = allPceNodes.get(edge.link().getSourceTP());
             Object tpd = allPceNodes.get(edge.link().getDestTP());
             if ((pceNode.getAvailableTribSlots().containsKey(tps.toString()))
                 && (pceNode.getAvailableTribSlots().containsKey(tpd.toString()))) {
-                List<Uint16> tribSlotEdgeSourceN = new ArrayList<>();
-                List<Uint16> tribSlotEdgeDestN = new ArrayList<>();
-                tribSlotEdgeSourceN = pceNode.getAvailableTribSlots().get(tps.toString());
-                tribSlotEdgeDestN = pceNode.getAvailableTribSlots().get(tps.toString());
+                List<Uint16> tribSlotEdgeSourceN = pceNode.getAvailableTribSlots().get(tps.toString());
+                List<Uint16> tribSlotEdgeDestN = pceNode.getAvailableTribSlots().get(tps.toString());
                 check = false;
                 for (int i = 0; i <= 79; i++) {
                     if (tribSlotEdgeSourceN.get(i) == null) {
@@ -381,12 +374,12 @@ public class PostAlgoPathValidator {
                     // TODO This will need to be modified as soon as the trib-slots allocation per
                     // trib-port
                     // policy applied by the different manufacturer is known
-                    if (tribSlotEdgeSourceN.get(i) == tribSlotEdgeDestN.get(i)) {
+                    if (tribSlotEdgeSourceN.get(i).equals(tribSlotEdgeDestN.get(i))) {
                         check = true;
                     } else {
                         check = false;
                         LOG.debug("In chooseTribSlot: Misalignement of trib slots between source {} and dest {}",
-                            edge.link().getSourceId().toString(), edge.link().getDestId().toString());
+                            edge.link().getSourceId(), edge.link().getDestId());
                         break;
                     }
                 }
@@ -395,7 +388,7 @@ public class PostAlgoPathValidator {
                 }
             } else {
                 LOG.debug("In chooseTribSlot: source {} does not have provisonned hosting HO interface ",
-                    edge.link().getSourceId().toString());
+                    edge.link().getSourceId());
                 statusOK = false;
             }
         }
@@ -430,10 +423,7 @@ public class PostAlgoPathValidator {
             return false;
         }
         LOG.info("In checkOSNR: OSNR of the path is {} dB", osnrDb);
-        if ((osnrDb + SYS_MARGIN) < MIN_OSNR_W100G) {
-            return false;
-        }
-        return true;
+        return ((osnrDb + SYS_MARGIN) > MIN_OSNR_W100G);
     }
 
     private double getOsnrDb(double osnrLu) {
index 8949d0a1ca71116ffae671340cc2d526d4a87590..bb946712d731d788dde31cd7d762c7fe41047901 100644 (file)
@@ -11,6 +11,7 @@ import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 import java.util.TreeMap;
+
 import org.opendaylight.transportpce.common.NetworkUtils;
 import org.opendaylight.transportpce.pce.constraints.PceConstraints;
 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.network.rev181130.Link1;
@@ -38,7 +39,7 @@ public final class MapUtils {
         List<String> excSrlgLinks = pceHardConstraints.getExcludeSrlgLinks();
 
         LOG.info("mapDiversityConstraints before : ExcludeClliNodes {} \n ExcludeNodes {} \n ExcludeSrlgLinks {}",
-                excClliNodes.toString(), excNodes.toString(), excSrlgLinks.toString());
+                excClliNodes, excNodes, excSrlgLinks);
 
         for (Node node : allNodes) {
             if (excClliNodes.contains(node.getNodeId().getValue())) {
@@ -61,16 +62,16 @@ public final class MapUtils {
                     if (!srlg.isEmpty()) {
                         pceHardConstraints.setExcludeSRLG(srlg);
                         LOG.debug("mapDiversityConstraints setExcludeSRLG {} for link {}",
-                                srlg.toString(), link.getLinkId().getValue());
+                                srlg, link.getLinkId().getValue());
                     }
                 }
             }
         }
 
         LOG.info("mapDiversityConstraints after : ExcludeCLLI {} \n ExcludeSupNodes {} \n ExcludeSRLG {}",
-                pceHardConstraints.getExcludeCLLI().toString(),
-                pceHardConstraints.getExcludeSupNodes().toString(),
-                pceHardConstraints.getExcludeSRLG().toString());
+                pceHardConstraints.getExcludeCLLI(),
+                pceHardConstraints.getExcludeSupNodes(),
+                pceHardConstraints.getExcludeSRLG());
 
     }
 
@@ -80,7 +81,7 @@ public final class MapUtils {
     }
 
     public static List<Long> getSRLG(Link link) {
-        List<Long> srlgList = new ArrayList<Long>();
+        List<Long> srlgList = new ArrayList<>();
         try {
             List<LinkConcatenation> linkList = getOmsAttributesSpan(link).getLinkConcatenation();
             for (LinkConcatenation lc : linkList) {
@@ -93,7 +94,7 @@ public final class MapUtils {
     }
 
     public static List<Long> getSRLGfromLink(Link link) {
-        List<Long> srlgList = new ArrayList<Long>();
+        List<Long> srlgList = new ArrayList<>();
         org.opendaylight.yang.gen.v1.http.org.openroadm.common.network.rev181130.Link1 linkC =
             link.augmentation(org.opendaylight.yang.gen.v1.http.org.openroadm.common.network.rev181130.Link1.class);
         if (linkC == null) {
@@ -137,8 +138,8 @@ public final class MapUtils {
     }
 
     public static TreeMap<String, String> getAllSupNode(Node node) {
-        TreeMap<String, String> allSupNodes = new TreeMap<String, String>();
-        List<SupportingNode> supNodes = new ArrayList<SupportingNode>();
+        TreeMap<String, String> allSupNodes = new TreeMap<>();
+        List<SupportingNode> supNodes = new ArrayList<>();
         try {
             supNodes = node.getSupportingNode();
         } catch (NullPointerException e) {
@@ -231,7 +232,7 @@ public final class MapUtils {
         org.opendaylight.yang.gen.v1.http.org.openroadm.common.network.rev181130.Link1 linkOpposite
             = link.augmentation(org.opendaylight.yang.gen.v1.http.org.openroadm.common.network.rev181130.Link1.class);
         tmpoppositeLink = linkOpposite.getOppositeLink();
-        LOG.debug("PceLink: reading oppositeLink.  {}", linkOpposite.toString());
+        LOG.debug("PceLink: reading oppositeLink.  {}", linkOpposite);
         if (tmpoppositeLink == null) {
             LOG.error("PceLink: Error reading oppositeLink. Link is ignored {}", link.getLinkId().getValue());
             return null;
index d8c2caf77382240b6634e6c31a74ba03dfcdec52..fd8f3a28007fea337672ec7a5ce060b3e3b82346 100644 (file)
@@ -59,9 +59,9 @@ public class PceCalculation {
     private PceConstraints pceHardConstraints;
 
     ///////////// Intermediate data/////////////////
-    private List<PceLink> addLinks = new ArrayList<PceLink>();
-    private List<PceLink> dropLinks = new ArrayList<PceLink>();
-    private HashSet<NodeId> azSrgs = new HashSet<NodeId>();
+    private List<PceLink> addLinks = new ArrayList<>();
+    private List<PceLink> dropLinks = new ArrayList<>();
+    private HashSet<NodeId> azSrgs = new HashSet<>();
 
     private PceNode aendPceNode = null;
     private PceNode zendPceNode = null;
@@ -70,11 +70,11 @@ public class PceCalculation {
     private List<Node> allNodes = null;
 
     // this List serves graph calculation
-    private Map<NodeId, PceNode> allPceNodes = new HashMap<NodeId, PceNode>();
+    private Map<NodeId, PceNode> allPceNodes = new HashMap<>();
     // this List serves calculation of ZtoA path description
     // TODO maybe better solution is possible
-    private Map<LinkId, PceLink> allPceLinks = new HashMap<LinkId, PceLink>();
-    private Set<LinkId> linksToExclude = new HashSet<LinkId>();
+    private Map<LinkId, PceLink> allPceLinks = new HashMap<>();
+    private Set<LinkId> linksToExclude = new HashSet<>();
     private PceResult returnStructure;
 
     private enum ConstraintTypes {
@@ -147,18 +147,18 @@ public class PceCalculation {
             //And casting to int bumps the limit here.
             //Passing by ENUM or String are possible alternatives.
             //Maybe HashMap and similar options should also be considered here.
-        } else if (serviceFormatA == "Ethernet") {
+        } else if ("Ethernet".equals(serviceFormatA)) {
         //only rate 100L is currently supported except in Ethernet
             if (serviceRate == 10L) {
                 serviceType = "10GE";
             } else if (serviceRate == 1L) {
                 serviceType = "1GE";
             } else {
-                LOG.debug("parseInput: unsupported service type: Format Ethernet Rate {}", String.valueOf(serviceRate));
+                LOG.debug("parseInput: unsupported service type: Format Ethernet Rate {}", serviceRate);
             }
         } else {
             LOG.debug("parseInput: unsupported service type: Format {} Rate {}",
-                serviceFormatA, String.valueOf(serviceRate));
+                serviceFormatA, serviceRate);
         }
 
         returnStructure.setRate(input.getServiceAEnd().getServiceRate().toJava());
@@ -190,7 +190,7 @@ public class PceCalculation {
                 networkTransactionService.read(LogicalDatastoreType.CONFIGURATION, nwInstanceIdentifier).get();
             if (nwOptional.isPresent()) {
                 nw = nwOptional.get();
-                LOG.debug("readMdSal: network nodes: nwOptional.isPresent = true {}", nw.toString());
+                LOG.debug("readMdSal: network nodes: nwOptional.isPresent = true {}", nw);
             }
         } catch (InterruptedException | ExecutionException e) {
             LOG.error("readMdSal: Error reading topology {}", nwInstanceIdentifier);
@@ -219,14 +219,14 @@ public class PceCalculation {
             return false;
         }
         LOG.info("readMdSal: network nodes: {} nodes added", allNodes.size());
-        LOG.debug("readMdSal: network nodes: {} nodes added", allNodes.toString());
+        LOG.debug("readMdSal: network nodes: {} nodes added", allNodes);
 
         if (allLinks == null || allLinks.isEmpty()) {
             LOG.error("readMdSal: no links ");
             return false;
         }
         LOG.info("readMdSal: network links: {} links added", allLinks.size());
-        LOG.debug("readMdSal: network links: {} links added", allLinks.toString());
+        LOG.debug("readMdSal: network links: {} links added", allLinks);
 
         return true;
     }
@@ -272,7 +272,7 @@ public class PceCalculation {
                 validateOtnNode(node);
             }
 
-            LOG.info("analyzeNw: allPceNodes {}", allPceNodes.toString());
+            LOG.info("analyzeNw: allPceNodes {}", allPceNodes);
 
             if (aendPceNode == null || zendPceNode == null) {
                 LOG.error("analyzeNw: Error in reading nodes: A or Z do not present in the network");
@@ -289,8 +289,8 @@ public class PceCalculation {
             return false;
         }
 
-        LOG.debug("analyzeNw: allPceNodes {}", allPceNodes.toString());
-        LOG.debug("analyzeNw: allPceLinks {}", allPceLinks.toString());
+        LOG.debug("analyzeNw: allPceNodes {}", allPceNodes);
+        LOG.debug("analyzeNw: allPceLinks {}", allPceLinks);
 
         return true;
     }
@@ -302,7 +302,7 @@ public class PceCalculation {
         if (azSrgs.contains(nodeId)) {
             allPceLinks.put(pcelink.getLinkId(), pcelink);
             allPceNodes.get(nodeId).addOutgoingLink(pcelink);
-            LOG.debug("analyzeNw: Add_LINK added to source and to allPceLinks {}", pcelink.getLinkId().toString());
+            LOG.debug("analyzeNw: Add_LINK added to source and to allPceLinks {}", pcelink.getLinkId());
             return true;
         }
 
@@ -320,7 +320,7 @@ public class PceCalculation {
         if (azSrgs.contains(nodeId)) {
             allPceLinks.put(pcelink.getLinkId(), pcelink);
             allPceNodes.get(nodeId).addOutgoingLink(pcelink);
-            LOG.debug("analyzeNw: Drop_LINK added to dest and to allPceLinks {}", pcelink.getLinkId().toString());
+            LOG.debug("analyzeNw: Drop_LINK added to dest and to allPceLinks {}", pcelink.getLinkId());
             return true;
         }
 
@@ -332,7 +332,7 @@ public class PceCalculation {
     }
 
     private boolean validateLink(Link link) {
-        LOG.info("validateLink: link {} ", link.toString());
+        LOG.info("validateLink: link {} ", link);
 
         NodeId sourceId = link.getSource().getSourceNode();
         NodeId destId = link.getDestination().getDestNode();
@@ -359,13 +359,10 @@ public class PceCalculation {
                 return false;
             }
             LinkId linkId = pcelink.getLinkId();
-            switch (validateLinkConstraints(pcelink)) {
-                case HARD_EXCLUDE:
-                    dropOppositeLink(link);
-                    LOG.debug("validateLink: constraints : link is ignored == {}", linkId.getValue());
-                    return false;
-                default:
-                    break;
+            if (validateLinkConstraints(pcelink).equals(ConstraintTypes.HARD_EXCLUDE)) {
+                dropOppositeLink(link);
+                LOG.debug("validateLink: constraints : link is ignored == {}", linkId.getValue());
+                return false;
             }
             switch (pcelink.getlinkType()) {
                 case ROADMTOROADM:
@@ -373,17 +370,17 @@ public class PceCalculation {
                     allPceLinks.put(linkId, pcelink);
                     source.addOutgoingLink(pcelink);
                     LOG.debug("validateLink: {}-LINK added to allPceLinks {}",
-                        pcelink.getlinkType(), pcelink.toString());
+                        pcelink.getlinkType(), pcelink);
                     break;
                 case ADDLINK:
                     pcelink.setClient(source.getRdmSrgClient(pcelink.getSourceTP().toString()));
                     addLinks.add(pcelink);
-                    LOG.debug("validateLink: ADD-LINK saved  {}", pcelink.toString());
+                    LOG.debug("validateLink: ADD-LINK saved  {}", pcelink);
                     break;
                 case DROPLINK:
                     pcelink.setClient(dest.getRdmSrgClient(pcelink.getDestTP().toString()));
                     dropLinks.add(pcelink);
-                    LOG.debug("validateLink: DROP-LINK saved  {}", pcelink.toString());
+                    LOG.debug("validateLink: DROP-LINK saved  {}", pcelink);
                     break;
                 case XPONDERINPUT:
                     // store separately all SRG links directly
@@ -391,7 +388,7 @@ public class PceCalculation {
                     // connected to A/Z
                     if (!dest.checkTP(pcelink.getDestTP().toString())) {
                         LOG.debug(
-                            "validateLink: XPONDER-INPUT is rejected as NW port is busy - {} ", pcelink.toString());
+                            "validateLink: XPONDER-INPUT is rejected as NW port is busy - {} ", pcelink);
                         return false;
                     }
                     if (dest.getXpdrClient(pcelink.getDestTP().toString()) != null) {
@@ -399,7 +396,7 @@ public class PceCalculation {
                     }
                     allPceLinks.put(linkId, pcelink);
                     source.addOutgoingLink(pcelink);
-                    LOG.debug("validateLink: XPONDER-INPUT link added to allPceLinks {}", pcelink.toString());
+                    LOG.debug("validateLink: XPONDER-INPUT link added to allPceLinks {}", pcelink);
                     break;
                 // does it mean XPONDER==>>SRG ?
                 case XPONDEROUTPUT:
@@ -408,7 +405,7 @@ public class PceCalculation {
                     // connected to A/Z
                     if (!source.checkTP(pcelink.getSourceTP().toString())) {
                         LOG.debug(
-                            "validateLink: XPONDER-OUTPUT is rejected as NW port is busy - {} ", pcelink.toString());
+                            "validateLink: XPONDER-OUTPUT is rejected as NW port is busy - {} ", pcelink);
                         return false;
                     }
                     if (source.getXpdrClient(pcelink.getSourceTP().toString()) != null) {
@@ -416,10 +413,10 @@ public class PceCalculation {
                     }
                     allPceLinks.put(linkId, pcelink);
                     source.addOutgoingLink(pcelink);
-                    LOG.debug("validateLink: XPONDER-OUTPUT link added to allPceLinks {}", pcelink.toString());
+                    LOG.debug("validateLink: XPONDER-OUTPUT link added to allPceLinks {}", pcelink);
                     break;
                 default:
-                    LOG.warn("validateLink: link type is not supported {}", pcelink.toString());
+                    LOG.warn("validateLink: link type is not supported {}", pcelink);
             }
             return true;
 
@@ -434,14 +431,12 @@ public class PceCalculation {
             }
 
             LinkId linkId = pceOtnLink.getLinkId();
-            switch (validateLinkConstraints(pceOtnLink)) {
-                case HARD_EXCLUDE:
-                    dropOppositeLink(link);
-                    LOG.debug("validateLink: constraints : link is ignored == {}", linkId.getValue());
-                    return false;
-                default:
-                    break;
+            if (validateLinkConstraints(pceOtnLink).equals(ConstraintTypes.HARD_EXCLUDE)) {
+                dropOppositeLink(link);
+                LOG.debug("validateLink: constraints : link is ignored == {}", linkId.getValue());
+                return false;
             }
+
             switch (pceOtnLink.getlinkType()) {
                 case OTNLINK:
                     if (dest.getXpdrClient(pceOtnLink.getDestTP().toString()) != null) {
@@ -450,10 +445,10 @@ public class PceCalculation {
 
                     allPceLinks.put(linkId, pceOtnLink);
                     source.addOutgoingLink(pceOtnLink);
-                    LOG.info("validateLink: OTN-LINK added to allPceLinks {}", pceOtnLink.toString());
+                    LOG.info("validateLink: OTN-LINK added to allPceLinks {}", pceOtnLink);
                     break;
                 default:
-                    LOG.warn("validateLink: link type is not supported {}", pceOtnLink.toString());
+                    LOG.warn("validateLink: link type is not supported {}", pceOtnLink);
             }
             return true;
 
@@ -465,7 +460,7 @@ public class PceCalculation {
     }
 
     private boolean validateNode(Node node) {
-        LOG.debug("validateNode: node {} ", node.toString());
+        LOG.debug("validateNode: node {} ", node);
 
         // PceNode will be used in Graph algorithm
         Node1 node1 = node.augmentation(Node1.class);
@@ -485,19 +480,15 @@ public class PceCalculation {
             return false;
         }
 
-        switch (validateNodeConstraints(pceNode)) {
-            case HARD_EXCLUDE:
-                return false;
-
-            default:
-                break;
+        if (validateNodeConstraints(pceNode).equals(ConstraintTypes.HARD_EXCLUDE)) {
+            return false;
         }
         if ((pceNode.getSupNetworkNodeId().equals(anodeId) && (this.aendPceNode == null))
-            && (endPceNode(nodeType, pceNode.getNodeId(), pceNode))) {
+            && (Boolean.TRUE.equals(endPceNode(nodeType, pceNode.getNodeId(), pceNode)))) {
             this.aendPceNode = pceNode;
         }
         if ((pceNode.getSupNetworkNodeId().equals(znodeId) && (this.zendPceNode == null))
-            && (endPceNode(nodeType, pceNode.getNodeId(), pceNode))) {
+            && (Boolean.TRUE.equals(endPceNode(nodeType, pceNode.getNodeId(), pceNode)))) {
             this.zendPceNode = pceNode;
         }
 
@@ -520,11 +511,8 @@ public class PceCalculation {
                 LOG.warn(" validateOtnNode: Node {} is ignored", node.getNodeId().getValue());
                 return false;
             }
-            switch (validateNodeConstraints(pceOtnNode)) {
-                case HARD_EXCLUDE:
-                    return false;
-                default:
-                    break;
+            if (validateNodeConstraints(pceOtnNode).equals(ConstraintTypes.HARD_EXCLUDE)) {
+                return false;
             }
             if (pceOtnNode.getNodeId().getValue().equals(anodeId) && this.aendPceNode == null) {
                 this.aendPceNode = pceOtnNode;
@@ -575,7 +563,7 @@ public class PceCalculation {
             return ConstraintTypes.NONE;
         }
 
-        List<Long> constraints = new ArrayList<Long>(pceHardConstraints.getExcludeSRLG());
+        List<Long> constraints = new ArrayList<>(pceHardConstraints.getExcludeSRLG());
         constraints.retainAll(link.getsrlgList());
         if (!constraints.isEmpty()) {
             LOG.info("validateLinkConstraints: {}", link.getLinkId().getValue());
@@ -588,9 +576,8 @@ public class PceCalculation {
     private void dropOppositeLink(Link link) {
         LinkId opplink = MapUtils.extractOppositeLink(link);
 
-        PceLink oppPceLink = allPceLinks.get(opplink);
-        if (oppPceLink != null) {
-            allPceLinks.remove(oppPceLink);
+        if (allPceLinks.containsKey(opplink)) {
+            allPceLinks.remove(opplink);
         } else {
             linksToExclude.add(opplink);
         }
@@ -646,7 +633,7 @@ public class PceCalculation {
         while (nodes.hasNext()) {
             PceNode pcenode = nodes.next().getValue();
             List<PceLink> links = pcenode.getOutgoingLinks();
-            LOG.info("In printNodes in node {} : outgoing links {} ", pcenode.getNodeId().getValue(), links.toString());
+            LOG.info("In printNodes in node {} : outgoing links {} ", pcenode.getNodeId().getValue(), links);
         }
     }
 }
index c8afb4c8a2b20d46ab752aa883194bd07b48ac6f..68b6d12db8ae933ab8a379a38e9250353b1f7b62 100644 (file)
@@ -8,6 +8,10 @@
 
 package org.opendaylight.transportpce.pce.networkanalyzer;
 
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
 import java.util.List;
 
 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.network.rev181130.Link1;
@@ -21,8 +25,9 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.top
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class PceLink {
+public class PceLink implements Serializable {
 
+    private static final long serialVersionUID = 1L;
     /* Logging. */
     private static final Logger LOG = LoggerFactory.getLogger(PceLink.class);
     ///////////////////////// LINKS ////////////////////
@@ -40,8 +45,8 @@ public class PceLink {
     private final OpenroadmLinkType linkType;
     private final NodeId sourceId;
     private final NodeId destId;
-    private final Object sourceTP;
-    private final Object destTP;
+    private transient Object sourceTP;
+    private transient Object destTP;
     private final String sourceNetworkSupNodeId;
     private final String destNetworkSupNodeId;
     private final String sourceCLLI;
@@ -52,7 +57,7 @@ public class PceLink {
     private final Long usedBandwidth;
     private final List<Long> srlgList;
     private final double osnr;
-    private final Span omsAttributesSpan;
+    private final transient Span omsAttributesSpan;
     private static final double CELERITY = 2.99792458 * 1e5; //meter per ms
     private static final double NOISE_MASK_A = 0.571429;
     private static final double NOISE_MASK_B = 39.285714;
@@ -102,7 +107,7 @@ public class PceLink {
             this.availableBandwidth = 0L;
             this.usedBandwidth = 0L;
         }
-        LOG.debug("PceLink: created PceLink  {}", toString());
+        LOG.debug("PceLink: created PceLink  {}", linkId);
     }
 
     //Retrieve the opposite link
@@ -231,7 +236,7 @@ public class PceLink {
     }
 
     public Long getUsedBandwidth() {
-        return availableBandwidth;
+        return usedBandwidth;
     }
 
     public String getsourceNetworkSupNodeId() {
@@ -302,7 +307,7 @@ public class PceLink {
             return false;
         }
 
-        long neededBW = 0L;
+        long neededBW;
         OtnLinkType neededType = null;
         switch (serviceType) {
 
@@ -363,8 +368,20 @@ public class PceLink {
         return true;
     }
 
+    @Override
     public String toString() {
         return "PceLink type=" + linkType + " ID=" + linkId.getValue() + " latency=" + latency;
     }
 
+    private void writeObject(ObjectOutputStream out) throws IOException {
+        out.defaultWriteObject();
+        out.writeObject(this.sourceTP);
+        out.writeObject(this.destTP);
+    }
+
+    private void readObject(ObjectInputStream in) throws IOException,ClassNotFoundException {
+        in.defaultReadObject();
+        this.sourceTP = in.readObject();
+        this.destTP = in.readObject();
+    }
 }
index a04cd6579922dc2aa61e5748c933c693afa8a56c..38fa7347bb0e02dc668c224f79050bf0cf5d9343 100644 (file)
@@ -29,7 +29,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 public class PceOpticalNode implements PceNode {
-    private static final Logger LOG = LoggerFactory.getLogger(PceCalculation.class);
+    private static final Logger LOG = LoggerFactory.getLogger(PceOpticalNode.class);
 
     private boolean valid = true;
 
@@ -40,12 +40,12 @@ public class PceOpticalNode implements PceNode {
     private final String pceNodeType;
 
     // wavelength calculation per node type
-    private List<Long> availableWLindex = new ArrayList<Long>();
-    private Map<String, OpenroadmTpType> availableSrgPp = new TreeMap<String, OpenroadmTpType>();
-    private Map<String, OpenroadmTpType> availableSrgCp = new TreeMap<String, OpenroadmTpType>();
-    private List<String> usedXpndrNWTps = new ArrayList<String>();
-    private List<PceLink> outgoingLinks = new ArrayList<PceLink>();
-    private Map<String, String> clientPerNwTp = new HashMap<String, String>();
+    private List<Long> availableWLindex = new ArrayList<>();
+    private Map<String, OpenroadmTpType> availableSrgPp = new TreeMap<>();
+    private Map<String, OpenroadmTpType> availableSrgCp = new TreeMap<>();
+    private List<String> usedXpndrNWTps = new ArrayList<>();
+    private List<PceLink> outgoingLinks = new ArrayList<>();
+    private Map<String, String> clientPerNwTp = new HashMap<>();
 
     public PceOpticalNode(Node node, OpenroadmNodeType nodeType, NodeId nodeId, ServiceFormat serviceFormat,
         String pceNodeType) {
@@ -74,7 +74,7 @@ public class PceOpticalNode implements PceNode {
         List<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.topology.rev180226.networks.network
             .node.TerminationPoint> allTps = nodeTp.getTerminationPoint();
         if (allTps == null) {
-            LOG.error("initSrgTpList: ROADM TerminationPoint list is empty for node {}", this.toString());
+            LOG.error("initSrgTpList: ROADM TerminationPoint list is empty for node {}", this);
             this.valid = false;
             return;
         }
@@ -85,7 +85,7 @@ public class PceOpticalNode implements PceNode {
                 .augmentation(org.opendaylight.yang.gen.v1.http.org.openroadm.network.topology.rev181130
                 .TerminationPoint1.class);
             OpenroadmTpType type = cntp1.getTpType();
-            LOG.info("type = {} for tp {}", type.getName(), tp.toString());
+            LOG.info("type = {} for tp {}", type.getName(), tp);
 
             switch (type) {
                 case SRGTXRXCP:
@@ -120,13 +120,12 @@ public class PceOpticalNode implements PceNode {
             }
         }
         if (this.availableSrgPp.isEmpty() && this.availableSrgCp.isEmpty()) {
-            LOG.error("initSrgTpList: ROADM SRG TerminationPoint list is empty for node {}", this.toString());
+            LOG.error("initSrgTpList: ROADM SRG TerminationPoint list is empty for node {}", this);
             this.valid = false;
             return;
         }
         LOG.info("initSrgTpList: availableSrgPp size = {} && availableSrgCp size = {} in {}",
-            this.availableSrgPp.size(), this.availableSrgCp.size(), this.toString());
-        return;
+            this.availableSrgPp.size(), this.availableSrgCp.size(), this);
     }
 
     public void initWLlist() {
@@ -142,13 +141,13 @@ public class PceOpticalNode implements PceNode {
                         node1.getSrgAttributes().getAvailableWavelengths();
                 if (srgAvailableWL == null) {
                     this.valid = false;
-                    LOG.error("initWLlist: SRG AvailableWavelengths is empty for node  {}", this.toString());
+                    LOG.error("initWLlist: SRG AvailableWavelengths is empty for node  {}", this);
                     return;
                 }
                 for (org.opendaylight.yang.gen.v1.http.org.openroadm.srg.rev181130.srg.node.attributes
                         .AvailableWavelengths awl : srgAvailableWL) {
                     this.availableWLindex.add(awl.getIndex().toJava());
-                    LOG.debug("initWLlist: SRG next = {} in {}", awl.getIndex(), this.toString());
+                    LOG.debug("initWLlist: SRG next = {} in {}", awl.getIndex(), this);
                 }
                 break;
             case DEGREE :
@@ -156,13 +155,13 @@ public class PceOpticalNode implements PceNode {
                     .AvailableWavelengths> degAvailableWL = node1.getDegreeAttributes().getAvailableWavelengths();
                 if (degAvailableWL == null) {
                     this.valid = false;
-                    LOG.error("initWLlist: DEG AvailableWavelengths is empty for node  {}", this.toString());
+                    LOG.error("initWLlist: DEG AvailableWavelengths is empty for node  {}", this);
                     return;
                 }
                 for (org.opendaylight.yang.gen.v1.http.org.openroadm.degree.rev181130.degree.node.attributes
                             .AvailableWavelengths awl : degAvailableWL) {
                     this.availableWLindex.add(awl.getIndex().toJava());
-                    LOG.debug("initWLlist: DEGREE next = {} in {}", awl.getIndex(), this.toString());
+                    LOG.debug("initWLlist: DEGREE next = {} in {}", awl.getIndex(), this);
                 }
                 break;
             case XPONDER :
@@ -172,15 +171,14 @@ public class PceOpticalNode implements PceNode {
                 }
                 break;
             default:
-                LOG.error("initWLlist: unsupported node type {} in node {}", this.nodeType, this.toString());
+                LOG.error("initWLlist: unsupported node type {} in node {}", this.nodeType, this);
                 break;
         }
-        if (this.availableWLindex.size() == 0) {
-            LOG.debug("initWLlist: There are no available wavelengths in node {}", this.toString());
+        if (this.availableWLindex.isEmpty()) {
+            LOG.debug("initWLlist: There are no available wavelengths in node {}", this);
             this.valid = false;
         }
-        LOG.debug("initWLlist: availableWLindex size = {} in {}", this.availableWLindex.size(), this.toString());
-        return;
+        LOG.debug("initWLlist: availableWLindex size = {} in {}", this.availableWLindex.size(), this);
     }
 
     public void initXndrTps() {
@@ -195,7 +193,7 @@ public class PceOpticalNode implements PceNode {
             .node.TerminationPoint> allTps = nodeTp.getTerminationPoint();
         if (allTps == null) {
             this.valid = false;
-            LOG.error("initXndrTps: XPONDER TerminationPoint list is empty for node {}", this.toString());
+            LOG.error("initXndrTps: XPONDER TerminationPoint list is empty for node {}", this);
             return;
         }
         this.valid = false;
@@ -223,8 +221,8 @@ public class PceOpticalNode implements PceNode {
                         this.clientPerNwTp.put(tp.getTpId().getValue(), client);
                         this.valid = true;
                     } else {
-                        LOG.error("initXndrTps: XPONDER {} NW TP doesn't have defined Client {}", this.toString(),
-                            tp.getTpId().getValue());
+                        LOG.error("initXndrTps: XPONDER {} NW TP doesn't have defined Client {}",
+                            this, tp.getTpId().getValue());
                     }
                 } else if (ServiceFormat.OTU.equals(this.serviceFormat)) {
                     LOG.info("Infrastructure OTU4 connection");
@@ -235,8 +233,7 @@ public class PceOpticalNode implements PceNode {
             }
         }
         if (!isValid()) {
-            LOG.error("initXndrTps: XPONDER doesn't have available wavelengths for node  {}", this.toString());
-            return;
+            LOG.error("initXndrTps: XPONDER doesn't have available wavelengths for node  {}", this);
         }
     }
 
@@ -275,13 +272,13 @@ public class PceOpticalNode implements PceNode {
                     .sorted(new SortPortsByName())
                     .findFirst();
             if (!client.isPresent()) {
-                LOG.error("getRdmSrgClient: ROADM {} doesn't have PP Client for CP {}", this.toString(), tp);
+                LOG.error("getRdmSrgClient: ROADM {} doesn't have PP Client for CP {}", this, tp);
                 return null;
             }
             LOG.info("getRdmSrgClient: client PP {} for CP {} found !", client, tp);
             return client.get();
         } else {
-            LOG.error("getRdmSrgClient: SRG TerminationPoint PP list is not available for node {}", this.toString());
+            LOG.error("getRdmSrgClient: SRG TerminationPoint PP list is not available for node {}", this);
             return null;
         }
     }
@@ -333,6 +330,7 @@ public class PceOpticalNode implements PceNode {
         return nodeId;
     }
 
+    @Override
     public String toString() {
         return "PceNode type=" + nodeType + " ID=" + nodeId.getValue() + " CLLI=" + this.getSupClliNodeId();
     }
@@ -364,13 +362,11 @@ public class PceOpticalNode implements PceNode {
 
     @Override
     public Map<String, List<Uint16>> getAvailableTribPorts() {
-        // TODO Auto-generated method stub
         return null;
     }
 
     @Override
     public Map<String, List<Uint16>> getAvailableTribSlots() {
-        // TODO Auto-generated method stub
         return null;
     }
 }
index bdf5aeebfd580886ec94fe17a0c76bb783df05b5..4966b9a4405263be5463ff5399fa994a08343dc5 100644 (file)
@@ -40,7 +40,7 @@ import org.slf4j.LoggerFactory;
 
 public class PceOtnNode implements PceNode {
     /* Logging. */
-    private static final Logger LOG = LoggerFactory.getLogger(PceCalculation.class);
+    private static final Logger LOG = LoggerFactory.getLogger(PceOtnNode.class);
     ////////////////////////// OTN NODES ///////////////////////////
     /*
      * For This Class the node passed shall be at the otn-openroadm Layer
@@ -54,18 +54,18 @@ public class PceOtnNode implements PceNode {
     private final String pceNodeType;
     private final String otnServiceType;
 
-    private Map<String, List<Uint16>> tpAvailableTribPort = new TreeMap<String, List<Uint16>>();
-    private Map<String, List<Uint16>> tpAvailableTribSlot = new TreeMap<String, List<Uint16>>();
-    private Map<String, OpenroadmTpType> availableXponderTp = new TreeMap<String, OpenroadmTpType>();
-    private List<String> usedXpdrNWTps = new ArrayList<String>();
+    private Map<String, List<Uint16>> tpAvailableTribPort = new TreeMap<>();
+    private Map<String, List<Uint16>> tpAvailableTribSlot = new TreeMap<>();
+    private Map<String, OpenroadmTpType> availableXponderTp = new TreeMap<>();
+    private List<String> usedXpdrNWTps = new ArrayList<>();
     private List<TpId> availableXpdrNWTps;
     private List<TpId> usableXpdrNWTps;
-    private List<String> usedXpdrClientTps = new ArrayList<String>();
+    private List<String> usedXpdrClientTps = new ArrayList<>();
     private List<TpId> availableXpdrClientTps;
     private List<TpId> usableXpdrClientTps;
 
-    private List<PceLink> outgoingLinks = new ArrayList<PceLink>();
-    private Map<String, String> clientPerNwTp = new HashMap<String, String>();
+    private List<PceLink> outgoingLinks = new ArrayList<>();
+    private Map<String, String> clientPerNwTp = new HashMap<>();
 
     public PceOtnNode(Node node, OpenroadmNodeType nodeType, NodeId nodeId, String pceNodeType, String serviceType) {
         this.node = node;
@@ -75,11 +75,11 @@ public class PceOtnNode implements PceNode {
         this.otnServiceType = serviceType;
         this.tpAvailableTribSlot.clear();
         this.usedXpdrNWTps.clear();
-        this.availableXpdrNWTps = new ArrayList<TpId>();
-        this.usableXpdrNWTps = new ArrayList<TpId>();
+        this.availableXpdrNWTps = new ArrayList<>();
+        this.usableXpdrNWTps = new ArrayList<>();
         this.usedXpdrClientTps.clear();
-        this.availableXpdrClientTps = new ArrayList<TpId>();
-        this.usableXpdrClientTps = new ArrayList<TpId>();
+        this.availableXpdrClientTps = new ArrayList<>();
+        this.usableXpdrClientTps = new ArrayList<>();
         this.tpAvailableTribPort.clear();
         checkAvailableTribPort();
         this.tpAvailableTribSlot.clear();
@@ -102,7 +102,7 @@ public class PceOtnNode implements PceNode {
             .node.TerminationPoint> allTps = nodeTp.getTerminationPoint();
         this.valid = false;
         if (allTps == null) {
-            LOG.error("PceOtnNode: initXndrTps: XPONDER TerminationPoint list is empty for node {}", this.toString());
+            LOG.error("PceOtnNode: initXndrTps: XPONDER TerminationPoint list is empty for node {}", this);
             return;
         }
 
@@ -238,12 +238,11 @@ public class PceOtnNode implements PceNode {
             && ontTp1.getXpdrTpPortConnectionAttributes().getOdtuTpnPool() != null
             && ontTp1.getXpdrTpPortConnectionAttributes().getOdtuTpnPool().get(0).getOdtuType()
                 .equals(ODTU4TsAllocated.class)
-            && ontTp1.getXpdrTpPortConnectionAttributes().getOdtuTpnPool().get(0).getTpnPool().size() >= 1
-            && ontTp1.getXpdrTpPortConnectionAttributes().getTsPool().size() >= tsNb) {
+            && ontTp1.getXpdrTpPortConnectionAttributes().getOdtuTpnPool().get(0).getTpnPool().isEmpty()
+            && (ontTp1.getXpdrTpPortConnectionAttributes().getTsPool().size() >= tsNb)) {
             return true;
-        } else {
-            return false;
         }
+        return false;
     }
 
     private boolean checkClientTp(TerminationPoint1 ontTp1) {
@@ -357,30 +356,28 @@ public class PceOtnNode implements PceNode {
             Long neededBW) {
         if (this.nodeType != OpenroadmNodeType.TPDR) {
             return true;
-        } else {
-            org.opendaylight.yang.gen.v1.http.org.openroadm.otn.network.topology.rev181130.Node1 node1 =
-                node.augmentation(
-                    org.opendaylight.yang.gen.v1.http.org.openroadm.otn.network.topology.rev181130.Node1.class);
-            SwitchingPools sp = node1.getSwitchingPools();
-            List<OduSwitchingPools> osp = new ArrayList<OduSwitchingPools>();
-            osp = sp.getOduSwitchingPools();
-            for (OduSwitchingPools ospx : osp) {
-                List<NonBlockingList> nbl = ospx.getNonBlockingList();
-                for (NonBlockingList nbll : nbl) {
-                    if (nbll.getAvailableInterconnectBandwidth().toJava() >= neededBW) {
-                        List<TpId> tplist = new ArrayList<TpId>(nbll.getTpList());
-                        if ((tplist.contains(tp1.getTpId())) & (tplist.contains(tp2.getTpId()))) {
-                            LOG.debug("validateSwitchingPoolBandwidth: couple  of tp {} x {} valid for crossconnection",
-                                tp1.getTpId().toString(), tp2.getTpId().toString());
-                            return true;
-                        }
-                    }
+        }
+        org.opendaylight.yang.gen.v1.http.org.openroadm.otn.network.topology.rev181130.Node1 node1 =
+            node.augmentation(
+                org.opendaylight.yang.gen.v1.http.org.openroadm.otn.network.topology.rev181130.Node1.class);
+        SwitchingPools sp = node1.getSwitchingPools();
+        List<OduSwitchingPools> osp = sp.getOduSwitchingPools();
+        for (OduSwitchingPools ospx : osp) {
+            List<NonBlockingList> nbl = ospx.getNonBlockingList();
+            for (NonBlockingList nbll : nbl) {
+                if (nbll.getAvailableInterconnectBandwidth().toJava() >= neededBW && nbll.getTpList() != null
+                        && nbll.getTpList().contains(tp1.getTpId()) && nbll.getTpList().contains(tp2.getTpId())) {
+                    LOG.debug("validateSwitchingPoolBandwidth: couple  of tp {} x {} valid for crossconnection",
+                        tp1.getTpId(), tp2.getTpId());
+                    return true;
                 }
             }
-            LOG.debug("validateSwitchingPoolBandwidth: No valid Switching pool for crossconnecting tp {} and {}",
-                tp1.getTpId().toString(), tp2.getTpId().toString());
-            return false;
         }
+
+        LOG.debug("validateSwitchingPoolBandwidth: No valid Switching pool for crossconnecting tp {} and {}",
+            tp1.getTpId(), tp2.getTpId());
+        return false;
+
     }
 
     public void validateIntermediateSwitch() {
@@ -397,7 +394,6 @@ public class PceOtnNode implements PceNode {
         } else {
             LOG.info("validateIntermediateSwitch: Switch usable for transit == {}", nodeId.getValue());
         }
-        return;
     }
 
     public void checkAvailableTribPort() {
@@ -453,10 +449,12 @@ public class PceOtnNode implements PceNode {
         return valid;
     }
 
+    @Override
     public void addOutgoingLink(PceLink outLink) {
         this.outgoingLinks.add(outLink);
     }
 
+    @Override
     public List<PceLink> getOutgoingLinks() {
         return outgoingLinks;
     }
@@ -466,12 +464,13 @@ public class PceOtnNode implements PceNode {
         return this.clientPerNwTp.get(tp);
     }
 
+    @Override
     public String toString() {
         return "PceNode type=" + nodeType + " ID=" + nodeId.getValue() + " CLLI=" + this.getSupClliNodeId();
     }
 
     public void printLinksOfNode() {
-        LOG.info(" outgoing links of node {} : {} ", nodeId.getValue(), this.getOutgoingLinks().toString());
+        LOG.info(" outgoing links of node {} : {} ", nodeId.getValue(), this.getOutgoingLinks());
     }
 
     @Override
@@ -509,7 +508,6 @@ public class PceOtnNode implements PceNode {
 
     @Override
     public String getRdmSrgClient(String tp) {
-        // TODO Auto-generated method stub
         return null;
     }
 
@@ -520,13 +518,11 @@ public class PceOtnNode implements PceNode {
 
     @Override
     public boolean checkTP(String tp) {
-        // TODO Auto-generated method stub
         return false;
     }
 
     @Override
     public boolean checkWL(long index) {
-        // TODO Auto-generated method stub
         return false;
     }
 }
index 8a1b33317c5e5f4c469e78fb2f66e2360bcabec1..9fc410afb0e92ede8d4919a785844a1dff9d07f0 100644 (file)
@@ -22,7 +22,6 @@ import org.opendaylight.transportpce.pce.PceComplianceCheck;
 import org.opendaylight.transportpce.pce.PceComplianceCheckResult;
 import org.opendaylight.transportpce.pce.PceSendingPceRPCs;
 import org.opendaylight.transportpce.pce.gnpy.GnpyResult;
-
 import org.opendaylight.yang.gen.v1.gnpy.path.rev200202.result.Response;
 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.pce.rev200128.CancelResourceReserveInput;
 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.pce.rev200128.CancelResourceReserveOutput;
@@ -105,12 +104,12 @@ public class PathComputationServiceImpl implements PathComputationService {
                         RpcStatusEx.Pending, "Service compliant, submitting cancelResourceReserve Request ...", null);
                 PceSendingPceRPCs sendingPCE = new PceSendingPceRPCs();
                 sendingPCE.cancelResourceReserve();
-                if (sendingPCE.getSuccess()) {
+                if (Boolean.TRUE.equals(sendingPCE.getSuccess())) {
                     message = "ResourceReserve cancelled !";
                 } else {
                     message = "Cancelling ResourceReserve failed !";
                 }
-                LOG.info(message);
+                LOG.info("in PathComputationServiceImpl : {}",message);
                 sendNotifications(ServicePathNotificationTypes.CancelResourceReserve, input.getServiceName(),
                         RpcStatusEx.Successful, "cancel Resource Reserve successful!", null);
                 ConfigurationResponseCommonBuilder configurationResponseCommon =
@@ -173,7 +172,7 @@ public class PathComputationServiceImpl implements PathComputationService {
                 }
                 output.setGnpyResponse(listResponse);
 
-                if (!(sendingPCE.getSuccess()) || (path == null)) {
+                if (Boolean.FALSE.equals(sendingPCE.getSuccess()) || (path == null)) {
                     configurationResponseCommon.setAckFinalIndicator("Yes")
                             .setRequestId(input.getServiceHandlerHeader().getRequestId()).setResponseCode(responseCode)
                             .setResponseMessage(message);
@@ -256,9 +255,7 @@ public class PathComputationServiceImpl implements PathComputationService {
                 feasible = true;
             }
         }
-        GnpyResponse gnpypResp = new GnpyResponseBuilder().setPathDir(pathDir).setResponseType(respType)
-                .setFeasibility(feasible).build();
-        return gnpypResp;
+        return new GnpyResponseBuilder().setPathDir(pathDir).setResponseType(respType).setFeasibility(feasible).build();
     }
 
 }