b50adf2a5aaca81006467c42479fb576671b4232
[aai/aai-common.git] / aai-core / src / test / java / org / onap / aai / serialization / db / DbSerializerTest.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *    http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.aai.serialization.db;
22
23 import static org.hamcrest.CoreMatchers.is;
24 import static org.junit.Assert.*;
25 import static org.mockito.Mockito.spy;
26 import static org.mockito.Mockito.when;
27
28 import java.io.UnsupportedEncodingException;
29 import java.net.URI;
30 import java.net.URISyntaxException;
31 import java.util.*;
32
33 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
34 import org.apache.tinkerpop.gremlin.structure.*;
35 import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
36 import org.janusgraph.core.JanusGraphFactory;
37 import org.junit.*;
38 import org.junit.rules.ExpectedException;
39 import org.junit.runner.RunWith;
40 import org.junit.runners.Parameterized;
41 import org.onap.aai.AAISetup;
42 import org.onap.aai.db.props.AAIProperties;
43 import org.onap.aai.dbmap.DBConnectionType;
44 import org.onap.aai.edges.EdgeIngestor;
45 import org.onap.aai.edges.enums.EdgeType;
46 import org.onap.aai.exceptions.AAIException;
47 import org.onap.aai.introspection.*;
48 import org.onap.aai.parsers.query.QueryParser;
49 import org.onap.aai.serialization.engines.JanusGraphDBEngine;
50 import org.onap.aai.serialization.engines.QueryStyle;
51 import org.onap.aai.serialization.engines.TransactionalGraphEngine;
52 import org.onap.aai.setup.SchemaVersion;
53 import org.onap.aai.util.AAIConstants;
54 import org.springframework.beans.factory.annotation.Autowired;
55 import org.springframework.test.annotation.DirtiesContext;
56
57 @RunWith(value = Parameterized.class)
58 @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
59 public class DbSerializerTest extends AAISetup {
60
61     // to use, set thrown.expect to whatever your test needs
62     // this line establishes default of expecting no exception to be thrown
63     @Rule
64     public ExpectedException thrown = ExpectedException.none();
65
66     protected static Graph graph;
67
68     @Autowired
69     protected EdgeSerializer edgeSer;
70     @Autowired
71     protected EdgeIngestor ei;
72
73     private SchemaVersion version;
74     private final ModelType introspectorFactoryType = ModelType.MOXY;
75     private final DBConnectionType type = DBConnectionType.REALTIME;
76     private Loader loader;
77     private TransactionalGraphEngine dbEngine;
78     private TransactionalGraphEngine engine; // for tests that aren't mocking the engine
79     private DBSerializer dbser;
80     TransactionalGraphEngine spy;
81     TransactionalGraphEngine.Admin adminSpy;
82
83     @Parameterized.Parameter(value = 0)
84     public QueryStyle queryStyle;
85
86     @Parameterized.Parameters(name = "QueryStyle.{0}")
87     public static Collection<Object[]> data() {
88         return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL}, {QueryStyle.TRAVERSAL_URI}});
89     }
90
91     @BeforeClass
92     public static void init() throws Exception {
93         graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open();
94
95     }
96
97     @Before
98     public void setup() throws Exception {
99         // createGraph();
100         version = schemaVersions.getDefaultVersion();
101         loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version);
102         dbEngine = new JanusGraphDBEngine(queryStyle, type, loader);
103         spy = spy(dbEngine);
104         adminSpy = spy(dbEngine.asAdmin());
105
106         engine = new JanusGraphDBEngine(queryStyle, type, loader);
107         dbser = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST");
108     }
109
110     @Test
111     public void testFindDeletableDoesNotReturnDuplicates() throws AAIException {
112
113         Vertex genericVnf1 = graph.addVertex("aai-node-type", "generic-vnf", "vnf-id", "vnf1", "vnf-name", "vnfName1");
114
115         Vertex lInterface1 = graph.addVertex("aai-node-type", "l-interface", "interface-name", "lInterface1");
116         Vertex lInterface2 = graph.addVertex("aai-node-type", "l-interface", "interface-name", "lInterface2");
117
118         Vertex logicalLink1 = graph.addVertex("aai-node-type", "logical-link", "link-name", "logicalLink1");
119         Vertex logicalLink2 = graph.addVertex("aai-node-type", "logical-link", "link-name", "logicalLink2");
120
121         GraphTraversalSource g = graph.traversal();
122
123         edgeSer.addTreeEdge(g, genericVnf1, lInterface1);
124         edgeSer.addTreeEdge(g, genericVnf1, lInterface2);
125         edgeSer.addEdge(g, lInterface1, logicalLink1);
126         edgeSer.addEdge(g, lInterface1, logicalLink2);
127         // This line will cause the logical link2 to be found twice under linterface 1
128         // and also under the linterface 2 and since in the past deletable returned
129         // duplicates this test checks that it shouldn't return duplicates
130         edgeSer.addEdge(g, lInterface2, logicalLink2);
131
132         when(spy.asAdmin()).thenReturn(adminSpy);
133         when(adminSpy.getTraversalSource()).thenReturn(g);
134         when(adminSpy.getReadOnlyTraversalSource()).thenReturn(g);
135
136         List<Vertex> deletableVertexes = spy.getQueryEngine().findDeletable(genericVnf1);
137         Set<Vertex> vertexSet = new HashSet<>();
138
139         for (Vertex deletableVertex : deletableVertexes) {
140             if (!vertexSet.contains(deletableVertex)) {
141                 vertexSet.add(deletableVertex);
142             } else {
143                 fail("Find deletable is returning a list of duplicate vertexes");
144             }
145         }
146     }
147
148     @After
149     public void tearDown() throws Exception {
150         engine.rollback();
151     }
152
153     @AfterClass
154     public static void destroy() throws Exception {
155         graph.close();
156     }
157
158     public void subnetSetup() throws AAIException {
159         /*
160          * This setus up the test graph, For future junits , add more vertices
161          * and edges
162          */
163
164         Vertex l3interipv4addresslist_1 = graph.traversal().addV("aai-node-type", "l3-interface-ipv4-address-list",
165                 "l3-interface-ipv4-address", "l3-interface-ipv4-address-1").next();
166         Vertex subnet_2 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-2").next();
167         Vertex l3interipv6addresslist_3 = graph.traversal().addV("aai-node-type", "l3-interface-ipv6-address-list",
168                 "l3-interface-ipv6-address", "l3-interface-ipv6-address-3").next();
169         Vertex subnet_4 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-4").next();
170         Vertex subnet_5 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-5").next();
171         Vertex l3network_6 = graph.traversal()
172                 .addV("aai-node-type", "l3-network", "network-id", "network-id-6", "network-name", "network-name-6")
173                 .next();
174
175         GraphTraversalSource g = graph.traversal();
176         edgeSer.addEdge(g, l3interipv4addresslist_1, subnet_2);
177         edgeSer.addEdge(g, l3interipv6addresslist_3, subnet_4);
178         edgeSer.addTreeEdge(g, subnet_5, l3network_6);
179     }
180
181     public void l3NetworkSetup() throws AAIException {
182         /*
183          * This setus up the test graph, For future junits , add more vertices
184          * and edges
185          */
186
187         Vertex l3network1 = graph.addVertex("aai-node-type", "l3-network", "network-id", "network-id-v1",
188                 "network-name", "network-name-v1");
189         Vertex l3network2 = graph.addVertex("aai-node-type", "l3-network", "network-id", "network-id-v2",
190                 "network-name", "network-name-v2");
191         Vertex subnet1 = graph.addVertex("aai-node-type", "subnet", "subnet-id", "subnet-id-v1");
192         Vertex subnet2 = graph.addVertex("aai-node-type", "subnet", "subnet-id", "subnet-id-v2");
193
194         Vertex l3interipv4addresslist_1 = graph.addVertex("aai-node-type", "l3-interface-ipv4-address-list",
195                 "l3-interface-ipv4-address", "l3-intr-v1");
196         Vertex l3interipv6addresslist_1 = graph.addVertex("aai-node-type", "l3-interface-ipv6-address-list",
197                 "l3-interface-ipv6-address", "l3-interface-ipv6-v1");
198
199         GraphTraversalSource g = graph.traversal();
200         edgeSer.addTreeEdge(g, subnet1, l3network1);
201         edgeSer.addEdge(g, l3interipv4addresslist_1, subnet1);
202         edgeSer.addEdge(g, l3interipv6addresslist_1, subnet1);
203
204         edgeSer.addTreeEdge(g, subnet2, l3network2);
205
206     }
207
208     public void vserverSetup() throws AAIException {
209         /*
210          * This setus up the test graph, For future junits , add more vertices
211          * and edges
212          */
213
214         Vertex vserver1 = graph.addVertex("aai-node-type", "vserver", "vserver-id", "vss1",
215                 AAIProperties.AAI_URI.toString(),
216                 "/cloud-infrastructure/cloud-regions/cloud-region/me/123/tenants/tenant/453/vservers/vserver/vss1");
217
218         Vertex lInterface1 = graph.addVertex("aai-node-type", "l-interface", "interface-name", "lIntr1");
219         Vertex lInterface2 = graph.addVertex("aai-node-type", "l-interface", "interface-name", "lIntr2");
220
221         Vertex logicalLink1 = graph.addVertex("aai-node-type", "logical-link", "link-name", "logLink1");
222         Vertex logicalLink2 = graph.addVertex("aai-node-type", "logical-link", "link-name", "logLink2");
223
224         Vertex l3interipv4addresslist_1 = graph.addVertex("aai-node-type", "l3-interface-ipv4-address-list",
225                 "l3-interface-ipv4-address", "l3-intr-ipv4-address-1");
226         Vertex l3interipv6addresslist_2 = graph.addVertex("aai-node-type", "l3-interface-ipv6-address-list",
227                 "l3-interface-ipv4-address", "l3-intr-ipv6-address-1");
228
229         GraphTraversalSource g = graph.traversal();
230
231         edgeSer.addTreeEdge(g, lInterface1, vserver1);
232         edgeSer.addTreeEdge(g, lInterface2, vserver1);
233         edgeSer.addTreeEdge(g, l3interipv4addresslist_1, lInterface1);
234         edgeSer.addTreeEdge(g, l3interipv6addresslist_2, lInterface2);
235
236         edgeSer.addEdge(g, lInterface1, logicalLink1);
237         edgeSer.addEdge(g, lInterface2, logicalLink2);
238     }
239
240     @Test
241     public void subnetDelWithInEdgesIpv4Test() throws AAIException {
242         subnetSetup();
243         String expected_message =
244                 "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types [l3-interface-ipv4-address-list]";
245
246         /*
247          * This subnet has in-edges with l3-ipv4 and NOT ok to delete
248          */
249         Vertex subnet = graph.traversal().V().has("aai-node-type", "subnet").has("subnet-id", "subnet-id-2").next();
250
251         String exceptionMessage = testCascadeDelete(subnet);
252         assertEquals(expected_message, exceptionMessage);
253
254     }
255
256     @Test
257     public void subnetDelWithInEdgesIpv6Test() throws AAIException {
258         subnetSetup();
259         String expected_message =
260                 "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types [l3-interface-ipv6-address-list]";
261
262         /*
263          * This subnet has in-edges with l3-ipv6 and NOT ok to delete
264          */
265         Vertex subnet = graph.traversal().V().has("aai-node-type", "subnet").has("subnet-id", "subnet-id-4").next();
266         String exceptionMessage = testCascadeDelete(subnet);
267         assertEquals(expected_message, exceptionMessage);
268
269     }
270
271     @Test
272     public void subnetDelWithInEdgesL3network() throws AAIException {
273         subnetSetup();
274         String expected_message = "";
275
276         /*
277          * This subnet has in-edges with l3-network and ok to delete
278          */
279         Vertex subnet = graph.traversal().V().has("aai-node-type", "subnet").has("subnet-id", "subnet-id-5").next();
280
281         String exceptionMessage = testCascadeDelete(subnet);
282         assertEquals(expected_message, exceptionMessage);
283
284     }
285
286     public String testCascadeDelete(Vertex v) throws AAIException {
287
288         GraphTraversalSource traversal = graph.traversal();
289         when(spy.asAdmin()).thenReturn(adminSpy);
290         when(adminSpy.getTraversalSource()).thenReturn(traversal);
291         when(adminSpy.getReadOnlyTraversalSource()).thenReturn(traversal);
292
293         String exceptionMessage = "";
294         DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST");
295         List<Vertex> deletableVertices = spy.getQueryEngine().findDeletable(v);
296
297         try {
298             serializer.delete(v, deletableVertices, "resourceVersion", false);
299         } catch (AAIException exception) {
300             exceptionMessage = exception.getMessage();
301         }
302         return exceptionMessage;
303
304     }
305
306     public String testDelete(Vertex v) throws AAIException {
307
308         GraphTraversalSource traversal = graph.traversal();
309         when(spy.asAdmin()).thenReturn(adminSpy);
310         when(adminSpy.getTraversalSource()).thenReturn(traversal);
311         when(adminSpy.getReadOnlyTraversalSource()).thenReturn(traversal);
312
313         String exceptionMessage = "";
314         DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST");
315
316         try {
317             serializer.delete(v, "resourceVersion", false);
318         } catch (AAIException exception) {
319             exceptionMessage = exception.getMessage();
320         }
321         return exceptionMessage;
322
323     }
324
325     @Test
326     public void createNewVertexTest() throws AAIException {
327         engine.startTransaction();
328
329         Introspector testObj = loader.introspectorFromName("generic-vnf");
330
331         Vertex testVertex = dbser.createNewVertex(testObj);
332         Vertex fromGraph = engine.tx().traversal().V().has("aai-node-type", "generic-vnf").toList().get(0);
333         assertEquals(testVertex.id(), fromGraph.id());
334         assertEquals("AAI-TEST", fromGraph.property(AAIProperties.SOURCE_OF_TRUTH.toString()).value());
335
336     }
337
338     @Test
339     public void touchStandardVertexPropertiesTest() throws AAIException, InterruptedException {
340         engine.startTransaction();
341
342         // if this test runs through too fast the value may not change, causing the test to fail. sleeping ensures a
343         // different value
344         Thread.sleep(2);
345         DBSerializer dbser2 = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST-2");
346         Vertex vert = graph.addVertex("aai-node-type", "generic-vnf");
347
348         // Upon first creation of the Vertex and the DBSerializer
349         // the source of truth and created-ts should be the same as their modified counterparts
350         dbser2.touchStandardVertexProperties(vert, true);
351         String createTS = (String) vert.property(AAIProperties.CREATED_TS).value();
352         String modTS = (String) vert.property(AAIProperties.LAST_MOD_TS).value();
353         String sot = (String) vert.property(AAIProperties.SOURCE_OF_TRUTH).value();
354         String lastModSOT = (String) vert.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH).value();
355         assertTrue(createTS.equals(modTS));
356         assertTrue(sot.equals(lastModSOT));
357
358         // if this test runs through too fast the value may not change, causing the test to fail. sleeping ensures a
359         // different value
360         Thread.sleep(2);
361
362         // Not new vertex && new DBSerializer (A new serializer since a new one will be created per transaction)
363         // Here the vertex will be modified by a different source of truth
364         DBSerializer dbser3 = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST-3");
365         dbser3.touchStandardVertexProperties(vert, false);
366         createTS = (String) vert.property(AAIProperties.CREATED_TS).value();
367         modTS = (String) vert.property(AAIProperties.LAST_MOD_TS).value();
368         sot = (String) vert.property(AAIProperties.SOURCE_OF_TRUTH).value();
369         lastModSOT = (String) vert.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH).value();
370         assertFalse(createTS.equals(modTS));
371         assertFalse(sot.equals(lastModSOT));
372
373         // if this test runs through too fast the value may not change, causing the test to fail. sleeping ensures a
374         // different value
375         Thread.sleep(2);
376
377         // The currentTimeMillis used for the created-ts and modified-ts is created at DBSerializer instantiation
378         // Every REST transaction should create a new DBSerializer - thus a new currentTimeMillis is used at the time of
379         // transaction.
380         // Using an existing vertex, but treating it as new && using an older DBSerializer
381         dbser.touchStandardVertexProperties(vert, true);
382         String resverStart = (String) vert.property(AAIProperties.RESOURCE_VERSION).value();
383         String lastModTimeStart = (String) vert.property(AAIProperties.LAST_MOD_TS).value();
384         createTS = (String) vert.property(AAIProperties.CREATED_TS).value();
385         modTS = (String) vert.property(AAIProperties.LAST_MOD_TS).value();
386         assertTrue(createTS.equals(modTS));
387         assertEquals("AAI-TEST", vert.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH).value());
388
389         // if this test runs through too fast the value may not change, causing the test to fail. sleeping ensures a
390         // different value
391         Thread.sleep(2);
392
393         dbser2.touchStandardVertexProperties(vert, false);
394         String resourceVer = (String) vert.property(AAIProperties.RESOURCE_VERSION).value();
395         String lastModTs = (String) vert.property(AAIProperties.LAST_MOD_TS).value();
396         String lastModSoT = (String) vert.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH).value();
397
398         assertFalse(resverStart.equals(resourceVer));
399         assertFalse(lastModTimeStart.equals(lastModTs));
400         assertEquals("AAI-TEST-2", lastModSoT);
401     }
402
403     @Test
404     public void touchStandardVertexPropertiesAAIUUIDTest() throws AAIException, InterruptedException {
405         engine.startTransaction();
406
407         Graph graph = TinkerGraph.open();
408         Vertex v = graph.addVertex("aai-node-type", "generic-vnf");
409
410         dbser.touchStandardVertexProperties(v, true);
411
412         assertTrue(v.property(AAIProperties.AAI_UUID).isPresent());
413         try {
414             UUID.fromString((String) v.property(AAIProperties.AAI_UUID).value());
415         } catch (IllegalArgumentException e) {
416             fail("Vertex uuid is not valid uuid");
417         }
418     }
419
420     @Test
421     public void verifyResourceVersion_SunnyDayTest() throws AAIException {
422         engine.startTransaction();
423
424         assertTrue(dbser.verifyResourceVersion("delete", "vnfc", "abc", "abc", "vnfcs/vnfc/vnfcId"));
425
426     }
427
428     @Test
429     public void verifyResourceVersion_CreateWithRVTest() throws AAIException {
430         engine.startTransaction();
431
432         thrown.expect(AAIException.class);
433         thrown.expectMessage("resource-version passed for create of generic-vnfs/generic-vnf/myid");
434         dbser.verifyResourceVersion("create", "generic-vnf", null, "old-res-ver", "generic-vnfs/generic-vnf/myid");
435
436     }
437
438     @Test
439     public void verifyResourceVersion_MissingRVTest() throws AAIException {
440         engine.startTransaction();
441
442         thrown.expect(AAIException.class);
443         thrown.expectMessage("resource-version not passed for update of generic-vnfs/generic-vnf/myid");
444         dbser.verifyResourceVersion("update", "generic-vnf", "current-res-ver", null, "generic-vnfs/generic-vnf/myid");
445
446     }
447
448     @Test
449     public void verifyResourceVersion_MismatchRVTest() throws AAIException {
450         engine.startTransaction();
451
452         thrown.expect(AAIException.class);
453         thrown.expectMessage("resource-version MISMATCH for update of generic-vnfs/generic-vnf/myid");
454         dbser.verifyResourceVersion("update", "generic-vnf", "current-res-ver", "old-res-ver",
455                 "generic-vnfs/generic-vnf/myid");
456
457     }
458
459     @Test
460     public void verifyResourceVersion_DeleteTest() throws AAIException {
461         engine.startTransaction();
462
463         assertTrue(dbser.verifyResourceVersion("delete", "generic-vnf", "current-res-ver",
464                 AAIConstants.AAI_RESVERSION_DISABLED_UUID_DEFAULT, "generic-vnfs/generic-vnf/myid"));
465
466     }
467
468     @Test
469     public void trimClassNameTest() throws AAIException {
470         assertEquals("GenericVnf", dbser.trimClassName("GenericVnf"));
471         assertEquals("GenericVnf", dbser.trimClassName("org.onap.aai.GenericVnf"));
472     }
473
474     @Test
475     public void getURIForVertexTest() throws AAIException, URISyntaxException, UnsupportedEncodingException {
476         engine.startTransaction();
477
478         Vertex cr = engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id",
479                 "123", "aai-uri", "/cloud-infrastructure/cloud-regions/cloud-region/me/123");
480         Vertex ten = engine.tx().addVertex("aai-node-type", "tenant", "tenant-id", "453");
481
482         edgeSer.addTreeEdge(engine.tx().traversal(), cr, ten);
483
484         ten.property("aai-uri", "/cloud-infrastructure/cloud-regions/cloud-region/me/123/tenants/tenant/453");
485
486         URI compare = new URI("/cloud-infrastructure/cloud-regions/cloud-region/me/123/tenants/tenant/453");
487         assertEquals(compare, dbser.getURIForVertex(ten));
488
489         URI compareFailure = new URI("/unknown-uri");
490         ten.property("aai-uri").remove();
491         assertEquals(compareFailure, dbser.getURIForVertex(ten));
492
493     }
494
495     @Test
496     public void getVertexPropertiesTest() throws AAIException, UnsupportedEncodingException {
497         engine.startTransaction();
498
499         Vertex cr =
500                 engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id", "123");
501
502         Introspector crIntro = dbser.getVertexProperties(cr);
503         assertEquals("cloud-region", crIntro.getDbName());
504         assertEquals("me", crIntro.getValue("cloud-owner"));
505         assertEquals("123", crIntro.getValue("cloud-region-id"));
506
507     }
508
509     @Test
510     public void getEdgeBetweenTest() throws AAIException {
511         engine.startTransaction();
512
513         Vertex cr =
514                 engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id", "123");
515         Vertex ten = engine.tx().addVertex("aai-node-type", "tenant", "tenant-id", "453");
516
517         edgeSer.addTreeEdge(engine.tx().traversal(), cr, ten);
518
519         Edge e = dbser.getEdgeBetween(EdgeType.TREE, ten, cr, null);
520         assertEquals("org.onap.relationships.inventory.BelongsTo", e.label());
521
522     }
523
524     @Test
525     public void deleteEdgeTest() throws AAIException, UnsupportedEncodingException {
526         engine.startTransaction();
527
528         Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri",
529                 "/network/generic-vnfs/generic-vnf/myvnf");
530         Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri",
531                 "/network/vnfcs/vnfc/a-name");
532
533         edgeSer.addEdge(engine.tx().traversal(), gvnf, vnfc);
534
535         Introspector relData = loader.introspectorFromName("relationship-data");
536         relData.setValue("relationship-key", "vnfc.vnfc-name");
537         relData.setValue("relationship-value", "a-name");
538         Introspector relationship = loader.introspectorFromName("relationship");
539         relationship.setValue("related-to", "vnfc");
540         relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
541         relationship.setValue("relationship-data", relData);
542
543         assertTrue(dbser.deleteEdge(relationship, gvnf));
544
545         assertFalse(engine.tx().traversal().V(gvnf).both("uses").hasNext());
546         assertFalse(engine.tx().traversal().V(vnfc).both("uses").hasNext());
547
548     }
549
550     @Test
551     public void createEdgeTest() throws AAIException, UnsupportedEncodingException {
552         engine.startTransaction();
553
554         Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri",
555                 "/network/generic-vnfs/generic-vnf/myvnf");
556         Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri",
557                 "/network/vnfcs/vnfc/a-name");
558
559         // sunny day case
560         Introspector relData = loader.introspectorFromName("relationship-data");
561         relData.setValue("relationship-key", "vnfc.vnfc-name");
562         relData.setValue("relationship-value", "a-name");
563         Introspector relationship = loader.introspectorFromName("relationship");
564         relationship.setValue("related-to", "vnfc");
565         relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
566         relationship.setValue("relationship-data", relData);
567
568         assertTrue(dbser.createEdge(relationship, gvnf));
569         assertTrue(engine.tx().traversal().V(gvnf).both("org.onap.relationships.inventory.BelongsTo").hasNext());
570         assertTrue(engine.tx().traversal().V(vnfc).both("org.onap.relationships.inventory.BelongsTo").hasNext());
571
572     }
573
574     @Test
575     public void createCousinEdgeThatShouldBeTreeTest()
576             throws AAIException, UnsupportedEncodingException, URISyntaxException {
577         engine.startTransaction();
578
579         Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri",
580                 "/network/generic-vnfs/generic-vnf/myvnf");
581         Vertex vf = engine.tx().addVertex("aai-node-type", "vf-module", "vf-module-id", "vf-id", "aai-uri",
582                 "/network/generic-vnfs/generic-vnf/myvnf/vf-modules/vf-module/vf-id");
583
584         edgeSer.addTreeEdge(engine.tx().traversal(), gvnf, vf);
585
586         Introspector relationship = loader.introspectorFromName("relationship");
587         relationship.setValue("related-to", "vf-module");
588         relationship.setValue("related-link", dbser.getURIForVertex(vf).toString());
589         Introspector relationshipList = loader.introspectorFromName("relationship-list");
590         relationshipList.setValue("relationship", Collections.singletonList(relationship.getUnderlyingObject()));
591
592         Introspector gvnfObj = loader.introspectorFromName("generic-vnf");
593         Vertex gvnf2 = dbser.createNewVertex(gvnfObj);
594         gvnfObj.setValue("relationship-list", relationshipList.getUnderlyingObject());
595         gvnfObj.setValue("vnf-id", "myvnf-1");
596
597         QueryParser uriQuery =
598                 dbEngine.getQueryBuilder().createQueryFromURI(new URI("/network/generic-vnfs/generic-vnf/myvnf-1"));
599
600         try {
601             dbser.serializeToDb(gvnfObj, gvnf2, uriQuery, null, "test");
602         } catch (AAIException e) {
603             assertEquals("AAI_6145", e.getCode());
604         }
605     }
606
607     @Test
608     public void createEdgeNodeDoesNotExistExceptionTest() throws AAIException, UnsupportedEncodingException {
609         engine.startTransaction();
610
611         Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri",
612                 "/network/generic-vnfs/generic-vnf/myvnf");
613
614         // rainy day case, edge to non-existent object
615         Introspector relData = loader.introspectorFromName("relationship-data");
616         relData.setValue("relationship-key", "vnfc.vnfc-name");
617         relData.setValue("relationship-value", "b-name");
618         Introspector relationship = loader.introspectorFromName("relationship");
619         relationship.setValue("related-to", "vnfc");
620         relationship.setValue("related-link", "/network/vnfcs/vnfc/b-name");
621         relationship.setValue("relationship-data", relData);
622
623         thrown.expect(AAIException.class);
624         thrown.expectMessage("Node of type vnfc. Could not find object at: /network/vnfcs/vnfc/b-name");
625         dbser.createEdge(relationship, gvnf);
626
627     }
628
629     @Test
630     public void serializeSingleVertexTopLevelTest() throws AAIException, UnsupportedEncodingException {
631         engine.startTransaction();
632
633         Introspector gvnf = loader.introspectorFromName("generic-vnf");
634         Vertex gvnfVert = dbser.createNewVertex(gvnf);
635
636         gvnf.setValue("vnf-id", "myvnf");
637         dbser.serializeSingleVertex(gvnfVert, gvnf, "test");
638         assertTrue(engine.tx().traversal().V().has("aai-node-type", "generic-vnf").has("vnf-id", "myvnf").hasNext());
639
640     }
641
642     @Test
643     public void serializeSingleVertexChildTest() throws AAIException, UnsupportedEncodingException {
644         engine.startTransaction();
645
646         Vertex cr = engine.tx().addVertex("aai-node-type", "cloud-region", "cloud-owner", "me", "cloud-region-id",
647                 "123", "aai-uri", "/cloud-infrastructure/cloud-regions/cloud-region/me/123");
648         Introspector tenIn = loader.introspectorFromName("tenant");
649         Vertex ten = dbser.createNewVertex(tenIn);
650         ten.property("aai-uri", cr.property("aai-uri").value().toString() + "/tenants/tenant/453");
651
652         edgeSer.addTreeEdge(engine.tx().traversal(), cr, ten);
653
654         tenIn.setValue("tenant-id", "453");
655         tenIn.setValue("tenant-name", "mytenant");
656
657         dbser.serializeSingleVertex(ten, tenIn, "test");
658
659         assertTrue(engine.tx().traversal().V().has("aai-node-type", "tenant").has("tenant-id", "453")
660                 .has("tenant-name", "mytenant").hasNext());
661
662     }
663
664     @Test
665     public void getVertexPropertiesRelationshipHasLabelTest() throws AAIException, UnsupportedEncodingException {
666         engine.startTransaction();
667
668         Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "vnf-123", "aai-uri",
669                 "/network/generic-vnfs/generic-vnf/vnf-123");
670         Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "vnfc-123", "aai-uri",
671                 "/network/vnfcs/vnfc/vnfc-123");
672
673         edgeSer.addEdge(engine.tx().traversal(), gvnf, vnfc);
674
675         Introspector obj = loader.introspectorFromName("generic-vnf");
676         obj = this.dbser.dbToObject(Arrays.asList(gvnf), obj, AAIProperties.MAXIMUM_DEPTH, false, "false");
677
678         MarshallerProperties properties =
679                 new MarshallerProperties.Builder(org.onap.aai.restcore.MediaType.getEnum("application/json"))
680                         .formatted(true).build();
681         System.out.println(obj.marshal(properties));
682
683         assertEquals("edge label between generic-vnf and vnfs is uses", "org.onap.relationships.inventory.BelongsTo",
684                 obj.getWrappedValue("relationship-list").getWrappedListValue("relationship").get(0)
685                         .getValue("relationship-label"));
686
687     }
688
689     @Test
690     public void getVertexPropertiesRelationshipOldVersionNoEdgeLabelTest()
691             throws AAIException, UnsupportedEncodingException {
692
693         SchemaVersion version = schemaVersions.getAppRootVersion();
694         DBSerializer dbser = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST");
695         Loader loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version);
696
697         engine.startTransaction();
698
699         Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "vnf-123", "aai-uri",
700                 "/network/generic-vnfs/generic-vnf/vnf-123");
701         Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "vnfc-123", "aai-uri",
702                 "/network/vnfcs/vnfc/vnfc-123");
703
704         edgeSer.addEdge(engine.tx().traversal(), gvnf, vnfc);
705
706         Introspector obj = loader.introspectorFromName("generic-vnf");
707         obj = dbser.dbToObject(Arrays.asList(gvnf), obj, AAIProperties.MAXIMUM_DEPTH, false, "false");
708
709         assertEquals("Relationship does not contain edge-property", false, obj.getWrappedValue("relationship-list")
710                 .getWrappedListValue("relationship").get(0).hasProperty("relationship-label"));
711
712     }
713
714     @Test
715     public void createEdgeWithInvalidLabelTest() throws AAIException, UnsupportedEncodingException,
716             NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
717
718         engine.startTransaction();
719
720         Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri",
721                 "/network/generic-vnfs/generic-vnf/myvnf");
722         engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
723
724         Introspector relData = loader.introspectorFromName("relationship-data");
725         relData.setValue("relationship-key", "vnfc.vnfc-name");
726         relData.setValue("relationship-value", "a-name");
727         Introspector relationship = loader.introspectorFromName("relationship");
728         relationship.setValue("related-to", "vnfc");
729         relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name");
730         relationship.setValue("relationship-data", relData);
731         relationship.setValue("relationship-label", "NA");
732
733         thrown.expect(AAIException.class);
734         thrown.expectMessage("No rule found");
735         thrown.expectMessage("node type: generic-vnf, node type: vnfc, label: NA, type: COUSIN");
736         dbser.createEdge(relationship, gvnf);
737
738     }
739
740     @Test
741     public void addRelatedToPropertyTest() throws AAIException {
742         engine.startTransaction();
743
744         Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myname", "vnf-name", "myname",
745                 "aai-uri", "/network/generic-vnfs/generic-vnf/myname");
746         engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", "/network/vnfcs/vnfc/a-name");
747         Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getAppRootVersion());
748         Introspector gv = loader.introspectorFromName("generic-vnf");
749         gv.setValue("vnf-name", "myname");
750
751         Introspector rel = loader.introspectorFromName("relationship");
752         DBSerializer dbser = new DBSerializer(schemaVersions.getAppRootVersion(), dbEngine, ModelType.MOXY, "AAI-TEST");
753         dbser.addRelatedToProperty(rel, gvnf, "generic-vnf");
754         List<Introspector> relToProps = rel.getWrappedListValue("related-to-property");
755         assertThat(relToProps.size(), is(1));
756         Introspector relToProp = relToProps.get(0);
757         assertThat(relToProp.getValue("property-key"), is("generic-vnf.vnf-name"));
758         assertThat(relToProp.getValue("property-value"), is("myname"));
759     }
760
761     @Test
762     public void dbToObjectContainerMismatchTest() throws AAIException, UnsupportedEncodingException {
763         DBSerializer dbser = new DBSerializer(schemaVersions.getAppRootVersion(), dbEngine, ModelType.MOXY, "AAI-TEST");
764         Graph vertexMaker = TinkerGraph.open();
765         Vertex a = vertexMaker.addVertex(T.id, "0");
766         Vertex b = vertexMaker.addVertex(T.id, "1");
767         List<Vertex> vertices = Arrays.asList(a, b);
768
769         Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getAppRootVersion());
770         Introspector intro = loader.introspectorFromName("image"); // just need any non-container object
771
772         thrown.expect(AAIException.class);
773         thrown.expectMessage("query object mismatch: this object cannot hold multiple items.");
774
775         dbser.dbToObject(vertices, intro, Integer.MAX_VALUE, true, "doesn't matter");
776     }
777
778     @Test
779     public void dbToObjectTest() throws AAIException, UnsupportedEncodingException {
780         engine.startTransaction();
781
782         DBSerializer dbser = new DBSerializer(version, engine, ModelType.MOXY, "AAI-TEST");
783         Vertex gv1 = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "id1");
784         Vertex gv2 = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "id2");
785         List<Vertex> vertices = Arrays.asList(gv1, gv2);
786
787         Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, version);
788         Introspector gvContainer = loader.introspectorFromName("generic-vnfs");
789
790         Introspector res = dbser.dbToObject(vertices, gvContainer, 0, true, "true");
791         List<Introspector> gvs = res.getWrappedListValue("generic-vnf");
792         assertTrue(gvs.size() == 2);
793         for (Introspector i : gvs) {
794             String vnfId = i.getValue("vnf-id");
795             assertTrue("id1".equals(vnfId) || "id2".equals(vnfId));
796         }
797
798     }
799
800     @Test
801     public void getEdgeBetweenNoLabelTest() throws AAIException {
802         DBSerializer dbser = new DBSerializer(version, engine, ModelType.MOXY, "AAI-TEST");
803         engine.startTransaction();
804         Vertex gv = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "id1");
805         Vertex lint = engine.tx().addVertex("aai-node-type", "l-interface", "interface-name", "name1");
806         edgeSer.addTreeEdge(engine.tx().traversal(), gv, lint);
807
808         Edge res = dbser.getEdgeBetween(EdgeType.TREE, gv, lint);
809         assertEquals("org.onap.relationships.inventory.BelongsTo", res.label());
810
811     }
812
813     @Test
814     public void deleteItemsWithTraversal() throws AAIException {
815         DBSerializer dbser = new DBSerializer(version, engine, ModelType.MOXY, "AAI-TEST");
816         engine.startTransaction();
817         Vertex gv = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "id1");
818         Vertex lint = engine.tx().addVertex("aai-node-type", "l-interface", "interface-name", "name1");
819
820         assertTrue(engine.tx().traversal().V().has("vnf-id", "id1").hasNext());
821         assertTrue(engine.tx().traversal().V().has("interface-name", "name1").hasNext());
822
823         dbser.deleteItemsWithTraversal(Arrays.asList(gv, lint));
824
825         assertTrue(!engine.tx().traversal().V().has("vnf-id", "id1").hasNext());
826         assertTrue(!engine.tx().traversal().V().has("interface-name", "name1").hasNext());
827
828     }
829
830     @Test
831     public void serializeToDbWithParentTest() throws AAIException, UnsupportedEncodingException, URISyntaxException {
832         DBSerializer dbser = new DBSerializer(version, engine, ModelType.MOXY, "AAI-TEST");
833         engine.startTransaction();
834         Vertex gv = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "id1", "aai-uri",
835                 "/network/generic-vnfs/generic-vnf/id1");
836         Vertex lint = engine.tx().addVertex("aai-node-type", "l-interface");
837         edgeSer.addTreeEdge(engine.tx().traversal(), gv, lint);
838
839         Introspector lintIntro = loader.introspectorFromName("l-interface");
840         lintIntro.setValue("interface-name", "name1");
841         lintIntro.setValue("interface-role", "actor");
842         URI lintURI = new URI("/network/generic-vnfs/generic-vnf/id1/l-interfaces/l-interface/name1");
843         QueryParser uriQuery = engine.getQueryBuilder(gv).createQueryFromURI(lintURI);
844         dbser.serializeToDb(lintIntro, lint, uriQuery, "test-identifier", "AAI-TEST");
845
846         assertTrue(engine.tx().traversal().V(lint).has("interface-role", "actor").hasNext());
847
848     }
849
850     @Test
851     public void getLatestVersionViewTest() throws AAIException, UnsupportedEncodingException {
852         DBSerializer dbser = new DBSerializer(version, engine, ModelType.MOXY, "AAI-TEST");
853         engine.startTransaction();
854         Vertex phys = engine.tx().addVertex("aai-node-type", "physical-link", "link-name", "zaldo", "speed-value",
855                 "very-fast", "service-provider-bandwidth-up-units", "things");
856
857         Introspector res = dbser.getLatestVersionView(phys);
858         assertTrue("zaldo".equals(res.getValue("link-name")));
859         assertTrue("very-fast".equals(res.getValue("speed-value")));
860         assertTrue("things".equals(res.getValue("service-provider-bandwidth-up-units")));
861     }
862
863     @Test
864     public void cascadeVserverDeleteTest() throws AAIException {
865         vserverSetup();
866         String expected_message = "";
867
868         /*
869          * vserver-->l-interface -->logical-link
870          * -->l3-ipvx-list
871          */
872         Vertex vserver = graph.traversal().V().has("aai-node-type", "vserver").has("vserver-id", "vss1").next();
873
874         String exceptionMessage = testCascadeDelete(vserver);
875         assertEquals(expected_message, exceptionMessage);
876
877     }
878
879     @Test
880     public void cascadeL3NetworkPreventDeleteTest() throws AAIException {
881         l3NetworkSetup();
882         ArrayList expected_messages = new ArrayList<String>();
883         expected_messages.add(
884                 "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types [l3-interface-ipv4-address-list, l3-interface-ipv6-address-list]");
885         expected_messages.add(
886                 "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types [l3-interface-ipv6-address-list, l3-interface-ipv4-address-list]");
887
888         /*
889          * vserver-->l-interface -->logical-link
890          * -->l3-ipvx-list
891          */
892         Vertex l3network =
893                 graph.traversal().V().has("aai-node-type", "l3-network").has("network-id", "network-id-v1").next();
894
895         String exceptionMessage = testCascadeDelete(l3network);
896         assertTrue(expected_messages.contains(exceptionMessage));
897
898     }
899
900     @Test
901     public void cascadeL3NetworkDeleteTest() throws AAIException {
902         l3NetworkSetup();
903         String expected_message = "";
904
905         /*
906          * vserver-->l-interface -->logical-link
907          * -->l3-ipvx-list
908          */
909         Vertex l3network =
910                 graph.traversal().V().has("aai-node-type", "l3-network").has("network-id", "network-id-v2").next();
911
912         String exceptionMessage = testCascadeDelete(l3network);
913         assertEquals(expected_message, exceptionMessage);
914
915     }
916 }