f13b1066f6f02a080aa04aff8fd033b6ab9390ea
[ccsdk/features.git] /
1 /*******************************************************************************
2  * ============LICENSE_START========================================================================
3  * ONAP : ccsdk feature sdnr wt
4  * =================================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
6  * =================================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
8  * in compliance with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software distributed under the License
13  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
14  * or implied. See the License for the specific language governing permissions and limitations under
15  * the License.
16  * ============LICENSE_END==========================================================================
17  ******************************************************************************/
18 package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.database;
19
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.List;
23
24 import javax.annotation.Nullable;
25
26 import org.elasticsearch.index.query.QueryBuilder;
27 import org.elasticsearch.search.SearchHit;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 /**
32  * Generic class to write lists of model classes to the database.
33  *
34  */
35 public class HtDataBaseReaderAndWriter<T extends IsEsObject> {
36
37     private static final Logger log = LoggerFactory.getLogger(HtDataBaseReaderAndWriter.class);
38
39
40     private final HtDataBase db;
41     private final String dataTypeName;
42     private final HtMapper<T> mapper;
43
44     /**
45      * Class specific access to database
46      * @param db ES database descriptor
47      * @param dataTypeName datatype name
48      * @param clazz class of datatype
49      */
50     public HtDataBaseReaderAndWriter(HtDataBase db, String dataTypeName, Class<? extends T> clazz) {
51
52         this.db = db;
53         this.dataTypeName = dataTypeName;
54         this.mapper = new HtMapper<>( clazz );
55
56     }
57
58     /**
59      * Remove Object from database
60      * @param object Object with content
61      * @return true if remove is done
62      */
63     public boolean doRemove( T object) {
64
65         return db.doRemove(dataTypeName, object );
66
67     }
68
69     /**
70      * Remove all data that match the filter
71      * @param query to specify data to be deleted
72      * @return number of removed objects
73      */
74     public int doRemoveByQuery(QueryBuilder query) {
75
76         int idx = 0;                //Idx for getAll
77         int iterateLength = 100;    //Step width for iterate
78
79         SearchHit hits[];
80         do {
81             hits = db.doReadByQueryJsonData(idx, iterateLength, dataTypeName, query);
82             log.debug("Found: {} elements: {}  Failures: {}",dataTypeName,hits.length, mapper.getMappingFailures());
83
84             T object;
85             idx += hits.length;
86             for (SearchHit hit : hits) {
87
88                 object = mapper.getObjectFromJson( hit.getSourceRef() );
89
90                 log.debug("Mapp Object: {}\nSource: '{}'\nResult: '{}'\n Failures: {}", hit.getId(), hit.getSourceAsString(), object, mapper.getMappingFailures());
91                 if (object != null) {
92                     object.setEsId( hit.getId() );
93                     doRemove(object);
94                 } else {
95                     log.warn("Mapp result null Object: {}\n Source: '{}'\n : '", hit.getId(), hit.getSourceAsString());
96                 }
97             }
98         } while (hits.length == iterateLength); //Do it until end indicated, because less hits than iterateLength allows.
99
100         return idx;
101     }
102
103     /**
104      * Do the mapping for test purpose
105      * @param object object for test purpose
106      * @return json String
107      */
108     public String getJson( T object ) {
109         String json = mapper.objectToJson(object);
110         return json;
111     }
112
113     /**
114      * Write one object into Database
115      * @param object Object with content
116      * @return This object for chained call pattern.
117      */
118     public T doWrite( T object) {
119
120         String json = mapper.objectToJson(object);
121         return doWrite(object, json);
122
123     }
124
125     /**
126      * Write one object into Database
127      * @param object Object with content
128      * @param json string
129      * @return This object for chained call pattern.
130      */
131     public T doWrite( T object, String json) {
132
133         log.debug("doWrite {} {}",object.getClass().getSimpleName(), object.getEsId());
134
135         if (json != null) {
136             String esId = db.doWriteJsonString(dataTypeName, object, json);
137             object.setEsId(esId);
138             log.debug("doWrite done for {} {}",object.getClass().getSimpleName(), object.getEsId());
139             return esId == null ? null : object;
140         } else {
141             log.warn("Can not map object and write to database. {} {}",object.getClass().getSimpleName(), object);
142             return null;
143         }
144
145     }
146
147
148     /**
149      * Write a list of Objects to the database.
150      * @param list Object list with content
151      * @return This object for chained call pattern.
152      */
153     public HtDataBaseReaderAndWriter<T> doWrite( Collection<T> list) {
154
155         int writeError = 0;
156         String indexName = db.getNetworkIndex();
157
158         log.debug("Write to ES database {}, {} Class: {}  {} elements",indexName,dataTypeName, mapper.getClazz().getSimpleName(), list.size());
159
160         if (indexName == null) {
161             throw new IllegalArgumentException("Missing Index");
162         }
163
164         if (list != null && !list.isEmpty()) {
165             for( T s : list ) {
166                 if ( doWrite(s) == null )  {
167                     if ( ++writeError > 5 ) {
168                         log.warn("Leave because of to >5 write errors");
169                         break;
170                     }
171                 }
172             }
173
174         }
175
176         return this;
177     }
178
179     /**
180      * Read one object via the object class specific ID
181      * @param object Object refrenced by idString
182      * @return The Object if found or null
183      */
184     public @Nullable T doRead( IsEsObject object ) {
185         T res = mapper.getObjectFromJson( db.doReadJsonData( dataTypeName, object) );
186         if (res != null) {
187             res.setEsId(object.getEsId());
188         }
189         return res;
190     }
191
192     /**
193      * Read one object via the object class specific ID
194      * @param objectEsId Object refrence
195      * @return The Object if found or null
196      */
197     public @Nullable T doRead( String objectEsId ) {
198         T res = mapper.getObjectFromJson( db.doReadJsonData( dataTypeName, objectEsId ) );
199         if (res != null) {
200             res.setEsId(objectEsId);
201         }
202         return res;
203     }
204
205
206     /**
207      * Read all existing objects of a type
208      * @return the list of all objects
209      */
210     public List<T> doReadAll() {
211
212         List<T> res = new ArrayList<>();
213         int idx = 0;                //Idx for getAll
214         int iterateLength = 100;    //Step width for iterate
215
216         SearchHit hits[];
217
218
219         do {
220             hits = db.doReadAllJsonData(idx, iterateLength, dataTypeName);
221             log.debug("Read: {} elements: {}  Failures: {}",dataTypeName,hits.length, mapper.getMappingFailures());
222
223             T object;
224             idx += hits.length;
225             for (SearchHit hit : hits) {
226
227                 object = mapper.getObjectFromJson( hit.getSourceRef() );
228
229                 log.debug("Mapp Object: {}\nSource: '{}'\nResult: '{}'\n Failures: {}", hit.getId(), hit.getSourceAsString(), object, mapper.getMappingFailures());
230                 if (object != null) {
231                     object.setEsId( hit.getId() );
232                     res.add( object );
233                 } else {
234                     log.warn("Mapp result null Object: {}\n Source: '{}'\n : '", hit.getId(), hit.getSourceAsString());
235                 }
236             }
237         } while (hits.length == iterateLength); //Do it until end indicated, because less hits than iterateLength allows.
238
239         return res;
240     }
241
242 }