2 * ============LICENSE_START=======================================================
3 * ONAP : ccsdk features
4 * ================================================================================
5 * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property.
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.ccsdk.features.sdnr.wt.dataprovider.database;
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.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.Entity;
37 import org.opendaylight.yangtools.concepts.Builder;
38 import org.opendaylight.yangtools.yang.binding.DataObject;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
43 * Class to rw yang-tool generated objects into elasticsearch database. For "ES _id" exchange the esIdAddAtributteName
44 * is used. This attribute mast be of type String and contains for read and write operations the object id. The function
45 * can be used without id handling. If id handling is required the parameter needs to be specified by class definition
46 * in yang and setting the name by using setAttributeName()
48 * Due to using Jackson base interfaces the org.eclipse.jdt.annotation.NonNull needs to be used here to get rid of
51 * @param <T> Yang tools generated class object.
53 public class EsDataObjectReaderWriter2<T extends DataObject> {
55 private final Logger LOG = LoggerFactory.getLogger(EsDataObjectReaderWriter2.class);
57 /** Typename for elastic search data schema **/
58 private String dataTypeName;
60 /** Elasticsearch Database client to be used **/
61 private DatabaseClient db;
63 /** Mapper with configuration to use opendaylight yang-tools builder pattern for object creation **/
64 private YangToolsMapper2<T> yangtoolsMapper;
66 /** Class of T as attribute to allow JSON to Class object mapping **/
67 private Class<T> clazz;
69 /** Field is used to write id. If null no id handling **/
70 private @Nullable Field field;
72 /** Attribute that is used as id field for the database object **/
73 private @Nullable String esIdAddAtributteName;
75 /** Interface to be used for write operations. Rule for write: T extends S and **/
76 private Class<? extends DataObject> writeInterfaceClazz; // == "S"
77 /** Flag true to sync this attribute during write always, what is slow and false do not sync */
78 private final boolean syncAfterWrite;
81 * Elasticsearch database read and write for specific class, defined by opendaylight yang-tools.
85 * @param db Database access client
86 * @param dataTypeName typename in database schema
87 * @param clazz class of type to be handled
88 * @param builderClazz class to build related object if builder pattern should be used.
89 * @param syncAfterWrite
90 * @throws ClassNotFoundException
92 public <X extends T, @NonNull B extends Builder<X>> EsDataObjectReaderWriter2(DatabaseClient db,
93 String dataTypeName, @Nonnull Class<T> clazz, @Nullable Class<B> builderClazz, boolean syncAfterWrite)
94 throws ClassNotFoundException {
95 LOG.info("Create {} for datatype {} class {}", this.getClass().getName(), dataTypeName, clazz.getName());
97 this.esIdAddAtributteName = null;
99 this.writeInterfaceClazz = clazz;
101 this.dataTypeName = dataTypeName;
102 this.yangtoolsMapper = new YangToolsMapper2<>(clazz, builderClazz);
104 this.syncAfterWrite = syncAfterWrite;
107 public <X extends T, @NonNull B extends Builder<X>> EsDataObjectReaderWriter2(DatabaseClient db,
108 Entity dataTypeName, @Nonnull Class<T> clazz, @Nullable Class<B> builderClazz)
109 throws ClassNotFoundException {
110 this(db, dataTypeName.getName(), clazz, builderClazz, false);
113 public <X extends T, @NonNull B extends Builder<X>> EsDataObjectReaderWriter2(DatabaseClient db,
114 Entity dataTypeName, @Nonnull Class<T> clazz, @Nullable Class<B> builderClazz, boolean syncAfterWrite)
115 throws ClassNotFoundException {
116 this(db, dataTypeName.getName(), clazz, builderClazz, syncAfterWrite);
119 public EsDataObjectReaderWriter2(DatabaseClient db, Entity dataTypeName, @Nonnull Class<T> clazz,
120 boolean syncAfterWrite) throws ClassNotFoundException {
121 this(db, dataTypeName.getName(), clazz, null, syncAfterWrite);
124 public EsDataObjectReaderWriter2(DatabaseClient db, Entity dataTypeName, Class<T> clazz)
125 throws ClassNotFoundException {
126 this(db, dataTypeName.getName(), clazz, null, false);
132 * @return string with dataTypeName
134 public String getDataTypeName() {
139 * Simlar to {@link #setEsIdAttributeName()}, but adapts the parameter to yangtools attribute naming schema
141 * @param esIdAttributeName is converted to UnderscoreCamelCase
142 * @return this for further operations.
144 public EsDataObjectReaderWriter2<T> setEsIdAttributeNameCamelized(String esIdAttributeName) {
145 return setEsIdAttributeName(YangToolsMapper2.toCamelCaseAttributeName(esIdAttributeName));
149 * Attribute name of class that is containing the object id
151 * @param esIdAttributeName of the implementation class for the yangtools interface. Expected attribute name format
152 * is CamelCase with leading underline. @
153 * @return this for further operations.
154 * @throws SecurityException if no access or IllegalArgumentException if wrong type or no attribute with this name.
156 public EsDataObjectReaderWriter2<T> setEsIdAttributeName(String esIdAttributeName) {
157 LOG.debug("Set attribute '{}'", esIdAttributeName);
158 this.esIdAddAtributteName = null; // Reset status
161 Field attributeField;
163 Builder<? extends T> builder = yangtoolsMapper.getBuilder(clazz);
164 if (builder == null) {
165 String msg = "No builder for " + clazz;
167 throw new IllegalArgumentException(msg);
169 T object = builder.build();
170 attributeField = object.getClass().getDeclaredField(esIdAttributeName);
171 if (attributeField.getType().equals(String.class)) {
172 attributeField.setAccessible(true);
173 this.esIdAddAtributteName = esIdAttributeName; // Set new status if everything OK
174 this.field = attributeField;
176 String msg = "Wrong field type " + attributeField.getType().getName() + " of " + esIdAttributeName;
178 throw new IllegalArgumentException(msg);
181 } catch (NoSuchFieldException e) {
182 // Convert to run-time exception
183 String msg = "NoSuchFieldException for '" + esIdAttributeName + "' in class " + clazz.getName();
185 throw new IllegalArgumentException(msg);
186 } catch (SecurityException e) {
187 LOG.debug("Access problem " + esIdAttributeName, e);
194 * Specify subclass of T for write operations.
196 * @param writeInterfaceClazz
198 public EsDataObjectReaderWriter2<T> setWriteInterface(@Nonnull Class<? extends DataObject> writeInterfaceClazz) {
199 LOG.debug("Set write interface to {}", writeInterfaceClazz);
200 if (writeInterfaceClazz == null) {
201 throw new IllegalArgumentException("Null not allowed here.");
204 this.writeInterfaceClazz = writeInterfaceClazz;
208 public interface IdGetter<S extends DataObject> {
209 String getId(S object);
212 public <S extends DataObject> void write(List<S> objectList, IdGetter<S> idGetter) {
213 for (S object : objectList) {
214 write(object, idGetter.getId(object));
219 * Write child object to database with specific id
221 * @param object to be written
222 * @param esId use the id or if null generate unique id
223 * @return String with id or null
225 public @Nullable <S extends DataObject> String write(S object, @Nullable String esId) {
226 if (object != null && writeInterfaceClazz.isInstance(object)) {
228 String json = yangtoolsMapper.writeValueAsString(object);
229 return db.doWriteRaw(dataTypeName, esId, json, this.syncAfterWrite);
230 } catch (JsonProcessingException e) {
231 LOG.error("Write problem: ", e);
234 LOG.error("Type {} does not provide interface {}", object != null ? object.getClass().getName() : "null",
235 writeInterfaceClazz.getName());
241 * Update partial child object to database with match/term query
243 * @param <S> of object
244 * @param object to write
245 * @param query for write of specific attributes
246 * @return json string with new Object
248 public @Nullable <S extends DataObject> boolean update(S object, QueryBuilder query) {
249 if (object != null && writeInterfaceClazz.isInstance(object)) {
251 String json = yangtoolsMapper.writeValueAsString(object);
252 return db.doUpdate(this.dataTypeName, json, query);
253 } catch (JsonProcessingException e) {
254 LOG.error("Update problem: ", e);
257 LOG.error("Type {} does not provide interface {}", object != null ? object.getClass().getName() : "null",
258 writeInterfaceClazz.getName());
264 * Write/ update partial child object to database with specific id Write if not exists, else update
268 * @return String with esId or null
270 public @Nullable <S extends DataObject> String update(S object, String esId) {
271 return this.updateOrCreate(object, esId, null);
275 * See {@link doUpdateOrCreate(String dataTypeName, String esId, String json, List<String> doNotUpdateField) }
277 public @Nullable <S extends DataObject> String updateOrCreate(S object, String esId, List<String> onlyForInsert) {
278 if (object != null && writeInterfaceClazz.isInstance(object)) {
280 String json = yangtoolsMapper.writeValueAsString(object);
281 return db.doUpdateOrCreate(dataTypeName, esId, json, onlyForInsert);
282 } catch (JsonProcessingException e) {
283 LOG.error("Update problem: ", e);
286 LOG.error("Type {} does not provide interface {}", object != null ? object.getClass().getName() : "null",
287 writeInterfaceClazz.getName());
293 * Read object from database, by using the id field
298 public @Nullable T read(String esId) {
302 String json = db.doReadJsonData(dataTypeName, esId);
305 res = yangtoolsMapper.readValue(json.getBytes(), clazz);
306 } catch (IOException e) {
307 LOG.error("Problem: ", e);
310 LOG.debug("Can not read from DB id {} type {}", esId, dataTypeName);
319 * @param esId to identify the object.
322 public boolean remove(String esId) {
323 return db.doRemove(this.dataTypeName, esId);
326 public int remove(QueryBuilder query) {
327 return this.db.doRemove(this.dataTypeName, query);
331 * Get all elements of related type
333 * @return all Elements
335 public SearchResult<T> doReadAll() {
336 return doReadAll(null);
339 public SearchResult<T> doReadAll(QueryBuilder query) {
340 return this.doReadAll(query, false);
344 * Read all existing objects of a type
346 * @param query for the elements
347 * @return the list of all objects
350 public SearchResult<T> doReadAll(QueryBuilder query, boolean ignoreException) {
352 SearchResult<T> res = new SearchResult<T>();
354 SearchResult<SearchHit> result;
355 List<SearchHit> hits;
357 LOG.debug("read data in {} with query {}", dataTypeName, query.toJSON());
358 result = db.doReadByQueryJsonData(dataTypeName, query, ignoreException);
360 result = db.doReadAllJsonData(dataTypeName, ignoreException);
362 hits = result.getHits();
363 LOG.debug("Read: {} elements: {} Failures: {}", dataTypeName, hits.size(),
364 yangtoolsMapper.getMappingFailures());
367 for (SearchHit hit : hits) {
368 object = getT(hit.getSourceAsString());
369 LOG.debug("Mapp Object: {}\nSource: '{}'\nResult: '{}'\n Failures: {}", hit.getId(),
370 hit.getSourceAsString(), object, yangtoolsMapper.getMappingFailures());
371 if (object != null) {
372 setEsId(object, hit.getId());
375 LOG.warn("Mapp result null Object: {}\n Source: '{}'\n : '", hit.getId(), hit.getSourceAsString());
378 res.setTotal(result.getTotal());
382 /* ---------------------------------------------
386 private void setEsId(T object, String esId) {
389 field.set(object, esId);
390 } catch (IllegalArgumentException | IllegalAccessException e) {
391 LOG.debug("Field set problem.", e);
396 private @Nullable T getT(String jsonString) {
398 return yangtoolsMapper.readValue(jsonString, clazz);
399 } catch (IOException e) {
400 LOG.info("Mapping problem", e);