Merge "Reformat sdnr devicemanager-onf to ONAP code style"
[ccsdk/features.git] / sdnr / wt / common / src / test / java / org / onap / ccsdk / features / sdnr / wt / common / test / TestDbRequests.java
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : ccsdk features
4  * ================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property.
6  * All rights reserved.
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  */
22 package org.onap.ccsdk.features.sdnr.wt.common.test;
23
24 import org.junit.AfterClass;
25 import org.junit.BeforeClass;
26 import org.junit.Test;
27 import org.onap.ccsdk.features.sdnr.wt.common.database.HtDatabaseClient;
28 import org.onap.ccsdk.features.sdnr.wt.common.database.config.HostInfo;
29 import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilders;
30 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.ClusterHealthRequest;
31 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.ClusterSettingsRequest;
32 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.CreateAliasRequest;
33 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.CreateIndexRequest;
34 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.DeleteAliasRequest;
35 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.DeleteByQueryRequest;
36 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.DeleteIndexRequest;
37 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.DeleteRequest;
38 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.GetIndexRequest;
39 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.GetRequest;
40 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.IndexRequest;
41 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.NodeStatsRequest;
42 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.RefreshIndexRequest;
43 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.SearchRequest;
44 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.UpdateByQueryRequest;
45 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.UpdateRequest;
46 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.ClusterHealthResponse;
47 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.ClusterSettingsResponse;
48 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.CreateAliasResponse;
49 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.CreateIndexResponse;
50 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.DeleteByQueryResponse;
51 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.DeleteIndexResponse;
52 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.DeleteResponse;
53 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.GetResponse;
54 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.ListIndicesResponse;
55 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.NodeStatsResponse;
56 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.SearchResponse;
57 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.UpdateByQueryResponse;
58 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.UpdateResponse;
59
60 import static org.junit.Assert.assertEquals;
61 import static org.junit.Assert.assertFalse;
62 import static org.junit.Assert.assertNotNull;
63 import static org.junit.Assert.assertNull;
64 import static org.junit.Assert.assertTrue;
65 import static org.junit.Assert.fail;
66 import java.io.IOException;
67 import java.text.ParseException;
68 import java.util.Arrays;
69 import java.util.List;
70
71 import org.json.JSONException;
72 import org.json.JSONObject;
73
74 public class TestDbRequests {
75
76     private static HtDatabaseClient dbClient;
77     private static HostInfo[] hosts = new HostInfo[] {new HostInfo("localhost", Integer
78             .valueOf(System.getProperty("databaseport") != null ? System.getProperty("databaseport") : "49200"))};
79
80     @BeforeClass
81     public static void init() throws Exception {
82
83         dbClient = new HtDatabaseClient(hosts);
84
85     }
86
87     @AfterClass
88     public static void deinit() {
89         if (dbClient != null) {
90             dbClient.close();
91         }
92     }
93
94     @Test
95     public void testHealth() {
96
97         ClusterHealthResponse response = null;
98         ClusterHealthRequest request = new ClusterHealthRequest();
99         request.timeout(10);
100         try {
101             response = dbClient.health(request);
102         } catch (UnsupportedOperationException | IOException | JSONException e) {
103             fail(e.getMessage());
104         }
105         assertNotNull("response is null", response);
106         assertTrue(response.isStatusMinimal(ClusterHealthResponse.HEALTHSTATUS_YELLOW));
107     }
108
109     @Test
110     public void testCount() {
111
112     }
113
114     @Test
115     public void testIndexAndAliasList() {
116         final String ALIAS = "asdoi32kmsasd";
117         final String IDX = ALIAS + "-v1";
118         CreateIndexRequest request = new CreateIndexRequest(IDX);
119         CreateIndexResponse response = null;
120         try {
121             response = dbClient.createIndex(request);
122         } catch (IOException e) {
123             fail(e.getMessage());
124         }
125         assertNotNull(response);
126
127         CreateAliasRequest request3 = new CreateAliasRequest(IDX, ALIAS);
128         CreateAliasResponse response3 = null;
129         try {
130             response3 = dbClient.createAlias(request3);
131         } catch (IOException e) {
132             fail(e.getMessage());
133         }
134         assertNotNull(response3);
135         assertTrue(response3.isResponseSucceeded());
136
137         assertTrue("index not existing", dbClient.isExistsIndex(IDX));
138         ListIndicesResponse response2 = null;
139         try {
140             response2 = dbClient.getIndices();
141         } catch (ParseException | IOException e) {
142             fail(e.getMessage());
143         }
144         assertNotNull(response2);
145         assertNotNull(response2.getEntries());
146         assertTrue(response2.getEntries().size() > 0);
147
148         DeleteIndexRequest request11 = new DeleteIndexRequest(IDX);
149
150         DeleteIndexResponse response11 = null;
151         try {
152             response11 = dbClient.deleteIndex(request11);
153         } catch (IOException e) {
154             fail(e.getMessage());
155         }
156         assertNotNull(response11);
157         assertFalse("index still existing", dbClient.isExistsIndex(IDX));
158         this.deleteAlias(IDX, ALIAS);
159         this.deleteIndex(IDX);
160     }
161
162     @Test
163     public void testCreateAndDeleteIndex() {
164         final String IDX = "testcidx1";
165         CreateIndexRequest request = new CreateIndexRequest(IDX);
166         CreateIndexResponse response = null;
167         try {
168             response = dbClient.createIndex(request);
169         } catch (IOException e) {
170             fail(e.getMessage());
171         }
172         assertNotNull(response);
173
174         assertTrue("index not existing", dbClient.isExistsIndex(IDX));
175
176         DeleteIndexRequest request2 = new DeleteIndexRequest(IDX);
177
178         DeleteIndexResponse response2 = null;
179         try {
180             response2 = dbClient.deleteIndex(request2);
181         } catch (IOException e) {
182             fail(e.getMessage());
183         }
184         assertNotNull(response2);
185         assertFalse("index still existing", dbClient.isExistsIndex(IDX));
186         this.deleteIndex(IDX);
187     }
188
189     @Test
190     public void testInsertAndDelete() {
191         final String IDX = "tesnt23-knmoinsd";
192         final String ID = "abcddd";
193         final String JSON = "{\"data\":{\"inner\":\"more\"}}";
194         try {
195             if (!dbClient.indicesExists(new GetIndexRequest(IDX))) {
196                 dbClient.createIndex(new CreateIndexRequest(IDX).mappings(defaultMappings(IDX, false)));
197             }
198         } catch (IOException e) {
199             fail("unable to create index");
200         }
201         this.insert(IDX, ID, JSON);
202         // delete data
203         DeleteRequest request2 = new DeleteRequest(IDX, IDX, ID);
204         DeleteResponse response2 = null;
205         try {
206             response2 = dbClient.delete(request2);
207         } catch (IOException e) {
208             fail(e.getMessage());
209         }
210         assertNotNull(response2);
211         assertTrue(response2.isDeleted());
212         try {
213             dbClient.refreshIndex(new RefreshIndexRequest(IDX));
214         } catch (IOException e) {
215             fail(e.getMessage());
216         }
217         // verify data deleted
218         GetRequest request4 = new GetRequest(IDX, IDX, ID);
219         GetResponse response4 = null;
220         try {
221             response4 = dbClient.get(request4);
222         } catch (IOException e1) {
223             fail(e1.getMessage());
224         }
225         assertNotNull(response4);
226         assertFalse("data still existing", response4.isExists());
227         this.deleteIndex(IDX);
228     }
229
230     /**
231      * @param b
232      * @return
233      */
234     private JSONObject defaultMappings(String idx, boolean useStrict) {
235         String mapping = "{}";
236         return new JSONObject(String.format("{\"%s\":{%s\"properties\":%s}}", idx,
237                 useStrict ? "\"dynamic\": false," : "\"dynamic\": true,", mapping));
238     }
239
240     @Test
241     public void testInsertAndDeleteByQuery() {
242         final String IDX = "test534-knmoinsd";
243         final String ID = "abcdddseae";
244         final String JSON = "{\"data\":{\"inner\":\"more\"}}";
245         try {
246             if (!dbClient.indicesExists(new GetIndexRequest(IDX))) {
247                 dbClient.createIndex(new CreateIndexRequest(IDX));
248             }
249         } catch (IOException e) {
250             fail("unable to create index");
251         }
252         this.insert(IDX, ID, JSON);
253
254         // delete data
255         DeleteByQueryRequest request2 = new DeleteByQueryRequest(IDX);
256         request2.source(QueryBuilders.matchQuery("_id", ID));
257         DeleteByQueryResponse response2 = null;
258         try {
259             response2 = dbClient.deleteByQuery(request2);
260         } catch (IOException e) {
261             fail(e.getMessage());
262         }
263         assertNotNull(response2);
264         assertTrue(response2.isResponseSucceeded());
265         try {
266             dbClient.refreshIndex(new RefreshIndexRequest(IDX));
267         } catch (IOException e) {
268             fail(e.getMessage());
269         }
270         // verify data deleted
271         GetRequest request4 = new GetRequest(IDX, IDX, ID);
272         GetResponse response4 = null;
273         try {
274             response4 = dbClient.get(request4);
275         } catch (IOException e1) {
276             fail(e1.getMessage());
277         }
278         assertNotNull(response4);
279         assertFalse("data still existing", response4.isExists());
280         this.deleteIndex(IDX);
281     }
282
283     private void insert(String IDX, String ID, String JSON) {
284
285         // create data
286         IndexRequest request = new IndexRequest(IDX, IDX, ID);
287         request.source(JSON);
288         String responseId = null;
289         responseId = dbClient.doWriteRaw(IDX, ID, JSON);
290         assertNotNull(responseId);
291         if (ID != null) {
292             assertEquals("id not correct", ID, responseId);
293         } else {
294             ID = responseId;
295         }
296         // do db refresh
297         try {
298             dbClient.refreshIndex(new RefreshIndexRequest(IDX));
299         } catch (IOException e) {
300             fail(e.getMessage());
301         }
302         // verify data exists
303         String response3 = null;
304         response3 = dbClient.doReadJsonData(IDX, ID);
305         assertNotNull(response3);
306         JSONAssert.assertEquals("could not verify update", JSON, response3, true);
307     }
308
309     @Test
310     public void testSearch() {
311         final String IDX = "testb44-moinsd";
312         final String ID = "abe";
313         final String JSON = "{\"data\":{\"inner\":\"more\"}}";
314         final String ID2 = "abe2";
315         final String JSON2 = "{\"data\":{\"inner\":\"more2\"}}";
316         final String ID3 = "abe3";
317         final String JSON3 = "{\"data\":{\"inner\":\"more3\"}}";
318         try {
319             if (!dbClient.indicesExists(new GetIndexRequest(IDX))) {
320                 dbClient.createIndex(new CreateIndexRequest(IDX));
321             }
322         } catch (IOException e) {
323             fail("unable to create index");
324         }
325         this.insert(IDX, ID, JSON);
326         this.insert(IDX, ID2, JSON2);
327         this.insert(IDX, ID3, JSON3);
328         SearchRequest request = new SearchRequest(IDX, IDX);
329         request.setQuery(QueryBuilders.matchAllQuery());
330         SearchResponse response = null;
331         try {
332             response = dbClient.search(request);
333         } catch (IOException e) {
334             fail(e.getMessage());
335         }
336         assertNotNull(response);
337         assertEquals("not all items found", 3, response.getHits().length);
338         assertEquals("incorrect index", IDX, response.getHits()[0].getIndex());
339         assertEquals("incorrect type", IDX, response.getHits()[0].getType());
340         this.deleteIndex(IDX);
341     }
342
343     @Test
344     public void testUpdate() {
345         final String IDX = "test45134-moinsd";
346         final String ID = "assbe";
347         final String JSON = "{\"data\":{\"inner\":\"more\"}}";
348         final String JSON2 = "{\"data\":{\"inner\":\"more2\"},\"data2\":\"value2\",\"data3\":true}";
349         try {
350             if (!dbClient.indicesExists(new GetIndexRequest(IDX))) {
351                 dbClient.createIndex(new CreateIndexRequest(IDX));
352             }
353         } catch (IOException e) {
354             fail("unable to create index");
355         }
356         this.insert(IDX, ID, JSON);
357         UpdateRequest request = new UpdateRequest(IDX, IDX, ID);
358         UpdateResponse response = null;
359         try {
360             request.source(new JSONObject(JSON2));
361             response = dbClient.update(request);
362         } catch (JSONException | IOException e) {
363             fail(e.getMessage());
364         }
365         assertNotNull(response);
366         assertTrue(response.succeeded());
367         // refresh index
368         try {
369             dbClient.refreshIndex(new RefreshIndexRequest(IDX));
370         } catch (IOException e) {
371             fail(e.getMessage());
372         }
373         // verify update
374         GetRequest request3 = new GetRequest(IDX, IDX, ID);
375         GetResponse response3 = null;
376         try {
377             response3 = dbClient.get(request3);
378         } catch (IOException e1) {
379             fail(e1.getMessage());
380         }
381         assertNotNull(response3);
382         JSONAssert.assertEquals("could not verify update", JSON2, response3.getSourceAsBytesRef(), true);
383         this.deleteIndex(IDX);
384     }
385
386     @Test
387     public void testUpdateByQuery() {
388         final String IDX = "test224534k-moinsd";
389         final String ID = "asssabe";
390         final String JSON = "{\"data\":{\"inner\":\"more\"}}";
391         final String JSON2 = "{\"data\":{\"inner\":\"more2\"},\"data2\":\"value2\",\"data3\":true}";
392         try {
393             if (!dbClient.indicesExists(new GetIndexRequest(IDX))) {
394                 dbClient.createIndex(new CreateIndexRequest(IDX));
395             }
396         } catch (IOException e) {
397             fail("unable to create index");
398         }
399         this.insert(IDX, ID, JSON);
400         UpdateByQueryRequest request = new UpdateByQueryRequest(IDX, IDX);
401         UpdateByQueryResponse response = null;
402         try {
403             request.source(ID, new JSONObject(JSON2));
404             response = dbClient.update(request);
405         } catch (JSONException | IOException e) {
406             fail(e.getMessage());
407         }
408         assertNotNull(response);
409         assertTrue(response.isUpdated());
410         // refresh index
411         try {
412             dbClient.refreshIndex(new RefreshIndexRequest(IDX));
413         } catch (IOException e) {
414             fail(e.getMessage());
415         }
416         // verify update
417         GetRequest request3 = new GetRequest(IDX, IDX, ID);
418         GetResponse response3 = null;
419         try {
420             response3 = dbClient.get(request3);
421         } catch (IOException e1) {
422             fail(e1.getMessage());
423         }
424         assertNotNull(response3);
425         JSONAssert.assertEquals("could not verify update", JSON2, response3.getSourceAsBytesRef(), true);
426         this.deleteIndex(IDX);
427     }
428
429     @Test
430     public void testAggregations() {
431         final String IDX = "test3227533677-moisnsd";
432         final String JSON = "{ \"node-id\":\"sim1\",\"severity\":\"critical\"}";
433         final String JSON2 = "{ \"node-id\":\"sim2\",\"severity\":\"critical\"}";
434         final String JSON3 = "{ \"node-id\":\"sim3\",\"severity\":\"minor\"}";
435         final String JSON4 = "{ \"node-id\":\"sim4\",\"severity\":\"warning\"}";
436         final String JSON5 = "{ \"node-id\":\"sim5\",\"severity\":\"major\"}";
437         final String MAPPINGS = String.format("{\"" + IDX + "\":{\"properties\":%s}}",
438                 "{\"node-id\":{\"type\": \"keyword\"},\"severity\": {\"type\": \"keyword\"}}");
439         // create index with mapping keyword
440         CreateIndexResponse iresponse = null;
441         try {
442             if (!dbClient.isExistsIndex(IDX)) {
443                 iresponse = dbClient.createIndex(new CreateIndexRequest(IDX).mappings(new JSONObject(MAPPINGS)));
444                 assertNotNull(iresponse);
445                 assertTrue(iresponse.isAcknowledged());
446             }
447         } catch (IOException e1) {
448             this.deleteIndex(IDX);
449             fail("unable to create index: " + e1.getMessage());
450         }
451
452         // fill index
453         this.insert(IDX, null, JSON);
454         this.insert(IDX, null, JSON2);
455         this.insert(IDX, null, JSON3);
456         this.insert(IDX, null, JSON4);
457         this.insert(IDX, null, JSON5);
458         // refresh index
459         try {
460             dbClient.refreshIndex(new RefreshIndexRequest(IDX));
461         } catch (IOException e) {
462             fail(e.getMessage());
463         }
464
465         SearchRequest request = new SearchRequest(IDX, IDX);
466         request.setQuery(QueryBuilders.matchAllQuery().aggregations("severity").size(0));
467         SearchResponse response = null;
468         try {
469             response = dbClient.search(request);
470         } catch (IOException e) {
471             fail(e.getMessage());
472         }
473         assertNotNull(response);
474         assertTrue(response.hasAggregations());
475         assertEquals("aggregation size not correct", 4, response.getAggregations("severity").size());
476
477         List<String> items1 = Arrays.asList(response.getAggregations("severity").getKeysAsPagedStringList(2, 0));
478         List<String> items2 = Arrays.asList(response.getAggregations("severity").getKeysAsPagedStringList(2, 2));
479         assertEquals("pagination does not work", 2, items1.size());
480         assertEquals("pagination does not work", 2, items2.size());
481         for (String s : items1) {
482             assertFalse("pagination overlap is not allowed", items2.contains(s));
483         }
484         for (String s : items2) {
485             assertFalse("pagination overlap is not allowed", items1.contains(s));
486         }
487
488         this.deleteIndex(IDX);
489     }
490
491     @Test
492     public void testStatistics() {
493         NodeStatsResponse stats = null;
494         try {
495             stats = dbClient.stats(new NodeStatsRequest());
496         } catch (IOException e) {
497             fail(e.getMessage());
498         }
499         assertNotNull(stats);
500         System.out.println(stats.getNodesInfo());
501         System.out.println(stats.getNodeStatistics());
502     }
503
504     // @Test
505     public void testPreventAutoCreateIndex() {
506         final String IDX1 = "acidx1";
507         final String ID1 = "acid1";
508         final String IDX2 = "acidx2";
509         final String ID2 = "acid2";
510         final String OBJ = "{\"test\":5}";
511
512         ClusterSettingsResponse settingsResponse = null;
513         String esId = null;
514         // set setting to allow autocreate
515         try {
516             settingsResponse = dbClient.setupClusterSettings(new ClusterSettingsRequest(true));
517         } catch (IOException e) {
518             fail(e.getMessage());
519         }
520         assertNotNull(settingsResponse);
521         assertTrue(settingsResponse.isAcknowledged());
522         // test if something new can be created
523         esId = dbClient.doWriteRaw(IDX1, IDX1, ID1, OBJ);
524         assertEquals(ID1, esId);
525         // set setting to deny autocreate
526         try {
527             settingsResponse = dbClient.setupClusterSettings(new ClusterSettingsRequest(false));
528         } catch (IOException e) {
529             fail(e.getMessage());
530         }
531         assertNotNull(settingsResponse);
532         assertTrue(settingsResponse.isAcknowledged());
533         // test if something new cannot be created
534         esId = dbClient.doWriteRaw(IDX2, IDX2, ID2, OBJ);
535         assertNull(esId);
536         // set setting to allow autocreate
537         try {
538             settingsResponse = dbClient.setupClusterSettings(new ClusterSettingsRequest(true));
539         } catch (IOException e) {
540             fail(e.getMessage());
541         }
542         assertNotNull(settingsResponse);
543         assertTrue(settingsResponse.isAcknowledged());
544
545     }
546
547     private void deleteAlias(String idx, String alias) {
548         try {
549             dbClient.deleteAlias(new DeleteAliasRequest(idx, alias));
550         } catch (IOException e) {
551
552         }
553     }
554
555     private void deleteIndex(String idx) {
556         try {
557             dbClient.deleteIndex(new DeleteIndexRequest(idx));
558         } catch (IOException e) {
559
560         }
561     }
562
563 }