Update license date and text
[aai/champ.git] / champ-lib / champ-core / src / test / java / org / onap / aai / champcore / core / ChampObjectTest.java
1 /**
2  * ============LICENSE_START==========================================
3  * org.onap.aai
4  * ===================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 Amdocs
7  * ===================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *        http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END============================================
20  */
21 package org.onap.aai.champcore.core;
22
23 import org.junit.Test;
24 import org.onap.aai.champcore.ChampAPI;
25 import org.onap.aai.champcore.ChampCapabilities;
26 import org.onap.aai.champcore.ChampGraph;
27 import org.onap.aai.champcore.ChampTransaction;
28 import org.onap.aai.champcore.core.ChampRelationshipTest.TestTransaction;
29 import org.onap.aai.champcore.exceptions.ChampMarshallingException;
30 import org.onap.aai.champcore.exceptions.ChampObjectNotExistsException;
31 import org.onap.aai.champcore.exceptions.ChampSchemaViolationException;
32 import org.onap.aai.champcore.exceptions.ChampTransactionException;
33 import org.onap.aai.champcore.exceptions.ChampUnmarshallingException;
34 import org.onap.aai.champcore.graph.impl.InMemoryChampGraphImpl;
35 import org.onap.aai.champcore.model.ChampCardinality;
36 import org.onap.aai.champcore.model.ChampField;
37 import org.onap.aai.champcore.model.ChampObject;
38 import org.onap.aai.champcore.model.ChampSchema;
39
40 import java.util.Collections;
41 import java.util.HashMap;
42 import java.util.List;
43 import java.util.Optional;
44 import java.util.stream.Collectors;
45 import java.util.stream.Stream;
46
47 import static org.junit.Assert.assertTrue;
48
49 public class ChampObjectTest extends BaseChampAPITest {
50
51   @Test
52   public void testHashCode() {
53     final ChampObject foo1 = ChampObject.create()
54         .ofType("foo")
55         .withoutKey()
56         .withProperty("property", "value")
57         .withProperty("prop", 1)
58         .build();
59
60     final ChampObject foo2 = ChampObject.create()
61         .ofType("foo")
62         .withoutKey()
63         .withProperty("property", "value")
64         .withProperty("prop", 1)
65         .build();
66
67     final ChampObject foo1Copy = ChampObject.create()
68         .from(foo1)
69         .withoutKey()
70         .build();
71
72     final ChampObject foo2Copy = ChampObject.create()
73         .from(foo2)
74         .withoutKey()
75         .build();
76
77     assertTrue(foo1.hashCode() == foo2.hashCode());
78     assertTrue(foo1.hashCode() == foo1.hashCode());
79     assertTrue(foo2.hashCode() == foo2.hashCode());
80     assertTrue(foo1.hashCode() == foo1Copy.hashCode());
81     assertTrue(foo2.hashCode() == foo2Copy.hashCode());
82
83     assertTrue(Collections.singleton(foo1).contains(foo1));
84     assertTrue(Collections.singleton(foo1).contains(foo1Copy));
85   }
86
87   @Test
88   public void runInMemoryTest() {
89     runTest("IN_MEMORY");
90   }
91
92   public void runTest(String apiType) {
93     final String graphName = ChampObjectTest.class.getSimpleName();
94
95     final ChampAPI api = ChampAPI.Factory.newInstance(apiType);
96     ChampObjectTest.testChampObjectCrud(api.getGraph(graphName));
97     testChampObjectReservedProperties(api.getGraph(graphName));
98     api.shutdown();
99   }
100
101   public static void testChampObjectCrud(ChampGraph graph) {
102     
103     // Create a dummy object...
104     final ChampObject bookooObject = ChampObject.create()
105         .ofType("foo")
106         .withoutKey()
107         .withProperty("property1", "value1")
108         .withProperty("integer", 1)
109         .withProperty("long", 1L)
110         .withProperty("double", 1.2)
111         .withProperty("float", 2.3F)
112         .withProperty("string", "foo")
113         .withProperty("boolean", true)
114         .withProperty("list", Collections.singletonList("list"))
115         .withProperty("set", Collections.singleton("set"))
116         .build();
117
118     final ChampObject storedBookooObject;
119    
120     try {
121
122       // Create a schema for the graph.
123       graph.storeSchema(ChampSchema.create()
124           .withObjectConstraint()
125           .onType("foo")
126           .withPropertyConstraint()
127           .onField("list")
128           .ofType(ChampField.Type.STRING)
129           .cardinality(ChampCardinality.LIST)
130           .optional()
131           .build()
132           .withPropertyConstraint()
133           .onField("set")
134           .ofType(ChampField.Type.STRING)
135           .cardinality(ChampCardinality.SET)
136           .optional()
137           .build()
138           .build()
139           .build());
140
141
142       
143       // Store the object in the graph.
144       storedBookooObject = graph.storeObject(bookooObject, Optional.empty());
145
146       // Check that the object we got back from the store call matches what we sent.
147       assertTrue(storedBookooObject.getProperty("property1").get().equals("value1"));
148       assertTrue(storedBookooObject.getProperty("integer").get().equals(1));
149       assertTrue(storedBookooObject.getProperty("long").get().equals(1L));
150       assertTrue(storedBookooObject.getProperty("double").get().equals(1.2));
151       assertTrue(storedBookooObject.getProperty("float").get().equals(2.3F));
152       assertTrue(storedBookooObject.getProperty("string").get().equals("foo"));
153       assertTrue(storedBookooObject.getProperty("boolean").get().equals(true));
154       assertTrue(storedBookooObject.getProperty("list").get().equals(Collections.singletonList("list")));
155       assertTrue(storedBookooObject.getProperty("set").get().equals(Collections.singleton("set")));
156
157       final Optional<ChampObject> retrievedBookooObject = graph.retrieveObject(storedBookooObject.getKey().get(), Optional.empty());
158         
159       final Stream<ChampObject> emptyStream = graph.queryObjects(new HashMap<String, Object>() {{
160         put(ChampObject.ReservedPropertyKeys.CHAMP_OBJECT_TYPE.toString(), "foo");
161         put("long", 2L);
162       }}, Optional.empty());
163
164       assertTrue(emptyStream.limit(1).count() == 0);
165
166       final Stream<ChampObject> oneStream = graph.queryObjects(new HashMap<String, Object>() {{
167         put(ChampObject.ReservedPropertyKeys.CHAMP_OBJECT_TYPE.toString(), "foo");
168         put("long", 1L);
169       }}, Optional.empty());
170       final List<ChampObject> oneObject = oneStream.limit(2).collect(Collectors.toList());
171       assertTrue(oneObject.size() == 1);
172       assertTrue(oneObject.get(0).equals(storedBookooObject));
173
174       final List<ChampObject> queryByKey = graph.queryObjects(Collections.singletonMap(ChampObject.ReservedPropertyKeys.CHAMP_OBJECT_KEY.toString(), storedBookooObject.getKey().get()), Optional.empty())
175           .limit(2)
176           .collect(Collectors.toList());
177
178       assertTrue(queryByKey.size() == 1);
179       assertTrue(queryByKey.get(0).equals(storedBookooObject));
180
181       if (!retrievedBookooObject.isPresent()) {
182         throw new AssertionError("Failed to retrieve stored object " + bookooObject);
183       }
184       if (!storedBookooObject.equals(retrievedBookooObject.get())) {
185         throw new AssertionError("Retrieved object does not equal stored object");
186       }
187       
188       final ChampObject updatedBookoo = graph.storeObject(ChampObject.create()
189           .from(storedBookooObject)
190           .withKey(storedBookooObject.getKey().get())
191           .withProperty("long", 2L)
192           .build(), Optional.empty());
193
194       final Optional<ChampObject> retrievedUpdBookooObject = graph.retrieveObject(updatedBookoo.getKey().get(), Optional.empty());
195
196       assertTrue(updatedBookoo.getProperty("property1").get().equals("value1"));
197       assertTrue(updatedBookoo.getProperty("integer").get().equals(1));
198       assertTrue(updatedBookoo.getProperty("long").get().equals(2L));
199       assertTrue(updatedBookoo.getProperty("double").get().equals(1.2));
200       assertTrue(updatedBookoo.getProperty("float").get().equals(2.3F));
201       assertTrue(updatedBookoo.getProperty("string").get().equals("foo"));
202       assertTrue(updatedBookoo.getProperty("boolean").get().equals(true));
203       assertTrue(updatedBookoo.getProperty("list").get().equals(Collections.singletonList("list")));
204       assertTrue(updatedBookoo.getProperty("set").get().equals(Collections.singleton("set")));
205
206       if (!retrievedUpdBookooObject.isPresent()) {
207         throw new AssertionError("Failed to retrieve stored object " + bookooObject);
208       }
209       if (!updatedBookoo.equals(retrievedUpdBookooObject.get())) {
210         throw new AssertionError("Retrieved object does not equal stored object");
211       }
212       
213       //validate the replaceObject method
214       final ChampObject replacedBookoo = graph.replaceObject(ChampObject.create()
215           .ofType("foo")
216           .withKey(storedBookooObject.getKey().get())
217           .withProperty("property1", "value2")
218           .withProperty("list", Collections.singletonList("list"))
219           .withProperty("set", Collections.singleton("set"))
220           .build(), Optional.empty());
221
222       final Optional<ChampObject> retrievedReplacedBookooObject = graph.retrieveObject(replacedBookoo.getKey().get(), Optional.empty());
223
224       assertTrue(replacedBookoo.getProperties().size() == 3);
225       assertTrue(replacedBookoo.getProperty("property1").get().equals("value2"));
226       assertTrue(replacedBookoo.getProperty("list").get().equals(Collections.singletonList("list")));
227       assertTrue(replacedBookoo.getProperty("set").get().equals(Collections.singleton("set")));
228
229
230       if (!retrievedReplacedBookooObject.isPresent()) {
231         throw new AssertionError("Failed to retrieve stored object " + replacedBookoo);
232       }
233       if (!replacedBookoo.equals(retrievedReplacedBookooObject.get())) {
234         throw new AssertionError("Retrieved object does not equal stored object");
235       }
236       
237       graph.deleteObject(storedBookooObject.getKey().get(), Optional.empty());
238       
239       if (graph.retrieveObject(storedBookooObject.getKey().get(), Optional.empty()).isPresent()) {
240         throw new AssertionError("Object not successfully deleted");
241       }
242
243       assertTrue(graph.queryObjects(Collections.emptyMap(), Optional.empty()).count() == 0);
244       assertTrue(graph.queryRelationships(Collections.emptyMap(), Optional.empty()).count() == 0);
245       
246       
247     } catch (ChampSchemaViolationException e) {
248       throw new AssertionError("Schema mismatch while storing object", e);
249     } catch (ChampMarshallingException e) {
250       throw new AssertionError("Marshalling exception while storing object", e);
251     } catch (ChampUnmarshallingException e) {
252       throw new AssertionError("Unmarshalling exception while retrieving object", e);
253     } catch (ChampObjectNotExistsException e) {
254       throw new AssertionError("Missing object on delete/update", e);
255     } catch (ChampTransactionException e) {
256       throw new AssertionError("Transaction exception occurred", e);
257     }
258     
259     try {
260       graph.deleteObject(storedBookooObject.getKey().get(), Optional.empty());
261       throw new AssertionError("Delete succeeded when it should have failed");
262     } catch (ChampObjectNotExistsException e) {
263       //Expected
264     } catch (ChampTransactionException e) {
265       throw new AssertionError("Transaction exception occurred", e);
266     } 
267     
268     try {
269       graph.storeObject(ChampObject.create()
270           .ofType("foo")
271           .withKey("non-existent object key")
272           .build(), Optional.empty());
273       throw new AssertionError("Expected ChampObjectNotExistsException but object was successfully stored");
274     } catch (ChampObjectNotExistsException e) {
275       //Expected
276     } catch (ChampMarshallingException e) {
277       throw new AssertionError(e);
278     } catch (ChampSchemaViolationException e) {
279       throw new AssertionError(e);
280     } catch (ChampTransactionException e) {
281       throw new AssertionError(e);
282     }
283
284     try {
285       // validate the replaceObject method when Object key is not passed
286       graph.replaceObject(
287           ChampObject.create().ofType("foo").withoutKey().withProperty("property1", "value2").build(), Optional.empty());
288     } catch (ChampObjectNotExistsException e) {
289       // Expected
290     } catch (ChampMarshallingException e) {
291       throw new AssertionError(e);
292     } catch (ChampSchemaViolationException e) {
293       throw new AssertionError(e);
294     } catch (ChampTransactionException e) {
295       throw new AssertionError(e);
296     }
297   }
298
299   public void testChampObjectReservedProperties(ChampGraph graph) {
300
301     for (ChampObject.ReservedPropertyKeys key : ChampObject.ReservedPropertyKeys.values()) {
302       try {
303         ChampObject.create()
304             .ofType(ChampObject.ReservedTypes.ANY.toString())
305             .withoutKey()
306             .withProperty(key.toString(), "")
307             .build();
308         throw new AssertionError("Allowed reserved property key to be used during object creation");
309       } catch (IllegalArgumentException e) {
310         //Expected
311       }
312     }
313   }
314
315   @Test
316   public void testFluentObjectCreation() {
317     final Object value1 = new Object();
318     final String value2 = "value2";
319     final float value3 = 0.0f;
320
321     final ChampObject champObject1 = ChampObject.create()
322         .ofType("foo")
323         .withoutKey()
324         .withProperty("key1", value1)
325         .withProperty("key2", value2)
326         .withProperty("key3", value3)
327         .build();
328
329     assertTrue(champObject1.getKey().equals(Optional.empty()));
330     assertTrue(champObject1.getKey().isPresent() == false);
331     assertTrue(champObject1.getType().equals("foo"));
332     assertTrue(champObject1.getProperty("key1").get() instanceof Object);
333     assertTrue(champObject1.getProperty("key1").get().equals(value1));
334     assertTrue(champObject1.getProperty("key2").get() instanceof String);
335     assertTrue(champObject1.getProperty("key2").get().equals(value2));
336     assertTrue(champObject1.getProperty("key3").get() instanceof Float);
337     assertTrue(champObject1.getProperty("key3").get().equals(value3));
338
339     final ChampObject champObject2 = ChampObject.create()
340         .ofType("foo")
341         .withKey(1)
342         .withProperty("key1", value1)
343         .withProperty("key2", value2)
344         .withProperty("key3", value3)
345         .build();
346
347     assertTrue(champObject2.getType().equals("foo"));
348     assertTrue(champObject2.getKey().isPresent() == true);
349     assertTrue(champObject2.getKey().get() instanceof Integer);
350     assertTrue(champObject2.getKey().get().equals(1));
351     assertTrue(champObject2.getProperty("key1").get() instanceof Object);
352     assertTrue(champObject2.getProperty("key1").get().equals(value1));
353     assertTrue(champObject2.getProperty("key2").get() instanceof String);
354     assertTrue(champObject2.getProperty("key2").get().equals(value2));
355     assertTrue(champObject2.getProperty("key3").get() instanceof Float);
356     assertTrue(champObject2.getProperty("key3").get().equals(value3));
357   }
358 }