clean some compilation warnings
[transportpce.git] / tests / stubpce / src / main / java / org / opendaylight / transportpce / stubpce / SendingPceRPCs.java
1 /*
2  * Copyright © 2017 Orange, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9
10 package org.opendaylight.transportpce.stubpce;
11
12 import com.google.common.base.Optional;
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import com.google.common.util.concurrent.ListeningExecutorService;
16 import java.util.ArrayList;
17 import java.util.Iterator;
18 import java.util.List;
19 import java.util.ListIterator;
20 import java.util.SortedSet;
21 import java.util.TreeSet;
22 import java.util.concurrent.Callable;
23 import java.util.concurrent.ExecutionException;
24 import java.util.concurrent.Future;
25 import java.util.concurrent.TimeUnit;
26 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
27 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
28 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
29 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
30 import org.opendaylight.transportpce.stubpce.topology.PathDescriptionsOrdered;
31 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.stubpce.rev170426.CancelResourceReserveInput;
32 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.stubpce.rev170426.PathComputationRequestInput;
33 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.stubpce.rev170426.PathDescriptionList;
34 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.stubpce.rev170426.ServicePathList;
35 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.stubpce.rev170426.path.description.list.PathDescriptions;
36 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.stubpce.rev170426.service.path.list.ServicePaths;
37 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.stubpce.rev170426.service.path.list.ServicePathsBuilder;
38 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.stubpce.rev170426.service.path.list.ServicePathsKey;
39 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.stubpce.rev170426.service.path.rpc.result.PathDescriptionBuilder;
40 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev170426.path.description.AToZDirection;
41 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev170426.path.description.ZToADirection;
42 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev170426.path.description.atoz.direction.AToZ;
43 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev170426.pce.resource.resource.Resource;
44 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev170426.pce.resource.resource.resource.Link;
45 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev170426.pce.resource.resource.resource.Node;
46 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev170426.pce.resource.resource.resource.TerminationPoint;
47 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev170426.constraints.sp.co.routing.or.general.General;
48 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev170426.constraints.sp.co.routing.or.general.general.Diversity;
49 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev170426.constraints.sp.co.routing.or.general.general.Exclude;
50 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev170426.routing.constraints.sp.HardConstraints;
51 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev170426.routing.constraints.sp.SoftConstraints;
52 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.service.types.rev170426.service.handler.header.ServiceHandlerHeaderBuilder;
53 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.service.types.rev170426.service.path.ServiceAEnd;
54 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.service.types.rev170426.service.path.ServiceZEnd;
55 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 /**
60  * Class for Sending
61  * PCE requests :
62  * - path-computation-request
63  * - cancel-resource-reserve.
64  * @author <a href="mailto:martial.coulibaly@gfi.com">Martial Coulibaly</a> on behalf of Orange
65  *
66  */
67 public class SendingPceRPCs {
68     /** Logging. */
69     private static final Logger LOG = LoggerFactory.getLogger(SendingPceRPCs.class);
70     private Boolean success;
71     private PathComputationRequestInput input;
72     private CancelResourceReserveInput cancelInput;
73     private PathDescriptionBuilder pathDescription;
74     private DataBroker db;
75     private String error;
76     private final ListeningExecutorService executor;
77     private List<ServicePaths> servicePathList;
78
79     public SendingPceRPCs() {
80         success = true;
81         setPathDescription(null);
82         setError("");
83         executor = null;
84         setServicePathList(new ArrayList<ServicePaths>());
85     }
86
87     public SendingPceRPCs(PathComputationRequestInput input,DataBroker databroker,ListeningExecutorService executor) {
88         success = true;
89         setPathDescription(null);
90         setInput(input);
91         setCancelInput(null);
92         setDb(databroker);
93         setError("");
94         servicePathList = readServicePathList();
95         this.executor = executor;
96     }
97
98     public SendingPceRPCs(CancelResourceReserveInput input,DataBroker databroker,ListeningExecutorService executor) {
99         success = true;
100         setPathDescription(null);
101         setInput(null);
102         setCancelInput(input);
103         setDb(databroker);
104         setError("");
105         servicePathList = readServicePathList();
106         this.executor = executor;
107     }
108
109     /**
110      * Compare AEnd and ZEnd resource Node to
111      * AEnd and ZEnd String.
112      *
113      * @param pathAend AEnd resource Node
114      * @param pathZend ZEnd resource Node
115      * @param inputAend AEnd String Node
116      * @param inputZend ZEnd String Node
117      * @return Boolean result true if equal, false if not
118      */
119     private Boolean comp(Resource pathAend, Resource pathZend, String inputAend, String inputZend) {
120         Boolean result = false;
121         if ((pathAend != null) && (pathZend != null) && (inputAend != null) && (inputZend != null)) {
122             if ((pathAend instanceof Node) && (pathZend instanceof Node)) {
123                 Node aend = (Node) pathAend;
124                 Node zend = (Node) pathZend;
125                 if (aend.getNodeIdentifier().getNodeId().compareToIgnoreCase(inputAend) == 0) {
126                     if (zend.getNodeIdentifier().getNodeId().compareToIgnoreCase(inputZend) == 0) {
127                         result = true;
128                     }
129                 }
130             }
131         }
132         return result;
133     }
134
135     /**
136      * Compare two resource.
137      *
138      * @param res1 first resource
139      * @param res2 second resource
140      * @return Boolean result true if equal, false if not
141      */
142     private Boolean egalResource(Resource res1, Resource res2) {
143         LOG.info("comparing resource ...");
144         Boolean result = false;
145         LOG.info("{} - {}", res1.getClass().getName(), res2.getClass().getName());
146         if (res1.getClass().getName().compareToIgnoreCase(res2.getClass().getName()) == 0) {
147             if ((res1 instanceof Node) && (res2 instanceof Node)) {
148                 Node node1 = (Node)res1;
149                 Node node2 = (Node)res2;
150                 if (node1.getNodeIdentifier().getNodeId()
151                         .compareTo(node2.getNodeIdentifier().getNodeId()) == 0) {
152                     result = true;
153                 }
154             }
155             if ((res1 instanceof TerminationPoint) && (res2 instanceof TerminationPoint)) {
156                 TerminationPoint tp1 = (TerminationPoint)res1;
157                 TerminationPoint tp2 = (TerminationPoint)res2;
158                 if (tp1.getTerminationPointIdentifier().getNodeId()
159                         .compareTo(tp2.getTerminationPointIdentifier().getNodeId()) == 0) {
160                     if (tp1.getTerminationPointIdentifier().getTpId()
161                             .compareTo(tp2.getTerminationPointIdentifier().getTpId()) == 0) {
162                         result = true;
163                     }
164                 }
165             }
166             if ((res1 instanceof Link) && (res2 instanceof Link)) {
167                 Link link1 = (Link)res1;
168                 Link link2 = (Link)res2;
169                 if (link1.getLinkIdentifier().getLinkId().compareTo(link2.getLinkIdentifier().getLinkId()) == 0) {
170                     result = true;
171                 }
172
173             }
174         }
175         return result;
176     }
177
178     /**
179      *  compare two AtoZDirection.
180      *
181      * @param atoz1 first AToZDirection
182      * @param atoz2 second AToZDirection
183      * @return Boolean result true if equal, false if not
184      */
185     private Boolean egalAtoZDirection(AToZDirection atoz1, AToZDirection atoz2) {
186         LOG.info("comparing AtoZDirection ...");
187         Boolean result = true;
188         if (atoz1.getAToZ().size() == atoz2.getAToZ().size()) {
189             int index = 0;
190             int size = atoz1.getAToZ().size();
191             LOG.info("size : {}", size);
192             String id1 = null;
193             String id2 = null;
194             while (index < size) {
195                 id1 = atoz1.getAToZ().get(index).getId();
196                 LOG.info("id : {}", id1);
197                 Resource res1 = atoz1.getAToZ().get(index).getResource().getResource();
198                 LOG.info("res1 : {}", res1.toString());
199                 Resource res2 = null;
200                 if (id1 != null) {
201                     Boolean trouve = false;
202                     for (int loop = 0;loop < size;loop++) {
203                         id2 = atoz2.getAToZ().get(loop).getId();
204                         if ((id2 != null) && (id2.compareTo(id1) == 0)) {
205                             res2 = atoz2.getAToZ().get(loop).getResource().getResource();
206                             LOG.info("res2 : {}", res2.toString());
207                             trouve = true;
208                             break;
209                         }
210                     }
211                     if (trouve) {
212                         if (!egalResource(res1, res2)) {
213                             result = false;
214                             break;
215                         }
216                     }
217                 } else {
218                     result = false;
219                     break;
220                 }
221                 index++;
222             }
223         } else {
224             LOG.info("AToZDirection size is not equal !");
225             result = false;
226         }
227         return result;
228     }
229
230     /**
231      *  compare two ZtoZDirection.
232      *
233      * @param ztoa1 first ZToZDirection
234      * @param ztoa2 second ZToZDirection
235      * @return Boolean result true if equal, false if not
236      */
237     private Boolean egalZtoADirection(ZToADirection ztoa1, ZToADirection ztoa2) {
238         LOG.info("comparing ZtoADirection ...");
239         Boolean result = true;
240         if (ztoa1.getZToA().size() == ztoa2.getZToA().size()) {
241             int index = 0;
242             int size = ztoa1.getZToA().size();
243             LOG.info("size : {}", size);
244             String id1 = null;
245             String id2 = null;
246             while (index < size) {
247                 id1 = ztoa1.getZToA().get(index).getId();
248                 LOG.info("id : {}", id1);
249                 Resource res1 = ztoa1.getZToA().get(index).getResource().getResource();
250                 LOG.info("res1 : {}", res1.toString());
251                 Resource res2 = null;
252                 if (id1 != null) {
253                     Boolean trouve = false;
254                     for (int loop = 0;loop < size;loop++) {
255                         id2 = ztoa2.getZToA().get(loop).getId();
256                         if ((id2 != null) && (id2.compareTo(id1) == 0)) {
257                             res2 = ztoa2.getZToA().get(loop).getResource().getResource();
258                             LOG.info("res2 : {}", res2.toString());
259                             trouve = true;
260                             break;
261                         }
262                     }
263                     if (trouve) {
264                         if (!egalResource(res1, res2)) {
265                             result = false;
266                             break;
267                         }
268                     }
269                 } else {
270                     result = false;
271                     break;
272                 }
273                 index++;
274             }
275         } else {
276             result = false;
277         }
278         return result;
279     }
280
281     /**
282      * Test if resources Nodes
283      * not include in PathDescriptions.
284      *
285      * @param path PathDescriptions
286      * @param nodes Nodes List
287      * @return Boolean result true if found, false if not
288      */
289     private Boolean excludeNode(PathDescriptions path, List<String> nodes) {
290         LOG.info("Testing exclude Nodes ...");
291         Boolean result = false;
292         if ((path != null) && !nodes.isEmpty()) {
293             List<AToZ> list = path.getAToZDirection().getAToZ();
294             if (!list.isEmpty()) {
295                 int index = 0;
296                 boolean found = false;
297                 while ((index < list.size()) && !found) {
298                     Resource res = list.get(index).getResource().getResource();
299                     if ((res != null) && (res instanceof Node)) {
300                         Node node = (Node) res;
301                         for (String exclude : nodes) {
302                             if (exclude.compareToIgnoreCase(node.getNodeIdentifier().getNodeId()) == 0) {
303                                 LOG.info("Node not excluded !");
304                                 found = true;
305                                 break;
306                             }
307                         }
308                     }
309                     index++;
310                 }
311                 if (!found) {
312                     result = true;
313                 }
314             }
315         } else {
316             LOG.info("exclude parameters not corrrect !");
317         }
318         return result;
319     }
320
321     /**
322      * check if existing services not
323      * in pathDescriptions.
324      *
325      *
326      * @param existingService existing service list
327      * @param path PathDescriptions
328      * @param choice 0:Nodes, 1:Clli, 2:Srlg
329      * @return Boolean result true if found, false if not
330      */
331     private Boolean diversityService(List<String> existingService, PathDescriptions path, int choice) {
332         LOG.info("Testing diversity ...");
333         Boolean result = false;
334         if ((path != null) && (choice >= 0) && !existingService.isEmpty()) {
335             int index = 0;
336             while (index < existingService.size()) {
337                 String tmp = existingService.get(index);
338                 if (tmp != null) {
339                     org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.service
340                         .types.rev170426.service.path.PathDescription pathDesc = null;
341                     if ((servicePathList != null) && !servicePathList.isEmpty()) {
342                         for (ServicePaths service : servicePathList) {
343                             if (service.getServicePathName().compareTo(tmp) == 0) {
344                                 LOG.info("Existing Service '{}' found in ServicePathList ...", tmp);
345                                 pathDesc = service.getPathDescription();
346                             }
347                         }
348                     }
349                     if (pathDesc != null) {
350                         switch (choice) {
351                             case 0: //Nodes
352                                 LOG.info("Checking Node existing-service-applicability ...");
353                                 if (!egalAtoZDirection(path.getAToZDirection(), pathDesc.getAToZDirection())) {
354                                     result = true;
355                                     break;
356                                 }
357                                 break;
358                             case 1: //Clli
359                                 LOG.info("Checking clli existing-service-applicability ...");
360                                 break;
361
362                             case 2: //Srlg
363                                 LOG.info("Checking srlg existing-service-applicability ...");
364
365                                 break;
366                             default:
367                                 break;
368                         }
369                     } else {
370                         LOG.info("Existing Service '{}' not found in ServicePathList !", tmp);
371                         result = true;
372                     }
373                     if (!result) {
374                         break;
375                     }
376                 }
377                 index++;
378             }
379         } else {
380             LOG.info("Diversity parameters not coherent !");
381         }
382         return result;
383     }
384
385     /**
386      * test if pathDescription
387      * already exists in ServicePathList.
388      *
389      * @param path PathDescriptions
390      * @return <code>Boolean</code> result
391      */
392     private Boolean testPathDescription(PathDescriptions path) {
393         LOG.info("Testing pathDescription ...");
394         Boolean result = false;
395         if (path != null) {
396             LOG.info("retrieving path from servicePath List ...");
397             try {
398                 if (!servicePathList.isEmpty()) {
399                     LOG.info("ServicePathList not empty, contains {} paths.", servicePathList.size());
400                     for (ServicePaths service : servicePathList) {
401                         org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.service
402                             .types.rev170426.service.path.PathDescription tmp = service.getPathDescription();
403                         if (tmp != null) {
404                             if ((path.getAToZDirection() != null) && (tmp.getAToZDirection() != null)
405                                     && egalAtoZDirection(path.getAToZDirection(), tmp.getAToZDirection())) {
406                                 if ((path.getZToADirection() != null) && (tmp.getZToADirection() != null)
407                                         && egalZtoADirection(path.getZToADirection(), tmp.getZToADirection())) {
408                                     result = true;
409                                     LOG.info("Path already present in servicePath List");
410                                     break;
411                                 } else {
412                                     LOG.info("ZtoADirection not equal or one of ZtoADirection is null!");
413                                     break;
414                                 }
415                             } else {
416                                 LOG.info("AtoZDirection not equal !");
417                                 break;
418                             }
419
420                         }
421                     }
422                 } else {
423                     LOG.info("ServicePathList is empty");
424                 }
425             } catch (NullPointerException e) {
426                 LOG.error("ServicePathList is empty");
427             }
428         } else {
429             LOG.info("PathDescriptions is null !");
430             result = true;
431         }
432         LOG.info("testPathDescription result : {}", result);
433         return result;
434     }
435
436     /**
437      * function to retrieve Paths based on
438      * AEnd and ZEnd.
439      *
440      * @param aendNodeId Aend Node Id
441      * @param zendNodeId Zend Node Id
442      * @return result PathDescriptions List
443      */
444     private List<PathDescriptions> retrievePath(String aendNodeId, String zendNodeId) {
445         List<PathDescriptions> result = new ArrayList<PathDescriptions>();
446         List<PathDescriptions> paths = readPathDescriptionList();
447         if (!paths.isEmpty() && (aendNodeId != null) && (zendNodeId != null)) {
448             LOG.info("retrieving paths from pathDescription List for {} / {}", aendNodeId, zendNodeId);
449             for (PathDescriptions tmp : paths) {
450                 Resource pathAend = null;
451                 Resource pathZend = null;
452                 String id = null;
453                 if (tmp != null) {
454                     LOG.info("Getting Aend & ZEnd from path '{}'...",tmp.getPathName());
455                     int index = 0;
456                     int size = tmp.getAToZDirection().getAToZ().size();
457                     while (index < size) {
458                         id = tmp.getAToZDirection().getAToZ().get(index).getId();
459                         if (id.compareToIgnoreCase("1") == 0) {
460                             Resource resource = tmp.getAToZDirection().getAToZ().get(index).getResource()
461                                     .getResource();
462                             LOG.info("{} : {}", resource.getClass().toString(), resource.toString());
463                             pathAend = resource;
464                             break;
465                         }
466                         index++;
467                     }
468                     index = 0;
469                     while (index < size) {
470                         id = tmp.getZToADirection().getZToA().get(index).getId();
471                         if (id.compareToIgnoreCase("1") == 0) {
472                             Resource resource = tmp.getZToADirection().getZToA().get(index).getResource()
473                                     .getResource();
474                             LOG.info(resource.toString());
475                             pathZend = resource;
476                             break;
477                         }
478                         index++;
479                     }
480                     if ((pathAend != null) && (pathZend != null)) {
481                         LOG.info("pathAend : {} - pathZend: {}",pathAend, pathZend);
482                         LOG.info("aendNodeId : {} - zendNodeId : {}", aendNodeId, zendNodeId);
483                         if (comp(pathAend, pathZend, aendNodeId, zendNodeId)) {
484                             LOG.info("PathDescription found !");
485                             result.add(tmp);
486                         }
487                     }
488                 }
489             }
490         }
491         return result;
492     }
493
494
495     /**
496      * found Pathdescriptions with
497      * name containing an expression.
498      *
499      * @param pathdescr PathDescriptions List
500      * @param contain String expression
501      * @return PathDescriptionsOrdered List
502      */
503     private SortedSet<PathDescriptionsOrdered> foundpath(List<PathDescriptions> pathdescr, String contain) {
504         SortedSet<PathDescriptionsOrdered> result = new TreeSet<PathDescriptionsOrdered>();
505         ListIterator<PathDescriptions> it = pathdescr.listIterator();
506         int odr = 0;
507         while (it.hasNext()) {
508             PathDescriptions path = it.next();
509             String name = path.getPathName();
510             LOG.info("path  : {}", name);
511             if ((name != null) && name.contains(contain)) {
512                 LOG.info("    path gets : {}", name);
513                 String [] split = name.split("_");
514                 if (split.length == 3) {
515                     odr = Integer.parseInt(split[2]);
516                     result.add(new PathDescriptionsOrdered(path, odr));
517                 }
518             }
519         }
520         return result;
521     }
522
523     /**
524      * order PathDescriptions List
525      * with first, ordered direct links
526      * and secondly ordered indirect
527      * links.
528      *
529      * @param pathdescr PathDescriptions List
530      * @return PathDescriptions List ordered
531      */
532     private List<PathDescriptions> orderPathdescriptionsList(List<PathDescriptions> pathdescr) {
533         SortedSet<PathDescriptionsOrdered> direct = new TreeSet<PathDescriptionsOrdered>();
534         SortedSet<PathDescriptionsOrdered> indirect = new TreeSet<PathDescriptionsOrdered>();
535         List<PathDescriptions> result = new ArrayList<PathDescriptions>();
536         int size = pathdescr.size();
537         if (size > 0) {
538             LOG.info("getting direct path first ...");
539             direct = foundpath(pathdescr, "_direct_");
540             LOG.info("getting indirect path first ...");
541             indirect = foundpath(pathdescr, "_indirect_");
542         }
543         if (direct.size() > 0) {
544             Iterator<PathDescriptionsOrdered> itset = direct.iterator();
545             while (itset.hasNext()) {
546                 result.add(itset.next().getPathDescriptions());
547             }
548             if (indirect.size() > 0) {
549                 Iterator<PathDescriptionsOrdered> itset2 = indirect.iterator();
550                 while (itset2.hasNext()) {
551                     result.add(itset2.next().getPathDescriptions());
552                 }
553             }
554
555         } else if (indirect.size() > 0) {
556             Iterator<PathDescriptionsOrdered> itset2 = indirect.iterator();
557             while (itset2.hasNext()) {
558                 result.add(itset2.next().getPathDescriptions());
559             }
560         }
561         if (result.size() == pathdescr.size()) {
562             return result;
563         } else {
564             return null;
565         }
566     }
567
568     public ListenableFuture<Boolean> cancelResourceReserve() {
569         LOG.info("In cancelResourceReserve request ...");
570         setSuccess(false);
571         return executor.submit(new Callable<Boolean>() {
572             @Override
573             public Boolean call() throws Exception {
574                 Boolean output = false;
575                 if (cancelInput != null) {
576                     Boolean found = false;
577                     String name = cancelInput.getServiceName();
578                     if ((name != null) && !servicePathList.isEmpty()) {
579                         for (ServicePaths service : servicePathList) {
580                             if (name.compareTo(service.getServicePathName()) == 0) {
581                                 LOG.info("ServicePaths found in ServicePathList !!!");
582                                 found = true;
583                                 break;
584                             }
585                         }
586                         if (found) {
587                             LOG.info("removing servicePaths from datastore ...");
588                             if (writeOrDeleteServicePathList(name,1)) {
589                                 LOG.info("Service deleted !");
590                                 setSuccess(true);
591                                 output = true;
592                             } else {
593                                 LOG.info("service deletion failed !");
594                             }
595                         }
596                     } else {
597                         LOG.info("serviceName is null or servicePathList is empty !");
598                     }
599                 } else {
600                     LOG.info("cancelresourcereserveinput parameter not valid !");
601                 }
602                 return output;
603             }
604         });
605     }
606
607     public ListenableFuture<Boolean> pathComputation() {
608         LOG.info("In pathComputation request ...");
609         setSuccess(false);
610         return executor.submit(new Callable<Boolean>() {
611             @Override
612             public Boolean call() throws Exception {
613                 Boolean output = false;
614                 List<PathDescriptions> pathsList = new ArrayList<PathDescriptions>();
615                 PathDescriptions path = null;
616                 int index ;
617                 Boolean constraints = false;
618                 if (input != null) {
619                     HardConstraints inputHard = input.getHardConstraints();
620                     SoftConstraints inputSoft = input.getSoftConstraints();
621                     if ((inputHard != null) || (inputSoft != null)) {
622                         constraints = true;
623                     }
624                     path = null;
625                     pathsList =  retrievePath(input.getServiceAEnd().getNodeId(), input.getServiceZEnd()
626                             .getNodeId());
627                     index = 0;
628                     output = false;
629                     /** get pathList ordered. */
630                     pathsList = orderPathdescriptionsList(pathsList);
631                     if (!pathsList.isEmpty()) {
632                         LOG.info("{} Paths get from Pathdescription List", pathsList.size());
633                         index = 0;
634                         output = false;
635                         while (index < pathsList.size()) {
636                             path = pathsList.get(index);
637                             LOG.info("path n°{} gets : '{}'!", index, path.getPathName());
638                             if (constraints) {
639                                 LOG.info("Calculating path with constraints ...");
640                                 if (inputHard.getCoRoutingOrGeneral() instanceof General) {
641                                     General general = (General)inputHard.getCoRoutingOrGeneral();
642                                     if (general != null) {
643                                         Diversity diversity = general.getDiversity();
644                                         if (diversity != null) {
645                                             LOG.info("Getting diversity ...");
646                                             List<String> existingService = diversity.getExistingService();
647                                             if (existingService.size() > 0) {
648                                                 LOG.info("Getting existing service applicability ...");
649                                                 int choice = -1;
650                                                 if ((choice < 0)
651                                                         && diversity.getExistingServiceApplicability().isNode()) {
652                                                     LOG.info("existing-service-applicability : Node");
653                                                     choice = 0;
654                                                 }
655                                                 if ((choice < 0)
656                                                         && diversity.getExistingServiceApplicability().isClli()) {
657                                                     LOG.info("existing-service-applicability : Clli");
658                                                     choice = 1;
659                                                 }
660                                                 if ((choice < 0)
661                                                         && diversity.getExistingServiceApplicability().isSrlg()) {
662                                                     LOG.info("existing-service-applicability : Srlg");
663                                                     choice = 2;
664                                                 }
665                                                 if (!diversityService(existingService, path, choice)) {
666                                                     error = "existing service applicability not satisfied";
667                                                     LOG.info(error);
668                                                     path = null;
669                                                 }
670                                             }
671                                         }
672                                         Exclude exclude = general.getExclude();
673                                         if (exclude != null) {
674                                             LOG.info("Getting exclude ...");
675                                             if (!excludeNode(path, exclude.getNodeId())) {
676                                                 error = "Exclude node constraints not satisfied !";
677                                                 LOG.info(error);
678                                                 path = null;
679                                             }
680                                         }
681                                     }
682                                 }
683                             }
684                             if (!testPathDescription(path)) {
685                                 LOG.info("Process finish !");
686                                 output = true;
687                                 break;
688                             }
689                             index++;
690                         }
691                     } else {
692                         LOG.info("failed to retrieve path from PathDescription List !");
693                     }
694                 } else {
695                     LOG.info("pathComputationRequestInput parameter not valid !");
696                 }
697                 if (path != null) {
698                     LOG.info("Path ok !");
699                     pathDescription = new PathDescriptionBuilder()
700                             .setAToZDirection(path.getAToZDirection())
701                             .setZToADirection(path.getZToADirection());
702                     if (input.isResourceReserve()) {
703                         LOG.info("reserving pce resource ...");
704                         setPathDescription(pathDescription);
705                         if (writeOrDeleteServicePathList(input.getServiceName(), 0)) {
706                             LOG.info("write ServicePaths to datastore");
707                             setSuccess(true);
708                         } else {
709                             LOG.error("writing ServicePaths to datastore failed ! ");
710                         }
711                     } else {
712                         LOG.info("no pce resource reserve !");
713                         setSuccess(true);
714                     }
715                 }
716                 return output;
717             }
718         });
719     }
720
721
722     /**
723      * get all ServicePaths in ServicePathlist.
724      *
725      * @return <code>ServicePaths List</code>
726      */
727     private List<ServicePaths> readServicePathList() {
728         LOG.info("Reading ServicePathList ...");
729         List<ServicePaths> result = null;
730         ReadOnlyTransaction readTx = db.newReadOnlyTransaction();
731         InstanceIdentifier<ServicePathList> iid = InstanceIdentifier.create(ServicePathList.class);
732         Future<Optional<ServicePathList>> future = readTx.read(LogicalDatastoreType.OPERATIONAL,iid);
733         Optional<ServicePathList> optional = Optional.absent();
734         try {
735             optional = Futures.getChecked(future, ExecutionException.class, 60, TimeUnit.SECONDS);
736         } catch (ExecutionException e) {
737             LOG.error("Reading service failed:", e);
738         }
739         if (optional.isPresent()) {
740             LOG.info("ServicePath List present !");
741             result = optional.get().getServicePaths();
742         }
743         return result;
744     }
745
746
747     private List<PathDescriptions> readPathDescriptionList() {
748         LOG.info("Reading PathDescriptionsList ...");
749         List<PathDescriptions> result = null;
750         ReadOnlyTransaction readTx = db.newReadOnlyTransaction();
751         InstanceIdentifier<PathDescriptionList> iid = InstanceIdentifier.create(PathDescriptionList.class);
752         Future<Optional<PathDescriptionList>> future = readTx.read(LogicalDatastoreType.OPERATIONAL,iid);
753         Optional<PathDescriptionList> optional = Optional.absent();
754         try {
755             optional = Futures.getChecked(future, ExecutionException.class, 60, TimeUnit.SECONDS);
756         } catch (ExecutionException e) {
757             LOG.error("Reading service failed:", e);
758         }
759         if (optional.isPresent()) {
760             LOG.info("ServicePath List present !");
761             result = optional.get().getPathDescriptions();
762         }
763         return result;
764
765     }
766
767     /**
768      * Write or Delete ServicePaths
769      * for ServicePathList.
770      *
771      * @param serviceName Service Name
772      * @param choice 0 : write or 1 : delete
773      * @return Boolean result true if deleted, false if not
774      */
775     private Boolean writeOrDeleteServicePathList(String serviceName, int choice) {
776         Boolean result = null;
777         if ((serviceName != null) && (serviceName.compareTo(" ") != 0) && (choice >= 0) && (choice < 2)) {
778             LOG.info("WriteOrDeleting '{}' ServicePaths", serviceName);
779             WriteTransaction writeTx = db.newWriteOnlyTransaction();
780             result = true;
781             String action = null;
782             InstanceIdentifier<ServicePaths> iid = InstanceIdentifier.create(ServicePathList.class)
783                     .child(ServicePaths.class,new ServicePathsKey(serviceName));
784             Future<Void> future = null;
785             switch (choice) {
786                 case 0: /** Write. */
787                     LOG.info("Writing '{}' Service", serviceName);
788                     org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.service.types.rev170426.service
789                         .path.PathDescriptionBuilder path = new org.opendaylight.yang.gen.v1.http.org.transportpce.b.c
790                         ._interface.service.types.rev170426.service.path.PathDescriptionBuilder();
791                     if (pathDescription != null) {
792                         if (pathDescription.getAToZDirection() != null) {
793                             path.setAToZDirection(pathDescription.getAToZDirection());
794                         }
795                         if (pathDescription.getZToADirection() != null) {
796                             path.setZToADirection(pathDescription.getZToADirection());
797                         }
798                         LOG.info("pathdescription gets");
799                     }
800                     ServiceAEnd aend = new org.opendaylight.yang.gen.v1.http.org.transportpce.b.c
801                             ._interface.service.types.rev170426.service.path.ServiceAEndBuilder(input.getServiceAEnd())
802                             .build();
803                     ServiceZEnd zend = new org.opendaylight.yang.gen.v1.http.org.transportpce.b.c
804                             ._interface.service.types.rev170426.service.path.ServiceZEndBuilder(input.getServiceZEnd())
805                             .build();
806                     ServicePaths service = new ServicePathsBuilder()
807                             .setServicePathName(serviceName)
808                             .setServiceHandlerHeader(new ServiceHandlerHeaderBuilder()
809                                     .setRequestId(input.getServiceHandlerHeader().getRequestId()).build())
810                             .setServiceAEnd(aend)
811                             .setServiceZEnd(zend)
812                             .setHardConstraints(input.getHardConstraints())
813                             .setSoftConstraints(input.getSoftConstraints())
814                             .setPathDescription(path.build())
815                             .build();
816                     LOG.info("Servicepath build");
817                     writeTx.put(LogicalDatastoreType.OPERATIONAL, iid, service);
818                     action = "write";
819                     //CheckedFuture<Void, OperationFailedException> future = transaction.submit();
820                     future = writeTx.submit();
821                     try {
822                         LOG.info("Sending '{}' command to datastore !", action);
823                         Futures.getChecked(future, ExecutionException.class);
824                     } catch (ExecutionException e) {
825                         LOG.error("Failed to {} service from Service List", action);
826                         result = false;
827                     }
828                     break;
829
830                 case 1: /** Delete */
831                     LOG.info("Deleting '{}' Service", serviceName);
832                     writeTx.delete(LogicalDatastoreType.OPERATIONAL, iid);
833                     action = "delete";
834                     future = writeTx.submit();
835                     try {
836                         LOG.info("Sending '{}' command to datastore !", serviceName);
837                         Futures.getChecked(future, ExecutionException.class);
838                     } catch (ExecutionException e) {
839                         LOG.error("Failed to {} service from Service List", serviceName);
840                         result = false;
841                     }
842                     break;
843
844                 default:
845                     LOG.info("No choice found");
846                     break;
847
848             }
849
850         } else {
851             LOG.info("Parameters not correct !");
852         }
853         return result;
854     }
855
856     public PathDescriptionBuilder getPathDescription() {
857         return pathDescription;
858     }
859
860     public void setPathDescription(PathDescriptionBuilder pathDescription) {
861         this.pathDescription = pathDescription;
862     }
863
864     public Boolean getSuccess() {
865         return success;
866     }
867
868     public void setSuccess(Boolean success) {
869         this.success = success;
870     }
871
872     public PathComputationRequestInput getInput() {
873         return input;
874     }
875
876     public void setInput(PathComputationRequestInput pathComputationRequestInput) {
877         this.input = pathComputationRequestInput;
878     }
879
880     public CancelResourceReserveInput getCancelInput() {
881         return cancelInput;
882     }
883
884     public void setCancelInput(CancelResourceReserveInput cancelResourceReserveInput) {
885         this.cancelInput = cancelResourceReserveInput;
886     }
887
888     public DataBroker getDb() {
889         return db;
890     }
891
892     public void setDb(DataBroker db) {
893         this.db = db;
894     }
895
896     public String getError() {
897         return error;
898     }
899
900     public void setError(String error) {
901         this.error = error;
902     }
903
904     public List<ServicePaths> getServicePathList() {
905         return servicePathList;
906     }
907
908     public void setServicePathList(List<ServicePaths> servicePathList) {
909         this.servicePathList = servicePathList;
910     }
911 }