a742a94b02f30d2a6ed9c6945e9488fd0a9c728f
[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      * @return dataTypeName
59      */
60     public String getDataTypeName() {
61         return this.dataTypeName;
62     }
63     /**
64      * Remove Object from database
65      * @param object Object with content
66      * @return true if remove is done
67      */
68     public boolean doRemove( T object) {
69
70         return db.doRemove(dataTypeName, object );
71
72     }
73
74     /**
75      * Remove all data that match the filter
76      * @param query to specify data to be deleted
77      * @return number of removed objects
78      */
79     public int doRemoveByQuery(QueryBuilder query) {
80
81         int idx = 0;                //Idx for getAll
82         int iterateLength = 100;    //Step width for iterate
83
84         SearchHit hits[];
85         do {
86             hits = db.doReadByQueryJsonData(idx, iterateLength, dataTypeName, query);
87             log.debug("Found: {} elements: {}  Failures: {}",dataTypeName,hits.length, mapper.getMappingFailures());
88
89             T object;
90             idx += hits.length;
91             for (SearchHit hit : hits) {
92
93                 object = mapper.getObjectFromJson( hit.getSourceRef() );
94
95                 log.debug("Mapp Object: {}\nSource: '{}'\nResult: '{}'\n Failures: {}", hit.getId(), hit.getSourceAsString(), object, mapper.getMappingFailures());
96                 if (object != null) {
97                     object.setEsId( hit.getId() );
98                     doRemove(object);
99                 } else {
100                     log.warn("Mapp result null Object: {}\n Source: '{}'\n : '", hit.getId(), hit.getSourceAsString());
101                 }
102             }
103         } while (hits.length == iterateLength); //Do it until end indicated, because less hits than iterateLength allows.
104
105         return idx;
106     }
107
108     /**
109      * Do the mapping for test purpose
110      * @param object object for test purpose
111      * @return json String
112      */
113     public String getJson( T object ) {
114         String json = mapper.objectToJson(object);
115         return json;
116     }
117
118     /**
119      * Write one object into Database
120      * @param object Object with content
121      * @return This object for chained call pattern.
122      */
123     public T doWrite( T object) {
124
125         String json = mapper.objectToJson(object);
126         return doWrite(object, json);
127
128     }
129
130     /**
131      * Write one object into Database
132      * @param object Object with content
133      * @param json string
134      * @return This object for chained call pattern.
135      */
136     public T doWrite( T object, String json) {
137
138         log.debug("doWrite {} {}",object.getClass().getSimpleName(), object.getEsId());
139
140         if (json != null) {
141             String esId = db.doWriteJsonString(dataTypeName, object, json);
142             object.setEsId(esId);
143             log.debug("doWrite done for {} {}",object.getClass().getSimpleName(), object.getEsId());
144             return esId == null ? null : object;
145         } else {
146             log.warn("Can not map object and write to database. {} {}",object.getClass().getSimpleName(), object);
147             return null;
148         }
149
150     }
151
152
153     /**
154      * Write a list of Objects to the database.
155      * @param list Object list with content
156      * @return This object for chained call pattern.
157      */
158     public HtDataBaseReaderAndWriter<T> doWrite( Collection<T> list) {
159
160         int writeError = 0;
161         String indexName = db.getNetworkIndex();
162
163         log.debug("Write to ES database {}, {} Class: {}  {} elements",indexName,dataTypeName, mapper.getClazz().getSimpleName(), list.size());
164
165         if (indexName == null) {
166             throw new IllegalArgumentException("Missing Index");
167         }
168
169         if (list != null && !list.isEmpty()) {
170             for( T s : list ) {
171                 if ( doWrite(s) == null )  {
172                     if ( ++writeError > 5 ) {
173                         log.warn("Leave because of to >5 write errors");
174                         break;
175                     }
176                 }
177             }
178
179         }
180
181         return this;
182     }
183
184     /**
185      * Read one object via the object class specific ID
186      * @param object Object refrenced by idString
187      * @return The Object if found or null
188      */
189     public @Nullable T doRead( IsEsObject object ) {
190         T res = mapper.getObjectFromJson( db.doReadJsonData( dataTypeName, object) );
191         if (res != null) {
192             res.setEsId(object.getEsId());
193         }
194         return res;
195     }
196
197     /**
198      * Read one object via the object class specific ID
199      * @param objectEsId Object refrence
200      * @return The Object if found or null
201      */
202     public @Nullable T doRead( String objectEsId ) {
203         T res = mapper.getObjectFromJson( db.doReadJsonData( dataTypeName, objectEsId ) );
204         if (res != null) {
205             res.setEsId(objectEsId);
206         }
207         return res;
208     }
209     /**
210      * Get all elements of related type
211      * @return all Elements
212      */
213     public List<T> doReadAll() {
214         return doReadAll(null);
215     }
216     /**
217      * Read all existing objects of a type
218      * @param query for the elements
219      * @return the list of all objects
220      */
221     public List<T> doReadAll(QueryBuilder query) {
222
223         List<T> res = new ArrayList<>();
224         int idx = 0;                //Idx for getAll
225         int iterateLength = 100;    //Step width for iterate
226
227         SearchHit hits[];
228         do {
229             if(query!=null) {
230                 log.trace("read data in {} {} with query {}",db.getNetworkIndex(),dataTypeName,query);
231                 hits=db.doReadByQueryJsonData(0, 99999, dataTypeName, query);
232             }
233             else {
234                 hits = db.doReadAllJsonData(idx, iterateLength, dataTypeName);
235             }
236             log.debug("Read: {} elements: {}  Failures: {}",dataTypeName,hits.length, mapper.getMappingFailures());
237
238             T object;
239             idx += hits.length;
240             for (SearchHit hit : hits) {
241
242                 object = mapper.getObjectFromJson( hit.getSourceRef() );
243
244                 log.debug("Mapp Object: {}\nSource: '{}'\nResult: '{}'\n Failures: {}", hit.getId(), hit.getSourceAsString(), object, mapper.getMappingFailures());
245                 if (object != null) {
246                     object.setEsId( hit.getId() );
247                     res.add( object );
248                 } else {
249                     log.warn("Mapp result null Object: {}\n Source: '{}'\n : '", hit.getId(), hit.getSourceAsString());
250                 }
251             }
252         } while (hits.length == iterateLength); //Do it until end indicated, because less hits than iterateLength allows.
253
254         return res;
255     }
256
257 }