update verigraph
[parser.git] / verigraph / src / it / polito / neo4j / manager / Neo4jLibrary.java
1 /*******************************************************************************
2  * Copyright (c) 2017 Politecnico di Torino and others.
3  *
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Apache License, Version 2.0
6  * which accompanies this distribution, and is available at
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *******************************************************************************/
9 package it.polito.neo4j.manager;
10
11 import java.io.File;
12 import java.io.FileNotFoundException;
13 import java.io.FileReader;
14 import java.io.IOException;
15 import java.math.BigInteger;
16 import java.util.ArrayList;
17 import java.util.HashMap;
18 import java.util.HashSet;
19 import java.util.Iterator;
20 import java.util.LinkedHashMap;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Properties;
24 import java.util.Set;
25 import java.util.logging.Logger;
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28
29 import org.neo4j.graphalgo.GraphAlgoFactory;
30 import org.neo4j.graphalgo.PathFinder;
31 import org.neo4j.graphdb.Direction;
32 import org.neo4j.graphdb.GraphDatabaseService;
33 import org.neo4j.graphdb.Label;
34 import org.neo4j.graphdb.Node;
35 import org.neo4j.graphdb.NotFoundException;
36 import org.neo4j.graphdb.Path;
37 import org.neo4j.graphdb.PathExpanders;
38 import org.neo4j.graphdb.PropertyContainer;
39 import org.neo4j.graphdb.Relationship;
40 import org.neo4j.graphdb.RelationshipType;
41 import org.neo4j.graphdb.ResourceIterator;
42 import org.neo4j.graphdb.Transaction;
43 import org.neo4j.graphdb.factory.GraphDatabaseFactory;
44 import org.neo4j.graphdb.traversal.Paths;
45
46 import com.fasterxml.jackson.core.JsonGenerationException;
47 import com.fasterxml.jackson.databind.JsonMappingException;
48 import com.fasterxml.jackson.databind.ObjectMapper;
49
50 import it.polito.neo4j.jaxb.Antispam;
51 import it.polito.neo4j.jaxb.Cache;
52 import it.polito.neo4j.jaxb.Configuration;
53 import it.polito.neo4j.jaxb.Dpi;
54 import it.polito.neo4j.jaxb.Elements;
55 import it.polito.neo4j.jaxb.Endhost;
56 import it.polito.neo4j.jaxb.Endpoint;
57 import it.polito.neo4j.jaxb.Fieldmodifier;
58 import it.polito.neo4j.jaxb.Firewall;
59 import it.polito.neo4j.jaxb.FunctionalTypes;
60 import it.polito.neo4j.jaxb.Graph;
61 import it.polito.neo4j.jaxb.Graphs;
62 import it.polito.neo4j.jaxb.Mailclient;
63 import it.polito.neo4j.jaxb.Mailserver;
64 import it.polito.neo4j.jaxb.Nat;
65 import it.polito.neo4j.jaxb.Neighbour;
66 import it.polito.neo4j.jaxb.ObjectFactory;
67 import it.polito.neo4j.jaxb.ProtocolTypes;
68 import it.polito.neo4j.jaxb.Vpnaccess;
69 import it.polito.neo4j.jaxb.Vpnexit;
70 import it.polito.neo4j.jaxb.Webclient;
71 import it.polito.neo4j.jaxb.Webserver;
72 import it.polito.neo4j.manager.Neo4jDBInteraction.NodeType;
73 import it.polito.verigraph.exception.DataNotFoundException;
74 import it.polito.verigraph.service.VerigraphLogger;
75 import it.polito.neo4j.exceptions.DuplicateNodeException;
76 import it.polito.neo4j.exceptions.MyInvalidIdException;
77 import it.polito.neo4j.exceptions.MyInvalidObjectException;
78 import it.polito.neo4j.exceptions.MyNotFoundException;
79
80
81 public class Neo4jLibrary implements Neo4jDBInteraction
82 {
83     private static final int MAX_DEPTH = 50;
84
85
86     private static final RelationshipType ElementRelationship = null;
87
88
89
90     private GraphDatabaseFactory dbFactory;
91     private GraphDatabaseService graphDB;
92     private ObjectFactory obFactory;
93     private static Neo4jLibrary neo4jLib = new Neo4jLibrary();
94     public static VerigraphLogger vlogger = VerigraphLogger.getVerigraphlogger();
95
96     private Neo4jLibrary()
97     {
98         try {
99             FileReader r;
100             Properties p = new Properties();
101             String neo4j_path = System.getProperty("catalina.home");
102
103             if(neo4j_path != null){
104                 r = new FileReader(new File(neo4j_path+File.separator+"/webapps/verigraph/server.properties"));
105
106             }else{
107                 neo4j_path=System.getProperty("user.dir");
108                 r= new FileReader(new File(neo4j_path+File.separator+"/server.properties"));
109             }
110
111             p.load(r);
112             String pathDB = (String) p.get("graphDBPath");
113             dbFactory = new GraphDatabaseFactory();
114             graphDB = dbFactory.newEmbeddedDatabase(new File(neo4j_path + "/neo4j"+File.separator+pathDB));
115             VerigraphLogger.logger.info("Database location is "+ neo4j_path + "/neo4j"+File.separator+pathDB);
116             registerShutdownHook(graphDB);
117             obFactory = new ObjectFactory();
118
119         } catch (FileNotFoundException e1) {
120             e1.printStackTrace();
121         }
122         catch (IOException e) {
123             e.printStackTrace();
124         }
125     }
126
127     //singleton class
128     public static Neo4jLibrary getNeo4jLibrary(){
129         return neo4jLib;
130     }
131
132     private static void registerShutdownHook(final GraphDatabaseService graphDB)
133     {
134         // Registers a shutdown hook for the Neo4j instance so that it shuts down
135         // nicely when the VM exits (even if you "Ctrl-C" the running application).
136         Runtime.getRuntime().addShutdownHook(new Thread()
137         {
138             @Override
139             public void run()
140             {
141                 graphDB.shutdown();
142             }
143         });
144     }
145
146     public void createGraphs(Graphs graphs) throws MyNotFoundException, MyInvalidIdException
147     {
148         for (Graph graph : graphs.getGraph())
149         {
150             createGraph(graph);
151         }
152     }
153
154     public Graph createGraph(Graph graph) throws MyNotFoundException, MyInvalidIdException{
155         Transaction tx = graphDB.beginTx();
156
157         try
158         {
159             Node nffgRoot = graphDB.createNode(NodeType.Nffg);
160             nffgRoot.setProperty("id", nffgRoot.getId());
161             graph.setId(nffgRoot.getId());
162
163             for(it.polito.neo4j.jaxb.Node nodo : graph.getNode()){
164                 Node newNode = createNode(nffgRoot, nodo, graph);
165                 nodo.setId(newNode.getId());
166                 it.polito.neo4j.jaxb.Configuration c=nodo.getConfiguration();
167                 Node newConf=createConfiguration(newNode, c);
168                 c.setId(newConf.getId());
169
170             }
171
172             //modify  the neighbours id inserting the relationship
173
174             for(it.polito.neo4j.jaxb.Node nodo : graph.getNode()){
175                 Map<String, Neighbour> neighs = addNeighbours(nodo, graph);
176
177                 for(Neighbour neig : nodo.getNeighbour()){
178                     Neighbour n = neighs.get(neig.getName());
179                     neig.setId(n.getId());
180
181                 }
182
183             }
184
185             tx.success();
186
187         }
188         finally
189         {
190             tx.close();
191
192         }
193         return graph;
194     }
195
196     private Node createConfiguration(Node newNode, Configuration c) throws MyInvalidIdException {
197
198         Node newConf=graphDB.createNode(NodeType.Configuration);
199         newConf.setProperty("name", c.getName());
200         newConf.setProperty("id", newConf.getId());
201         c.setId(newConf.getId());
202         if(c.getDescription()!=null)
203             newConf.setProperty("description", c.getDescription());
204
205         Relationship r=newConf.createRelationshipTo(newNode, RelationType.ConfigurationRelantionship);
206         r.setProperty("id", newNode.getId());
207         setConfiguration(newConf, c.getName().toUpperCase(), c);
208
209         return newConf;
210
211     }
212
213     private void setConfiguration(Node newConf, String type, it.polito.neo4j.jaxb.Configuration c) throws MyInvalidIdException {
214
215         switch(type){
216
217         case "FIREWALL":{
218             List<Elements> list=c.getFirewall().getElements();
219             if(!list.isEmpty()){
220                 for(Elements e : list){
221                     Node newElem=graphDB.createNode(NodeType.Firewall);
222                     newElem.setProperty("source", e.getSource());
223                     newElem.setProperty("destination", e.getDestination());
224
225                     Relationship firewall=newElem.createRelationshipTo(newConf, RelationType.ElementRelationship);
226                     firewall.setProperty("id", newConf.getId());
227                 }
228
229             }else{
230                 vlogger.logger.info("Configuration firewall empty");
231
232             }
233             break;
234         }
235
236         case "ANTISPAM":{
237             List<String> list=c.getAntispam().getSource();
238             if(!list.isEmpty()){
239                 for(String s : list){
240                     Node newElem=graphDB.createNode(NodeType.Antispam);
241                     newElem.setProperty("source", s);
242                     Relationship antispam=newElem.createRelationshipTo(newConf, RelationType.ElementRelationship);
243                     antispam.setProperty("id", newConf.getId());
244                 }
245
246             }else{
247                 vlogger.logger.info("Configuration Antispam empty");
248
249             }
250             break;
251
252         }
253         case "CACHE":{
254             List<String> list=c.getCache().getResource();
255             if(!list.isEmpty()){
256                 for(String s : list){
257                     Node newElem=graphDB.createNode(NodeType.Cache);
258                     newElem.setProperty("resource", s);
259                     Relationship cache=newElem.createRelationshipTo(newConf, RelationType.ElementRelationship);
260                     cache.setProperty("id", newConf.getId());
261                 }
262             }else{
263                 vlogger.logger.info("Configuration Cache empty");
264
265             }
266             break;
267
268         }
269         case "DPI":{
270             List<String> list=c.getDpi().getNotAllowed();
271             if(!list.isEmpty()){
272                 for(String s : list){
273                     Node newElem=graphDB.createNode(NodeType.DPI);
274                     newElem.setProperty("notAllowed", s);
275                     Relationship dpi=newElem.createRelationshipTo(newConf, RelationType.ElementRelationship);
276                     dpi.setProperty("id", newConf.getId());
277                 }
278             }else{
279                 vlogger.logger.info("Configuration Dpi empty");
280
281             }
282             break;
283         }
284         case "ENDHOST":{
285             String destination=c.getEndhost().getDestination();
286             String body=c.getEndhost().getBody();
287             String email_from=c.getEndhost().getEmailFrom();
288             ProtocolTypes protocol=c.getEndhost().getProtocol();
289             String options=c.getEndhost().getOptions();
290             String url=c.getEndhost().getUrl();
291             BigInteger sequence=c.getEndhost().getSequence();
292             if(destination!=null){
293                 Node dest=graphDB.createNode(NodeType.EndHost);
294                 dest.setProperty("destination", destination);
295                 Relationship d=dest.createRelationshipTo(newConf,  RelationType.ElementRelationship);
296                 d.setProperty("id", newConf.getId());
297                 d.setProperty("name", "destination");
298             }
299             if(body!=null){
300                 Node b=graphDB.createNode(NodeType.EndHost);
301                 b.setProperty("body", body);
302                 Relationship bo=b.createRelationshipTo(newConf,  RelationType.ElementRelationship);
303                 bo.setProperty("id", newConf.getId());
304                 bo.setProperty("name", "body");
305
306             }
307             if(email_from!=null){
308                 Node email=graphDB.createNode(NodeType.EndHost);
309                 email.setProperty("email_from", email_from);
310                 Relationship e_from=email.createRelationshipTo(newConf,  RelationType.ElementRelationship);
311                 e_from.setProperty("id", newConf.getId());
312                 e_from.setProperty("name", "email_from");
313             }
314             if(protocol!=null){
315                 String protocollo=c.getEndhost().getProtocol().value();
316                 Node proto=graphDB.createNode(NodeType.EndHost);
317                 proto.setProperty("protocol", protocollo);
318                 Relationship p=proto.createRelationshipTo(newConf,  RelationType.ElementRelationship);
319                 p.setProperty("id", newConf.getId());
320                 p.setProperty("name", "protocol");
321             }
322             if(options!=null){
323                 Node opt=graphDB.createNode(NodeType.EndHost);
324                 opt.setProperty("options", options);
325                 Relationship o=opt.createRelationshipTo(newConf,  RelationType.ElementRelationship);
326                 o.setProperty("id", newConf.getId());
327                 o.setProperty("name", "options");
328             }
329             if(url!=null){
330                 Node u=graphDB.createNode(NodeType.EndHost);
331                 u.setProperty("url", url);
332                 Relationship ur=u.createRelationshipTo(newConf,  RelationType.ElementRelationship);
333                 ur.setProperty("id", newConf.getId());
334                 ur.setProperty("name", "url");
335             }
336             if(sequence != null && !sequence.equals(BigInteger.ZERO)){
337                 Node seq=graphDB.createNode(NodeType.EndHost);
338                 seq.setProperty("sequence", sequence);
339                 Relationship seque=seq.createRelationshipTo(newConf,  RelationType.ElementRelationship);
340                 seque.setProperty("id", newConf.getId());
341                 seque.setProperty("name", "sequence");
342             }
343
344             break;
345         }
346         case "ENDPOINT":{
347             vlogger.logger.info("It is an ENDPOINT");
348
349             break;
350         }
351         case "FIELDMODIFIER":{
352             vlogger.logger.info("It is a FIELMODIFIER");
353
354             break;
355
356         }
357
358         case "MAILCLIENT":{
359             String list=c.getMailclient().getMailserver();
360             if(list!=null){
361                 Node newElem=graphDB.createNode(NodeType.Mailclient);
362                 newElem.setProperty("mailserver", list);
363                 Relationship mailclient=newElem.createRelationshipTo(newConf, RelationType.ElementRelationship);
364                 mailclient.setProperty("id", newConf.getId());
365             }else{
366                 vlogger.logger.info("Configuration Mailclient empty");
367
368             }
369
370             break;
371         }
372         case "MAILSERVER":{
373             vlogger.logger.info("It is a MAILSERVER");
374
375             break;
376         }
377         case "NAT":{
378
379             List<String> list=c.getNat().getSource();
380             if(!list.isEmpty()){
381                 for(String s : list){
382                     Node newElem=graphDB.createNode(NodeType.NAT);
383                     newElem.setProperty("source", s);
384                     Relationship nat=newElem.createRelationshipTo(newConf, RelationType.ElementRelationship);
385                     nat.setProperty("id", newConf.getId());
386                 }
387             }else{
388                 vlogger.logger.info("Configuration Nat empty");
389
390             }
391             break;
392         }
393
394
395         case "VPNACCESS":{
396             String list=c.getVpnaccess().getVpnexit();
397             if(list!=null){
398                 Node newElem=graphDB.createNode(NodeType.VPNAccess);
399                 newElem.setProperty("vpnexit", list);
400                 Relationship vpnaccess=newElem.createRelationshipTo(newConf, RelationType.ElementRelationship);
401                 vpnaccess.setProperty("id", newConf.getId());
402             }else{
403                 vlogger.logger.info("Configuration Vpnaccess empty");
404
405             }
406
407             break;
408         }
409         case "VPNEXIT":{
410             String list=c.getVpnexit().getVpnaccess();
411             if(list!=null){
412                 Node newElem=graphDB.createNode(NodeType.VPNExit);
413                 newElem.setProperty("vpnaccess", list);
414                 Relationship vpnexit=newElem.createRelationshipTo(newConf, RelationType.ElementRelationship);
415                 vpnexit.setProperty("id", newConf.getId());
416             }else{
417                 vlogger.logger.info("Configuration Vpnexit empty");
418
419             }
420
421             break;
422         }
423         case "WEBCLIENT":{
424             String list=c.getWebclient().getNameWebServer();
425             if(list!=null){
426                 Node newElem=graphDB.createNode(NodeType.Webclient);
427                 newElem.setProperty("webserver", list);
428                 Relationship webclient=newElem.createRelationshipTo(newConf, RelationType.ElementRelationship);
429                 webclient.setProperty("id", newConf.getId());
430             }else{
431                 vlogger.logger.info("Configuration Webclient empty");
432
433             }
434
435             break;
436         }
437         case "WEBSERVER":{
438             vlogger.logger.info("It's a webserver");
439             break;
440         }
441         default:{
442             throw new MyInvalidIdException("Element node "+type+" not valid");
443         }
444         }
445
446     }
447
448     private Node createNode(Node nffgRoot, it.polito.neo4j.jaxb.Node nodo, it.polito.neo4j.jaxb.Graph graph){
449         Node newNode = graphDB.createNode(NodeType.Node);
450         newNode.setProperty("name", nodo.getName());
451         newNode.setProperty("functionalType", nodo.getFunctionalType().value());
452         nodo.setId(newNode.getId());
453         newNode.setProperty("id", newNode.getId());
454         Relationship r=newNode.createRelationshipTo(nffgRoot, RelationType.OwnerRelationship);
455         r.setProperty("id", graph.getId());
456
457         return newNode;
458     }
459
460     private Map<String,Neighbour> addNeighbours(it.polito.neo4j.jaxb.Node nodo, Graph graph) throws MyNotFoundException{
461
462         Node srcNode = graphDB.findNode(NodeType.Node, "id", nodo.getId());
463         if(srcNode==null){
464             throw new DataNotFoundException("Source node (in neighbour node) not found");
465         }
466
467
468         Map<String,Neighbour> neighbours = new HashMap<>();
469
470         for(Neighbour neighbour : nodo.getNeighbour()){
471
472             Node dstNode = findNodeByNameOfSpecificGraph(neighbour.getName(), graph.getId());
473
474             if(dstNode == null)
475                 throw new DataNotFoundException("Destination node (in neighbour node) not found");
476
477             Relationship rel = srcNode.createRelationshipTo(dstNode,RelationType.PathRelationship);
478
479             neighbour.setId(dstNode.getId());
480             rel.setProperty("id", neighbour.getId());
481             neighbours.put((String)dstNode.getProperty("name"),neighbour);
482         }
483         return neighbours;
484     }
485
486     private Node findNodeByIdAndSpecificGraph(long nodoId, long graphId) throws MyNotFoundException {
487
488         Node node=graphDB.findNode(NodeType.Node, "id", nodoId);
489         Node n;
490
491         if(node == null)
492             throw new DataNotFoundException("There is no Node whose Id is '" + nodoId + "'");
493         else{
494
495             for(Relationship rel : node.getRelationships(RelationType.OwnerRelationship)){
496                 Node[] nodi = rel.getNodes();
497                 if(nodi[0].getId() == graphId || nodi[1].getId() == graphId){
498                     if((long)rel.getProperty("id") == graphId)
499                         return node;
500
501                 }
502
503             }
504         }
505         return node;
506     }
507
508     private Node findNodeByNameOfSpecificGraph(String nodeName, long graphId){
509
510         ResourceIterator<Node> nodes = graphDB.findNodes(NodeType.Node, "name", nodeName);
511         while (nodes.hasNext()){
512             Node n = nodes.next();
513             for(Relationship rel : n.getRelationships(RelationType.OwnerRelationship)){
514                 Node[] nodi = rel.getNodes();
515                 if((nodi[0].getId() == graphId || nodi[1].getId()== graphId)){
516                     if((long)rel.getProperty("id") == graphId)
517                         return n;
518                 }
519             }
520         }
521         return null;
522     }
523
524     public it.polito.neo4j.jaxb.Node createNode(it.polito.neo4j.jaxb.Node node, long graphId) throws MyNotFoundException, DuplicateNodeException, MyInvalidIdException{
525         Node graph;
526         Transaction tx = graphDB.beginTx();
527
528
529         try{
530             graph = findGraph(graphId);
531             Graph myGraph = getGraph(graphId);
532             if(DuplicateNode(node,myGraph))
533                 throw new DuplicateNodeException("This node is already present");
534             Node newNode = createNode(graph,node,myGraph);
535             node.setId(newNode.getId());
536             it.polito.neo4j.jaxb.Configuration c=node.getConfiguration();
537             Node newConf=createConfiguration(newNode, c);
538             c.setId(newConf.getId());
539             Map<String, Neighbour> neighs = addNeighbours(node, myGraph);
540             for(Neighbour neig : node.getNeighbour()){
541                 Neighbour n = neighs.get(neig.getName());
542                 neig.setId(n.getId());
543             }
544
545             tx.success();
546         }
547         finally{
548             tx.close();
549         }
550         return node;
551     }
552
553     private boolean DuplicateNode(it.polito.neo4j.jaxb.Node node, Graph myGraph) {
554         for(it.polito.neo4j.jaxb.Node n : myGraph.getNode()){
555             if(n.getName().compareTo(node.getName()) == 0)
556                 return true;
557         }
558         return false;
559     }
560
561     public Graphs getGraphs(){
562         Graphs graphs = obFactory.createGraphs();
563         Transaction tx = graphDB.beginTx();
564
565         try{
566             ResourceIterator<Node> graphNodes = graphDB.findNodes(NodeType.Nffg);
567             while(graphNodes.hasNext()){
568                 Node currentGraph = graphNodes.next();
569                 Graph g = getGraph(currentGraph.getId());
570                 graphs.getGraph().add(g);
571             }
572             tx.success();
573         }
574         catch(MyNotFoundException e){
575             //NEVER BEEN HERE
576         }
577         finally{
578             tx.close();
579         }
580         return graphs;
581     }
582
583     public Graph getGraph(long id) throws MyNotFoundException{
584         Graph graph = obFactory.createGraph();
585         Transaction tx = graphDB.beginTx();
586
587         try
588         {
589             findGraph(id);//this method rises an exception if not found graph with Id id
590             graph.setId(id);
591             Set<Node> nodes = retrieveNodesOfSpecificGraph(id);
592
593             for(Node nodo : nodes){
594
595                 graph.getNode().add(retrieveNode(nodo));
596             }
597             tx.success();
598         }
599         catch(MyNotFoundException e){
600             tx.close();
601             throw new MyNotFoundException(e.getMessage());
602         }
603         finally{
604             tx.close();
605         }
606         return graph;
607     }
608
609     private Set<Node> retrieveNodesOfSpecificGraph(long graphId){
610         Set<Node> nodi = new HashSet<>();
611
612         Node nodo;
613         ResourceIterator<Node> nodes = graphDB.findNodes(NodeType.Node);
614         while (nodes.hasNext())
615         {
616             nodo = nodes.next();
617             Relationship rel = nodo.getSingleRelationship(RelationType.OwnerRelationship, Direction.BOTH);
618             if(rel != null){
619                 Node[] nodiRelation = rel.getNodes();
620                 if((nodiRelation[0].getId()==graphId || nodiRelation[1].getId()==graphId))
621                     if((long)rel.getProperty("id")==graphId)
622                         nodi.add(nodo);
623             }
624         }
625         return nodi;
626     }
627
628     private Node findGraph(long graphId) throws MyNotFoundException{
629         Node graph;
630
631         try{
632             graph=graphDB.findNode(NodeType.Nffg, "id", graphId);
633             if(graph==null){
634                 throw new DataNotFoundException("There is no Graph whose Id is '" + graphId + "'");
635
636             }
637         }
638         catch(NotFoundException e){
639             throw new MyNotFoundException("There is no Graph whose Id is '" + graphId + "'");
640         }
641
642         return graph;
643     }
644
645     private Node findNode(long nodeId) throws MyNotFoundException{
646         Node node;
647
648         try{
649             node=graphDB.findNode(NodeType.Node, "id", nodeId);
650             if(node==null)
651                 throw new DataNotFoundException("There is no Node whose Id is '" + nodeId + "'");
652         }
653         catch(NotFoundException e){
654             throw new MyNotFoundException("There is no Node whose Id is '" + nodeId + "'");
655         }
656
657         return node;
658     }
659
660
661     private void addNeighbour(it.polito.neo4j.jaxb.Node src, Node dst, long neighbourId){
662         Neighbour vicino = obFactory.createNeighbour();
663         vicino.setId(neighbourId);
664         vicino.setName((String) dst.getProperty("name"));
665         src.getNeighbour().add(vicino);
666     }
667
668     private it.polito.neo4j.jaxb.Node retrieveNode(Node nodo){
669         it.polito.neo4j.jaxb.Node n = obFactory.createNode();
670
671         n.setId(nodo.getId());
672         n.setName( nodo.getProperty("name").toString());
673         n.setFunctionalType(it.polito.neo4j.jaxb.FunctionalTypes.valueOf((String) nodo.getProperty("functionalType")));
674
675         //retrieve neighbours:
676         Iterable<Relationship> links = nodo.getRelationships(RelationType.PathRelationship, Direction.OUTGOING);
677         Iterator<Relationship> linksIt = links.iterator();
678         while(linksIt.hasNext()){
679             Relationship link = linksIt.next();
680             Node endpoint = link.getEndNode();
681             addNeighbour(n, endpoint, (long)link.getProperty("id"));
682         }
683
684         //retrieve configuration:
685         it.polito.neo4j.jaxb.Configuration c=obFactory.createConfiguration();
686         c=retrieveconfiguration(nodo);
687         n.setConfiguration(c);
688
689         return n;
690     }
691
692     private Configuration retrieveconfiguration(Node nodo) {
693         it.polito.neo4j.jaxb.Configuration c=obFactory.createConfiguration();
694         Relationship rel = nodo.getSingleRelationship(RelationType.ConfigurationRelantionship, Direction.BOTH);
695         if(rel != null){
696             Node conf;
697             Node[] nodiRelation = rel.getNodes();
698             String func_type;
699             if((nodiRelation[0].getId()==nodo.getId() || nodiRelation[1].getId()==nodo.getId())){
700                 if((long)rel.getProperty("id") == nodo.getId()){
701                     if(nodiRelation[0].hasLabel(NodeType.Configuration)){
702                         conf=nodiRelation[0];
703                     }else{
704                         conf=nodiRelation[1];
705                     }
706                     func_type=conf.getProperty("name").toString();
707                     c.setId((long)conf.getProperty("id"));
708                     Object value=conf.getProperty("description", "null");
709                     if(value!="null")
710                         c.setDescription(conf.getProperty("description").toString());
711                     c.setName(func_type);
712                     switch(c.getName().toUpperCase()){
713
714                     case "FIREWALL":{
715                         Iterable<Relationship> confs= conf.getRelationships(RelationType.ElementRelationship);
716                         Iterator<Relationship> confsIt = confs.iterator();
717                         Firewall firewall=new Firewall();
718                         List<Elements> element_list=new ArrayList<Elements>();
719                         while(confsIt.hasNext()){
720                             Relationship relConf = confsIt.next();
721                             Node element = relConf.getStartNode();
722                             if(element.hasLabel(NodeType.Firewall)){
723                                 Elements e=new Elements();
724                                 e.setDestination(element.getProperty("destination").toString());
725                                 e.setSource(element.getProperty("source").toString());
726                                 element_list.add(e);
727                             }
728                         }
729                         firewall.getElements().addAll(element_list);
730                         c.setFirewall(firewall);
731                         break;
732
733                     }
734
735                     case "ANTISPAM":{
736                         Iterable<Relationship> confs= conf.getRelationships(RelationType.ElementRelationship);
737                         Iterator<Relationship> confsIt = confs.iterator();
738                         Antispam antispam=new Antispam();
739                         List<String> source=new ArrayList<String>();
740                         while(confsIt.hasNext()){
741                             Relationship relConf = confsIt.next();
742                             Node element = relConf.getStartNode();
743                             if(element.hasLabel(NodeType.Antispam)){
744                                 String s=element.getProperty("source").toString();
745                                 source.add(s);
746                             }
747                         }
748                         antispam.getSource().addAll(source);
749                         c.setAntispam(antispam);
750                         break;
751                     }
752
753                     case "CACHE":{
754                         Iterable<Relationship> confs= conf.getRelationships(RelationType.ElementRelationship);
755                         Iterator<Relationship> confsIt = confs.iterator();
756                         Cache cache=new Cache();
757                         List<String> resource=new ArrayList<String>();
758                         while(confsIt.hasNext()){
759                             Relationship relConf = confsIt.next();
760                             Node element = relConf.getStartNode();
761                             if(element.hasLabel(NodeType.Cache)){
762                                 String s=element.getProperty("resource").toString();
763                                 resource.add(s);
764                             }
765                         }
766                         cache.getResource().addAll(resource);
767                         c.setCache(cache);
768                         break;
769                     }
770                     case "DPI":{
771                         Iterable<Relationship> confs= conf.getRelationships(RelationType.ElementRelationship);
772                         Iterator<Relationship> confsIt = confs.iterator();
773                         Dpi dpi=new Dpi();
774                         List<String> notAllowed=new ArrayList<String>();
775                         while(confsIt.hasNext()){
776                             Relationship relConf = confsIt.next();
777                             Node element = relConf.getStartNode();
778                             if(element.hasLabel(NodeType.DPI)){
779                                 String s=element.getProperty("notAllowed").toString();
780                                 notAllowed.add(s);
781                             }
782                         }
783                         dpi.getNotAllowed().addAll(notAllowed);
784                         c.setDpi(dpi);
785                         break;
786                     }
787
788                     case "ENDHOST":{
789                         Iterable<Relationship> confs= conf.getRelationships(RelationType.ElementRelationship);
790                         Iterator<Relationship> confsIt = confs.iterator();
791                         Endhost endhost=new Endhost();
792                         String destination=new String();
793                         String body=new String();
794                         String email_from=new String();
795                         String protocol=new String();
796                         String options=new String();
797                         String url=new String();
798                         BigInteger sequence=null;
799                         while(confsIt.hasNext()){
800                             Relationship relConf = confsIt.next();
801                             Node element = relConf.getStartNode();
802                             if(element.hasLabel(NodeType.EndHost)){
803                                 String type=relConf.getProperty("name").toString();
804                                 if(type.compareTo("destination")==0){
805                                     destination=element.getProperty("destination").toString();
806                                 }else 
807                                     if(type.compareTo("body")==0){
808                                         body=element.getProperty("body").toString();
809                                     }else
810                                         if(type.compareTo("email_from")==0){
811                                             email_from=element.getProperty("email_from").toString();
812                                         }else
813                                             if(type.compareTo("protocol")==0){
814                                                 protocol=element.getProperty("protocol").toString();
815                                             }else
816                                                 if(type.compareTo("options")==0){
817                                                     options=element.getProperty("options").toString();
818                                                 }else
819                                                     if(type.compareTo("url")==0){
820                                                         url=element.getProperty("url").toString();
821                                                     }else
822                                                         if(type.compareTo("sequence")==0){
823                                                             sequence=new BigInteger((byte[]) element.getProperty("sequence"));
824                                                         }
825
826                             }
827                         }
828
829                         endhost.setBody(body);
830                         endhost.setDestination(destination);
831                         endhost.setEmailFrom(email_from);
832                         endhost.setOptions(options);
833                         endhost.setSequence(sequence);
834                         endhost.setUrl(url);
835                         if(!protocol.isEmpty())
836                             endhost.setProtocol(ProtocolTypes.fromValue(protocol));
837                         c.setEndhost(endhost);
838                         break;
839                     }
840
841                     case "ENDPOINT":{
842                         Endpoint endpoint=new Endpoint();
843                         c.setEndpoint(endpoint);
844                         break;
845                     }
846
847                     case "FIELDMODIFIER":{
848
849                         Fieldmodifier field=new Fieldmodifier();
850                         c.setFieldmodifier(field);
851                         break;
852                     }
853                     case "MAILCLIENT":{
854                         Iterable<Relationship> confs= conf.getRelationships(RelationType.ElementRelationship);
855                         Iterator<Relationship> confsIt = confs.iterator();
856                         Mailclient mailclient=new Mailclient();
857                         String mailserver= new String();
858                         while(confsIt.hasNext()){
859                             Relationship relConf = confsIt.next();
860                             Node element = relConf.getStartNode();
861                             if(element.hasLabel(NodeType.Mailclient)){
862                                 mailserver=element.getProperty("mailserver").toString();
863                             }
864                         }
865                         mailclient.setMailserver(mailserver);
866                         c.setMailclient(mailclient);
867                         break;
868                     }
869
870                     case "MAILSERVER":{
871
872                         Mailserver mailserver=new Mailserver();
873                         c.setMailserver(mailserver);
874                         break;
875                     }
876
877                     case "NAT":{
878                         Iterable<Relationship> confs= conf.getRelationships(RelationType.ElementRelationship);
879                         Iterator<Relationship> confsIt = confs.iterator();
880                         Nat nat=new Nat();
881                         List<String> list=new ArrayList<String>();
882                         while(confsIt.hasNext()){
883                             Relationship relConf = confsIt.next();
884                             Node element = relConf.getStartNode();
885                             if(element.hasLabel(NodeType.NAT)){
886                                 String s=element.getProperty("source").toString();
887                                 list.add(s);
888                             }
889                         }
890                         nat.getSource().addAll(list);
891                         c.setNat(nat);
892                         break;
893                     }
894
895                     case "VPNACCESS":{
896
897                         Iterable<Relationship> confs= conf.getRelationships(RelationType.ElementRelationship);
898                         Iterator<Relationship> confsIt = confs.iterator();
899                         Vpnaccess vpnaccess=new Vpnaccess();
900                         String vpnexit= new String();
901                         while(confsIt.hasNext()){
902                             Relationship relConf = confsIt.next();
903                             Node element = relConf.getStartNode();
904                             if(element.hasLabel(NodeType.VPNAccess)){
905                                 vpnexit=element.getProperty("vpnexit").toString();
906                             }
907                         }
908                         vpnaccess.setVpnexit(vpnexit);
909                         c.setVpnaccess(vpnaccess);
910                         break;
911                     }
912
913                     case "VPNEXIT":{
914
915                         Iterable<Relationship> confs= conf.getRelationships(RelationType.ElementRelationship);
916                         Iterator<Relationship> confsIt = confs.iterator();
917                         Vpnexit vpnexit=new Vpnexit();
918                         String vpnaccess= new String();
919                         while(confsIt.hasNext()){
920                             Relationship relConf = confsIt.next();
921                             Node element = relConf.getStartNode();
922                             if(element.hasLabel(NodeType.VPNExit)){
923                                 vpnaccess=element.getProperty("vpnaccess").toString();
924                             }
925                         }
926                         vpnexit.setVpnaccess(vpnaccess);
927                         c.setVpnexit(vpnexit);
928                         break;
929                     }
930
931                     case "WEBCLIENT":{
932                         Iterable<Relationship> confs= conf.getRelationships(RelationType.ElementRelationship);
933                         Iterator<Relationship> confsIt = confs.iterator();
934                         Webclient webclient=new Webclient();
935                         String webserver= new String();
936                         while(confsIt.hasNext()){
937                             Relationship relConf = confsIt.next();
938                             Node element = relConf.getStartNode();
939                             if(element.hasLabel(NodeType.Webclient)){
940                                 webserver=element.getProperty("webserver").toString();
941                             }
942                         }
943                         webclient.setNameWebServer(webserver);
944                         c.setWebclient(webclient);
945                         break;
946                     }
947
948                     case "WEBSERVER":{
949
950                         Webserver webserver=new Webserver();
951                         c.setWebserver(webserver);
952                         break;
953                     }
954
955
956
957
958                     }
959
960                 }
961             }
962
963         }else{
964             vlogger.logger.info("Not valid functional type");
965
966         }
967         return c;
968     }
969
970     public void deleteGraph(long id) throws MyNotFoundException{
971         Node graph;
972         Transaction tx = graphDB.beginTx();
973
974         try{
975             graph = findGraph(id);
976             for(Relationship rel: graph.getRelationships(RelationType.OwnerRelationship)){
977                 Node[] nodes = rel.getNodes();
978                 if(nodes[0].hasLabel(NodeType.Node))
979                     deleteNode(nodes[0]);
980                 else
981                     deleteNode(nodes[1]);
982             }
983             deleteNode(graph);
984             tx.success();
985         }
986         finally{
987             tx.close();
988         }
989     }
990
991     private void deleteNode(Node n)
992     {
993         n.getAllProperties().clear();
994
995         deleteConfiguration(n);
996
997         for (Relationship r : n.getRelationships())
998         {
999             r.getAllProperties().clear();
1000             r.delete();
1001         }
1002
1003         n.delete();
1004     }
1005
1006     private void deleteConfiguration(Node n) {
1007         //delete configuration
1008         Relationship rel = n.getSingleRelationship(RelationType.ConfigurationRelantionship, Direction.BOTH);
1009         if(rel != null){
1010             Node conf=rel.getStartNode();
1011             Iterable<Relationship> confs= conf.getRelationships(RelationType.ElementRelationship);
1012             Iterator<Relationship> confsIt = confs.iterator();
1013             while(confsIt.hasNext()){
1014                 Relationship relConf = confsIt.next();
1015                 Node element = relConf.getStartNode();
1016                 element.getAllProperties().clear();
1017                 relConf.getAllProperties().clear();
1018                 relConf.delete();
1019                 element.delete();
1020             }
1021             conf.getAllProperties().clear();
1022             conf.delete();
1023             rel.getAllProperties().clear();
1024             rel.delete();
1025         }
1026
1027     }
1028
1029     public void deleteNode(long graphId, long nodeId) throws MyNotFoundException{
1030         Node nodo;
1031         Transaction tx = graphDB.beginTx();
1032
1033         try{
1034             findGraph(graphId);
1035             nodo = findNode(nodeId);
1036             if(nodo==null){
1037                 tx.failure();
1038                 throw new MyNotFoundException("There is no Node whose id is '" + nodeId+"'");
1039             }
1040
1041
1042             deleteNode(nodo);
1043             tx.success();
1044         }
1045         finally{
1046             tx.close();
1047         }
1048     }
1049
1050     public it.polito.neo4j.jaxb.Node getNode(long graphId, String nodeName) throws MyNotFoundException{
1051         Node nodo;
1052         Transaction tx = graphDB.beginTx();
1053
1054         try{
1055             findGraph(graphId);
1056             nodo = findNodeByNameOfSpecificGraph(nodeName, graphId);
1057             if(nodo==null)
1058                 return null;
1059
1060             else{
1061                 tx.success();
1062                 return retrieveNode(nodo);
1063             }
1064         }
1065         catch(MyNotFoundException e){
1066             tx.close();
1067             throw new MyNotFoundException(e.getMessage());
1068         }
1069         finally{
1070             tx.close();
1071         }
1072     }
1073
1074     public it.polito.neo4j.jaxb.Node getNode(long graphId, long nodeId) throws MyNotFoundException{
1075         Node nodo;
1076         Transaction tx = graphDB.beginTx();
1077
1078         try{
1079             findGraph(graphId);
1080             nodo = findNode(nodeId);
1081             tx.success();
1082             return retrieveNode(nodo);
1083         }
1084         catch(MyNotFoundException e){
1085             tx.close();
1086             throw new MyNotFoundException(e.getMessage());
1087         }
1088         finally{
1089             tx.close();
1090         }
1091     }
1092     public Set<it.polito.neo4j.jaxb.Node> getNodes(long graphId) throws MyNotFoundException{
1093         Node graph;
1094         Transaction tx = graphDB.beginTx();
1095         Set<it.polito.neo4j.jaxb.Node> set = new HashSet<>();
1096
1097         try{
1098             graph = findGraph(graphId);
1099             for(Relationship rel : graph.getRelationships(RelationType.OwnerRelationship)){
1100                 Node[] nodes = rel.getNodes();
1101                 it.polito.neo4j.jaxb.Node nodeAdded=null;
1102                 for(Label l: nodes[0].getLabels()){
1103                     if(l.name().compareTo(NodeType.Nffg.name())==0){
1104                         nodeAdded = retrieveNode(nodes[1]);
1105                     }else{
1106                         nodeAdded = retrieveNode(nodes[0]);
1107                     }
1108                 }
1109                 set.add(nodeAdded);
1110             }
1111             tx.success();
1112         }
1113         finally{
1114             tx.close();
1115         }
1116         return set;
1117     }
1118
1119     public Neighbour createNeighbour(Neighbour neighbour, long graphId, long nodeId) throws MyNotFoundException{
1120         Node nodosrc,nododst;
1121         Transaction tx = graphDB.beginTx();
1122
1123         try{
1124             findGraph(graphId);
1125             nodosrc=findNode(nodeId);
1126             nododst = findNodeByNameOfSpecificGraph(neighbour.getName(), graphId);
1127             if(nododst == null){
1128                 tx.failure();
1129                 throw new MyNotFoundException("There is no Node whose name is '" + neighbour.getName() + "'");
1130             }
1131             Relationship rel = nodosrc.createRelationshipTo(nododst,RelationType.PathRelationship);
1132             rel.setProperty("id", neighbour.getId());
1133             tx.success();
1134         }
1135         finally{
1136             tx.close();
1137         }
1138         return neighbour;
1139     }
1140
1141     public Set<Neighbour> getNeighbours(long graphId, long nodeId) throws MyNotFoundException{
1142         Node nodo;
1143         Transaction tx = graphDB.beginTx();
1144         Set<Neighbour> set = new HashSet<>();
1145
1146         try{
1147             findGraph(graphId);
1148             nodo = findNode(nodeId);
1149             for(Relationship rel : nodo.getRelationships(Direction.OUTGOING,RelationType.PathRelationship)){
1150                 Neighbour newNeigh = obFactory.createNeighbour();
1151                 Node endpoint = rel.getEndNode();
1152                 newNeigh.setName((String)endpoint.getProperty("name"));
1153                 newNeigh.setId((long)rel.getProperty("id"));
1154                 set.add(newNeigh);
1155             }
1156             tx.success();
1157             return set;
1158         }
1159         finally{
1160             tx.close();
1161         }
1162     }
1163
1164     public Neighbour getNeighbour(long graphId, long nodeId, long neighbourId) throws MyNotFoundException{
1165         Node nodo;
1166         Transaction tx = graphDB.beginTx();
1167         Neighbour newNeigh = obFactory.createNeighbour();
1168
1169         try{
1170             findGraph(graphId);
1171             nodo = findNeighbourNode(nodeId);
1172             if(nodo!=null){
1173                 for(Relationship rel : nodo.getRelationships(Direction.OUTGOING, RelationType.PathRelationship)){
1174                     if((long)rel.getProperty("id") == neighbourId){
1175                         Node endpoint = rel.getEndNode();
1176                         newNeigh.setName((String)endpoint.getProperty("name"));
1177                         newNeigh.setId((long)rel.getProperty("id"));
1178                         tx.success();
1179                         tx.close();
1180                         return newNeigh;
1181                     }
1182                 }
1183             }
1184             //if we arrive at this point it means there is not neighbour ad id neghbourId
1185             tx.failure();
1186             return null;
1187         }
1188         finally{
1189             tx.close();
1190         }
1191     }
1192
1193     private Node findNeighbourNode(long nodeId) throws MyNotFoundException {
1194         Node node;
1195
1196         try{
1197             node=graphDB.findNode(NodeType.Node, "id",nodeId);
1198
1199         }
1200         catch(NotFoundException e){
1201             throw new MyNotFoundException("There is no Node whose Id is '" + nodeId + "'");
1202         }
1203
1204         return node;
1205     }
1206
1207     public void deleteNeighbour(long graphId, long nodeId, long neighbourId) throws MyNotFoundException{
1208         Node nodo;
1209         Transaction tx = graphDB.beginTx();
1210         boolean trovato=false;
1211
1212         try{
1213             findGraph(graphId);
1214             nodo = findNode(nodeId);
1215             for(Relationship rel : nodo.getRelationships(Direction.OUTGOING, RelationType.PathRelationship)){
1216                 if((long)rel.getProperty("id") == neighbourId){
1217                     rel.delete();
1218                     trovato=true;
1219                     break;
1220                 }
1221             }
1222             if(!trovato){
1223                 tx.close();
1224                 throw new MyNotFoundException("There is no Neighbour whose Id is '" + neighbourId + "'");
1225             }
1226             tx.success();
1227         }
1228         finally{
1229             tx.close();
1230         }
1231     }
1232
1233     public it.polito.neo4j.jaxb.Node updateNode(it.polito.neo4j.jaxb.Node node, long graphId, long nodeId) throws MyInvalidObjectException,MyNotFoundException, MyInvalidIdException{
1234         Node nodo;
1235         Transaction tx = graphDB.beginTx();
1236         it.polito.neo4j.jaxb.Node returnedNode;
1237
1238         try{
1239             findGraph(graphId);
1240             nodo = findNode(nodeId);
1241             if(validNode(node,getGraph(graphId)) == false)
1242                 throw new MyInvalidObjectException("Invalid node");
1243             nodo.setProperty("name", node.getName());
1244             nodo.setProperty("functionalType", node.getFunctionalType().value());
1245             for(Neighbour neigh : node.getNeighbour()){
1246                 Neighbour n = updateNeighbour(nodo, neigh, graphId);
1247                 neigh.setId(n.getId());
1248             }
1249
1250             deleteConfiguration(nodo);
1251             createConfiguration(nodo, node.getConfiguration());
1252             returnedNode = retrieveNode(nodo);
1253             tx.success();
1254         }
1255         finally{
1256             tx.close();
1257         }
1258         return returnedNode;
1259     }
1260
1261     private boolean validNode(it.polito.neo4j.jaxb.Node node, Graph graph) {
1262         int cntNeighbour = 0;
1263         for(it.polito.neo4j.jaxb.Node n : graph.getNode()){
1264             if(node.getId().longValue() != n.getId().longValue() && node.getName().compareTo(n.getName()) == 0)
1265                 return false;
1266             if(node.getId() != n.getId()){
1267                 for(Neighbour neigh : node.getNeighbour()){
1268                     if(neigh.getName().compareTo(n.getName()) == 0)
1269                         cntNeighbour++;
1270                 }
1271             }
1272             else{
1273                 for(Neighbour neigh : node.getNeighbour()){
1274                     if(neigh.getName().compareTo(node.getName()) == 0)
1275                         return false;
1276                 }
1277             }
1278         }
1279         if(cntNeighbour == node.getNeighbour().size())
1280             return true;
1281         else
1282             return false;
1283     }
1284
1285     private Neighbour updateNeighbour(Node nodo, Neighbour neigh, long graphId){
1286         Node dst = findNodeByNameOfSpecificGraph(neigh.getName(), graphId);
1287
1288         try{
1289             boolean trovato = false;
1290             Iterable<Relationship> rels = nodo.getRelationships(Direction.OUTGOING, RelationType.PathRelationship);
1291             Iterator<Relationship> relIt = rels.iterator();
1292             if(neigh.getId() != null){
1293                 while(relIt.hasNext()){
1294                     Relationship r = relIt.next();
1295                     if((long)r.getProperty("id") == neigh.getId()){
1296                         trovato = true;
1297                         break;
1298                     }
1299                 }
1300             }
1301             if(!trovato)
1302                 throw new NotFoundException();
1303             //graphDB.getRelationshipById(neigh.getId());
1304             try {
1305                 changeNeighbour(nodo, neigh, neigh.getId(), graphId);
1306             } catch (MyNotFoundException e) {
1307                 e.printStackTrace();
1308             }
1309             return neigh;
1310         }
1311         catch(NotFoundException e){
1312             Relationship  rel = nodo.createRelationshipTo(dst, RelationType.PathRelationship);
1313             rel.setProperty("id", neigh.getId());
1314         }
1315
1316
1317         return neigh;
1318     }
1319
1320
1321
1322     public Graph updateGraph(Graph graph, long graphId) throws MyNotFoundException,DuplicateNodeException,MyInvalidObjectException, MyInvalidIdException{
1323         Transaction tx = graphDB.beginTx();
1324         Node nodo;
1325         Node graph_old;
1326
1327         try{
1328             graph_old = findGraph(graphId);
1329             for(Relationship rel: graph_old.getRelationships(RelationType.OwnerRelationship)){
1330                 Node[] nodes = rel.getNodes();
1331                 if(nodes[0].hasLabel(NodeType.Node))
1332                     deleteNode(nodes[0]);
1333                 else
1334                     deleteNode(nodes[1]);
1335             }
1336
1337             for(it.polito.neo4j.jaxb.Node tmpnodo : graph.getNode()){
1338                 Node newNode = createNode(graph_old, tmpnodo, graph);
1339                 tmpnodo.setId(newNode.getId());
1340                 it.polito.neo4j.jaxb.Configuration c=tmpnodo.getConfiguration();
1341                 Node newConf=createConfiguration(newNode, c);
1342                 c.setId(newConf.getId());
1343
1344             }
1345
1346             //modify neighbours ids inserting ids relationship
1347
1348
1349             for(it.polito.neo4j.jaxb.Node tmpnodo : graph.getNode()){
1350                 Map<String, Neighbour> neighs = addNeighbours(tmpnodo, graph);
1351
1352                 for(Neighbour neig : tmpnodo.getNeighbour()){
1353                     Neighbour n = neighs.get(neig.getName());
1354                     neig.setId(n.getId());
1355
1356                 }
1357
1358
1359             }
1360
1361             tx.success();
1362         }
1363         finally{
1364             tx.close();
1365         }
1366         return graph;
1367     }
1368
1369
1370
1371     private boolean ValidGraph(Graph graph) {
1372         if (duplicateNodesInsideGraph(graph))
1373             return false;
1374         for(it.polito.neo4j.jaxb.Node n :graph.getNode()){
1375             int cnt = 0;
1376             for(Neighbour neig : n.getNeighbour()){
1377                 if(neig.getName().compareTo(n.getName()) == 0)
1378                     return false;
1379                 for(it.polito.neo4j.jaxb.Node n2 : graph.getNode()){
1380                     if(neig.getName().compareTo(n2.getName()) == 0){
1381                         cnt++;
1382                         break;
1383                     }
1384                 }
1385             }
1386             if(cnt != n.getNeighbour().size())
1387                 return false;
1388         }
1389         return true;
1390     }
1391
1392     private boolean duplicateNodesInsideGraph(Graph graph) {
1393         for(it.polito.neo4j.jaxb.Node n :graph.getNode()){
1394             for(it.polito.neo4j.jaxb.Node n2 : graph.getNode()){
1395                 if(n!=n2  && n.getName().compareTo(n2.getName()) == 0)
1396                     return true;
1397             }
1398         }
1399         return false;
1400     }
1401
1402
1403     public it.polito.neo4j.jaxb.Node updateNeighbour(Neighbour neighbour, long graphId, long nodeId, long neighbourId) throws MyInvalidObjectException,MyNotFoundException{
1404         Node nodo;
1405         Transaction tx = graphDB.beginTx();
1406         it.polito.neo4j.jaxb.Node returnedNode;
1407
1408         try{
1409             findGraph(graphId);
1410             nodo = findNode(nodeId);
1411             if(validNeighbour(neighbour,getGraph(graphId),getNode(graphId, nodeId)) ==  false)
1412                 throw new MyInvalidObjectException("Invalid neighbour");
1413             changeNeighbour(nodo,neighbour,neighbourId,graphId);
1414             returnedNode = retrieveNode(nodo);
1415             tx.success();
1416         }
1417         finally{
1418             tx.close();
1419         }
1420         //return;
1421         return returnedNode;
1422     }
1423
1424     private boolean validNeighbour(Neighbour neighbour, Graph graph, it.polito.neo4j.jaxb.Node node) {
1425         if(neighbour.getName().compareTo(node.getName()) == 0)
1426             return false;
1427         for(it.polito.neo4j.jaxb.Node n : graph.getNode()){
1428             if(neighbour.getName().compareTo(n.getName()) ==  0)
1429                 return true;
1430         }
1431         return false;
1432     }
1433
1434     private void changeNeighbour(Node nodo, Neighbour neigh, long neighbourId, long graphId) throws MyNotFoundException{
1435         boolean trovato = false;
1436         Relationship rel = null;
1437         Iterable<Relationship> rels = nodo.getRelationships(Direction.OUTGOING, RelationType.PathRelationship);
1438         Iterator<Relationship> relIt = rels.iterator();
1439         while(relIt.hasNext()){
1440             Relationship r = relIt.next();
1441             if((long)r.getProperty("id") == neighbourId){
1442                 trovato=true;
1443                 rel=r;
1444                 break;
1445             }
1446         }
1447         if(!trovato)
1448             throw new MyNotFoundException("There is no Relationship with id '" + neigh.getId() + "'");
1449         rel.delete();
1450         Node dst = findNodeByNameOfSpecificGraph(neigh.getName(), graphId);
1451         if(dst == null)
1452             throw new MyNotFoundException("There is no Node whose name is '" + neigh.getName() + "'");
1453         Relationship relationship = nodo.createRelationshipTo(dst, RelationType.PathRelationship);
1454
1455         relationship.setProperty("id", neigh.getId());
1456
1457     }
1458
1459     public it.polito.neo4j.jaxb.Paths findAllPathsBetweenTwoNodes(long graphId, String srcName, String dstName, String direction) throws MyNotFoundException{
1460         Transaction tx = graphDB.beginTx();
1461         Set<String> pathPrinted = new HashSet<>();
1462
1463         try{
1464             findGraph(graphId);
1465             Node src = findNodeByNameOfSpecificGraph(srcName, graphId);
1466             Node dst = findNodeByNameOfSpecificGraph(dstName, graphId);
1467             if(src == null ){
1468                 tx.failure();
1469                 throw new DataNotFoundException("Source node "+src+" not exists");
1470             }else
1471                 if(dst == null){
1472                     tx.failure();
1473                     throw new DataNotFoundException("Destination node "+dst+" not exists");
1474                 }
1475             PathFinder<Path> finder = GraphAlgoFactory.allSimplePaths(PathExpanders.forTypeAndDirection(RelationType.PathRelationship, Direction.valueOf(direction.toUpperCase())), MAX_DEPTH);
1476
1477             for (Path p : finder.findAllPaths(src, dst))
1478             {
1479
1480                 pathPrinted.add(Paths.simplePathToString(p, "name"));
1481             }
1482         }
1483         finally{
1484             tx.close();
1485         }
1486
1487         it.polito.neo4j.jaxb.Paths paths = obFactory.createPaths();
1488         paths.setSource(srcName);
1489         paths.setDestination(dstName);
1490         paths.setDirection(direction);
1491         if(pathPrinted.isEmpty())
1492             paths.setMessage("No available paths");
1493         else
1494             paths.getPath().addAll(pathPrinted);
1495         return paths;
1496     }
1497
1498     public it.polito.neo4j.jaxb.Node getNodeByName(String name, long graphId) throws MyNotFoundException {
1499         Node nodo;
1500         Transaction tx = graphDB.beginTx();
1501
1502         try{
1503             findGraph(graphId);
1504
1505             nodo = findNodeByNameOfSpecificGraph(name, graphId);
1506             tx.success();
1507             if(nodo!=null)
1508                 return retrieveNode(nodo);
1509             else
1510                 return null;
1511         }
1512         catch(MyNotFoundException e){
1513             tx.close();
1514             throw new MyNotFoundException(e.getMessage());
1515         }
1516         finally{
1517             tx.close();
1518         }
1519     }
1520
1521     public it.polito.neo4j.jaxb.Node getNodeById(long nodeId, long graphId) throws MyNotFoundException {
1522         Node nodo;
1523         Transaction tx = graphDB.beginTx();
1524
1525         try{
1526             findGraph(graphId);
1527
1528             nodo = findNodeByIdAndSpecificGraph(nodeId, graphId);
1529             tx.success();
1530             if(nodo==null){
1531                 return null;
1532             }else
1533                 return retrieveNode(nodo);
1534         }
1535         catch(MyNotFoundException e){
1536             tx.close();
1537             throw new MyNotFoundException(e.getMessage());
1538         }
1539         finally{
1540             tx.close();
1541         }
1542     }
1543
1544     public void checkGraph(long graphId) throws MyNotFoundException {
1545
1546         Transaction tx = graphDB.beginTx();
1547
1548         try{
1549             findGraph(graphId);
1550
1551
1552             tx.success();
1553
1554         }
1555         catch(MyNotFoundException e){
1556             tx.close();
1557             throw new MyNotFoundException(e.getMessage());
1558         }
1559         finally{
1560             tx.close();
1561         }
1562
1563     }
1564
1565     public it.polito.neo4j.jaxb.Configuration updateConfiguration(long nodeId, long graphId, it.polito.neo4j.jaxb.Configuration nodeConfiguration) throws MyNotFoundException, MyInvalidIdException {
1566         Node nodo;
1567         Transaction tx = graphDB.beginTx();
1568         it.polito.neo4j.jaxb.Configuration returnedConf;
1569
1570         try{
1571             findGraph(graphId);
1572             nodo=findNode(nodeId);
1573             deleteConfiguration(nodo);
1574             createConfiguration(nodo, nodeConfiguration);
1575             returnedConf = retrieveconfiguration(nodo);
1576             tx.success();
1577         }
1578         finally{
1579             tx.close();
1580         }
1581         return returnedConf;
1582     }
1583
1584
1585 }