603c25baea4fb0e22f4c17ce3ea836c48da08fe9
[ccsdk/features.git] /
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.dataprovider.database;
23
24 import com.fasterxml.jackson.core.JsonProcessingException;
25 import java.io.IOException;
26 import java.lang.reflect.Field;
27 import java.util.List;
28 import javax.annotation.Nonnull;
29 import javax.annotation.Nullable;
30 import org.eclipse.jdt.annotation.NonNull;
31 import org.onap.ccsdk.features.sdnr.wt.common.database.DatabaseClient;
32 import org.onap.ccsdk.features.sdnr.wt.common.database.SearchHit;
33 import org.onap.ccsdk.features.sdnr.wt.common.database.SearchResult;
34 import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilder;
35 import org.onap.ccsdk.features.sdnr.wt.dataprovider.yangtools.YangToolsMapper2;
36 import org.onap.ccsdk.features.sdnr.wt.dataprovider.yangtools.YangToolsMapperHelper;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.Entity;
38 import org.opendaylight.yangtools.concepts.Builder;
39 import org.opendaylight.yangtools.yang.binding.DataObject;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * Class to rw yang-tool generated objects into elasticsearch database. For "ES _id" exchange the esIdAddAtributteName
45  * is used. This attribute mast be of type String and contains for read and write operations the object id. The function
46  * can be used without id handling. If id handling is required the parameter needs to be specified by class definition
47  * in yang and setting the name by using setAttributeName()
48  *
49  * Due to using Jackson base interfaces the org.eclipse.jdt.annotation.NonNull needs to be used here to get rid of
50  * warnings
51  *
52  * @param <T> Yang tools generated class object.
53  */
54 public class EsDataObjectReaderWriter2<T extends DataObject> {
55
56     private final Logger LOG = LoggerFactory.getLogger(EsDataObjectReaderWriter2.class);
57
58     /** Typename for elastic search data schema **/
59     private String dataTypeName;
60
61     /** Elasticsearch Database client to be used **/
62     private DatabaseClient db;
63
64     /** Mapper with configuration to use opendaylight yang-tools builder pattern for object creation **/
65     private YangToolsMapper2<T> yangtoolsMapper;
66
67     /** Class of T as attribute to allow JSON to Class object mapping **/
68     private Class<T> clazz;
69
70     /** Field is used to write id. If null no id handling **/
71     private @Nullable Field field;
72
73     /** Attribute that is used as id field for the database object **/
74     private @Nullable String esIdAddAtributteName;
75
76     /** Interface to be used for write operations. Rule for write: T extends S and **/
77     private Class<? extends DataObject> writeInterfaceClazz; // == "S"
78     /** Flag true to sync this attribute during write always, what is slow and false do not sync */
79     private final boolean syncAfterWrite;
80
81     /**
82      * Elasticsearch database read and write for specific class, defined by opendaylight yang-tools.
83      *
84      * @param <X>
85      * @param <B>
86      * @param db Database access client
87      * @param dataTypeName typename in database schema
88      * @param clazz class of type to be handled
89      * @param builderClazz class to build related object if builder pattern should be used.
90      * @param syncAfterWrite
91      * @throws ClassNotFoundException
92      */
93     public <X extends T, @NonNull B extends Builder<X>> EsDataObjectReaderWriter2(DatabaseClient db,
94             String dataTypeName, @Nonnull Class<T> clazz, @Nullable Class<B> builderClazz, boolean syncAfterWrite)
95             throws ClassNotFoundException {
96         LOG.info("Create {} for datatype {} class {}", this.getClass().getName(), dataTypeName, clazz.getName());
97
98         this.esIdAddAtributteName = null;
99         this.field = null;
100         this.writeInterfaceClazz = clazz;
101         this.db = db;
102         this.dataTypeName = dataTypeName;
103         this.yangtoolsMapper = new YangToolsMapper2<>(clazz, builderClazz);
104         this.clazz = clazz;
105         this.syncAfterWrite = syncAfterWrite;
106     }
107
108     public <X extends T, @NonNull B extends Builder<X>> EsDataObjectReaderWriter2(DatabaseClient db,
109             Entity dataTypeName, @Nonnull Class<T> clazz, @Nullable Class<B> builderClazz)
110             throws ClassNotFoundException {
111         this(db, dataTypeName.getName(), clazz, builderClazz, false);
112     }
113
114     public <X extends T, @NonNull B extends Builder<X>> EsDataObjectReaderWriter2(DatabaseClient db,
115             Entity dataTypeName, @Nonnull Class<T> clazz, @Nullable Class<B> builderClazz, boolean syncAfterWrite)
116             throws ClassNotFoundException {
117         this(db, dataTypeName.getName(), clazz, builderClazz, syncAfterWrite);
118     }
119
120     public EsDataObjectReaderWriter2(DatabaseClient db, Entity dataTypeName, @Nonnull Class<T> clazz,
121             boolean syncAfterWrite) throws ClassNotFoundException {
122         this(db, dataTypeName.getName(), clazz, null, syncAfterWrite);
123     }
124
125     public EsDataObjectReaderWriter2(DatabaseClient db, Entity dataTypeName, Class<T> clazz)
126             throws ClassNotFoundException {
127         this(db, dataTypeName.getName(), clazz, null, false);
128     }
129
130     /**
131      * Get Datatype name
132      *
133      * @return string with dataTypeName
134      */
135     public String getDataTypeName() {
136         return dataTypeName;
137     }
138
139     /**
140      * Simlar to {@link #setEsIdAttributeName()}, but adapts the parameter to yangtools attribute naming schema
141      *
142      * @param esIdAttributeName is converted to UnderscoreCamelCase
143      * @return this for further operations.
144      */
145     public EsDataObjectReaderWriter2<T> setEsIdAttributeNameCamelized(String esIdAttributeName) {
146         return setEsIdAttributeName(YangToolsMapperHelper.toCamelCaseAttributeName(esIdAttributeName));
147     }
148
149     /**
150      * Attribute name of class that is containing the object id
151      *
152      * @param esIdAttributeName of the implementation class for the yangtools interface. Expected attribute name format
153      *        is CamelCase with leading underline. @
154      * @return this for further operations.
155      * @throws SecurityException if no access or IllegalArgumentException if wrong type or no attribute with this name.
156      */
157     public EsDataObjectReaderWriter2<T> setEsIdAttributeName(String esIdAttributeName) {
158         LOG.debug("Set attribute '{}'", esIdAttributeName);
159         this.esIdAddAtributteName = null; // Reset status
160         this.field = null;
161
162         Field attributeField;
163         try {
164             Builder<? extends T> builder = yangtoolsMapper.getBuilder(clazz);
165             if (builder == null) {
166                 String msg = "No builder for " + clazz;
167                 LOG.debug(msg);
168                 throw new IllegalArgumentException(msg);
169             } else {
170                 T object = builder.build();
171                 attributeField = object.getClass().getDeclaredField(esIdAttributeName);
172                 if (attributeField.getType().equals(String.class)) {
173                     attributeField.setAccessible(true);
174                     this.esIdAddAtributteName = esIdAttributeName; // Set new status if everything OK
175                     this.field = attributeField;
176                 } else {
177                     String msg = "Wrong field type " + attributeField.getType().getName() + " of " + esIdAttributeName;
178                     LOG.debug(msg);
179                     throw new IllegalArgumentException(msg);
180                 }
181             }
182         } catch (NoSuchFieldException e) {
183             // Convert to run-time exception
184             String msg = "NoSuchFieldException for '" + esIdAttributeName + "' in class " + clazz.getName();
185             LOG.debug(msg);
186             throw new IllegalArgumentException(msg);
187         } catch (SecurityException e) {
188             LOG.debug("Access problem " + esIdAttributeName, e);
189             throw e;
190         }
191         return this;
192     }
193
194     /**
195      * Specify subclass of T for write operations.
196      *
197      * @param writeInterfaceClazz
198      */
199     public EsDataObjectReaderWriter2<T> setWriteInterface(@Nonnull Class<? extends DataObject> writeInterfaceClazz) {
200         LOG.debug("Set write interface to {}", writeInterfaceClazz);
201         if (writeInterfaceClazz == null) {
202             throw new IllegalArgumentException("Null not allowed here.");
203         }
204
205         this.writeInterfaceClazz = writeInterfaceClazz;
206         return this;
207     }
208
209     public interface IdGetter<S extends DataObject> {
210         String getId(S object);
211     }
212
213     public <S extends DataObject> void write(List<S> objectList, IdGetter<S> idGetter) {
214         for (S object : objectList) {
215             write(object, idGetter.getId(object));
216         }
217     }
218
219     /**
220      * Write child object to database with specific id
221      *
222      * @param object to be written
223      * @param esId use the id or if null generate unique id
224      * @return String with id or null
225      */
226     public @Nullable <S extends DataObject> String write(S object, @Nullable String esId) {
227         if (object != null && writeInterfaceClazz.isInstance(object)) {
228             try {
229                 String json = yangtoolsMapper.writeValueAsString(object);
230                 return db.doWriteRaw(dataTypeName, esId, json, this.syncAfterWrite);
231             } catch (JsonProcessingException e) {
232                 LOG.error("Write problem: ", e);
233             }
234         } else {
235             LOG.error("Type {} does not provide interface {}", object != null ? object.getClass().getName() : "null",
236                     writeInterfaceClazz.getName());
237         }
238         return null;
239     }
240
241     /**
242      * Update partial child object to database with match/term query
243      *
244      * @param <S> of object
245      * @param object to write
246      * @param query for write of specific attributes
247      * @return json string with new Object
248      */
249     public @Nullable <S extends DataObject> boolean update(S object, QueryBuilder query) {
250         if (object != null && writeInterfaceClazz.isInstance(object)) {
251             try {
252                 String json = yangtoolsMapper.writeValueAsString(object);
253                 return db.doUpdate(this.dataTypeName, json, query);
254             } catch (JsonProcessingException e) {
255                 LOG.error("Update problem: ", e);
256             }
257         } else {
258             LOG.error("Type {} does not provide interface {}", object != null ? object.getClass().getName() : "null",
259                     writeInterfaceClazz.getName());
260         }
261         return false;
262     }
263
264     /**
265      * Write/ update partial child object to database with specific id Write if not exists, else update
266      *
267      * @param object
268      * @param esId
269      * @return String with esId or null
270      */
271     public @Nullable <S extends DataObject> String update(S object, String esId) {
272         return this.updateOrCreate(object, esId, null);
273     }
274
275     /**
276      * See {@link doUpdateOrCreate(String dataTypeName, String esId, String json, List<String> doNotUpdateField) }
277      */
278     public @Nullable <S extends DataObject> String updateOrCreate(S object, String esId, List<String> onlyForInsert) {
279         if (object != null && writeInterfaceClazz.isInstance(object)) {
280             try {
281                 String json = yangtoolsMapper.writeValueAsString(object);
282                 return db.doUpdateOrCreate(dataTypeName, esId, json, onlyForInsert);
283             } catch (JsonProcessingException e) {
284                 LOG.error("Update problem: ", e);
285             }
286         } else {
287             LOG.error("Type {} does not provide interface {}", object != null ? object.getClass().getName() : "null",
288                     writeInterfaceClazz.getName());
289         }
290         return null;
291     }
292
293     /**
294      * Read object from database, by using the id field
295      *
296      * @param object
297      * @return
298      */
299     public @Nullable T read(String esId) {
300         @Nullable
301         T res = null;
302         if (esId != null) {
303             String json = db.doReadJsonData(dataTypeName, esId);
304             if (json != null) {
305                 try {
306                     res = yangtoolsMapper.readValue(json.getBytes(), clazz);
307                 } catch (IOException e) {
308                     LOG.error("Problem: ", e);
309                 }
310             } else {
311                 LOG.debug("Can not read from DB id {} type {}", esId, dataTypeName);
312             }
313         }
314         return res;
315     }
316
317     /**
318      * Remove object
319      *
320      * @param esId to identify the object.
321      * @return success
322      */
323     public boolean remove(String esId) {
324         return db.doRemove(this.dataTypeName, esId);
325     }
326
327     public int remove(QueryBuilder query) {
328         return this.db.doRemove(this.dataTypeName, query);
329     }
330
331     /**
332      * Get all elements of related type
333      *
334      * @return all Elements
335      */
336     public SearchResult<T> doReadAll() {
337         return doReadAll(null);
338     }
339
340     public SearchResult<T> doReadAll(QueryBuilder query) {
341         return this.doReadAll(query, false);
342     }
343
344     /**
345      * Read all existing objects of a type
346      *
347      * @param query for the elements
348      * @return the list of all objects
349      */
350
351     public SearchResult<T> doReadAll(QueryBuilder query, boolean ignoreException) {
352
353         SearchResult<T> res = new SearchResult<T>();
354
355         SearchResult<SearchHit> result;
356         List<SearchHit> hits;
357         if (query != null) {
358             LOG.debug("read data in {} with query {}", dataTypeName, query.toJSON());
359             result = db.doReadByQueryJsonData(dataTypeName, query, ignoreException);
360         } else {
361             result = db.doReadAllJsonData(dataTypeName, ignoreException);
362         }
363         hits = result.getHits();
364         LOG.debug("Read: {} elements: {}", dataTypeName, hits.size());
365
366         T object;
367         for (SearchHit hit : hits) {
368             object = getT(hit.getSourceAsString());
369             LOG.debug("Mapp Object: {}\nSource: '{}'\nResult: '{}'\n", hit.getId(),
370                     hit.getSourceAsString(), object);
371             if (object != null) {
372                 setEsId(object, hit.getId());
373                 res.add(object);
374             } else {
375                 LOG.warn("Mapp result null Object: {}\n Source: '{}'\n : '", hit.getId(), hit.getSourceAsString());
376             }
377         }
378         res.setTotal(result.getTotal());
379         return res;
380     }
381
382     /* ---------------------------------------------
383      * Private functions
384      */
385
386     private void setEsId(T object, String esId) {
387         if (field != null) {
388             try {
389                 field.set(object, esId);
390             } catch (IllegalArgumentException | IllegalAccessException e) {
391                 LOG.debug("Field set problem.", e);
392             }
393         }
394     }
395
396     private @Nullable T getT(String jsonString) {
397         try {
398             return yangtoolsMapper.readValue(jsonString, clazz);
399         } catch (IOException e) {
400             LOG.info("Mapping problem {}:", clazz.getName(), e);
401             return null;
402         }
403     }
404
405 }