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
10 * http://www.apache.org/licenses/LICENSE-2.0
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
16 * ============LICENSE_END==========================================================================
17 ******************************************************************************/
18 package org.onap.ccsdk.features.sdnr.wt.devicemanager.base.database;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.List;
24 import javax.annotation.Nullable;
26 import org.elasticsearch.index.query.QueryBuilder;
27 import org.elasticsearch.search.SearchHit;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
32 * Generic class to write lists of model classes to the database.
35 public class HtDataBaseReaderAndWriter<T extends IsEsObject> {
37 private static final Logger log = LoggerFactory.getLogger(HtDataBaseReaderAndWriter.class);
40 private final HtDataBase db;
41 private final String dataTypeName;
42 private final HtMapper<T> mapper;
45 * Class specific access to database
46 * @param db ES database descriptor
47 * @param dataTypeName datatype name
48 * @param clazz class of datatype
50 public HtDataBaseReaderAndWriter(HtDataBase db, String dataTypeName, Class<? extends T> clazz) {
53 this.dataTypeName = dataTypeName;
54 this.mapper = new HtMapper<>( clazz );
58 * @return dataTypeName
60 public String getDataTypeName() {
61 return this.dataTypeName;
64 * Remove Object from database
65 * @param object Object with content
66 * @return true if remove is done
68 public boolean doRemove( T object) {
70 return db.doRemove(dataTypeName, object );
75 * Remove all data that match the filter
76 * @param query to specify data to be deleted
77 * @return number of removed objects
79 public int doRemoveByQuery(QueryBuilder query) {
81 int idx = 0; //Idx for getAll
82 int iterateLength = 100; //Step width for iterate
86 hits = db.doReadByQueryJsonData(idx, iterateLength, dataTypeName, query);
87 log.debug("Found: {} elements: {} Failures: {}",dataTypeName,hits.length, mapper.getMappingFailures());
91 for (SearchHit hit : hits) {
93 object = mapper.getObjectFromJson( hit.getSourceRef() );
95 log.debug("Mapp Object: {}\nSource: '{}'\nResult: '{}'\n Failures: {}", hit.getId(), hit.getSourceAsString(), object, mapper.getMappingFailures());
97 object.setEsId( hit.getId() );
100 log.warn("Mapp result null Object: {}\n Source: '{}'\n : '", hit.getId(), hit.getSourceAsString());
103 } while (hits.length == iterateLength); //Do it until end indicated, because less hits than iterateLength allows.
109 * Do the mapping for test purpose
110 * @param object object for test purpose
111 * @return json String
113 public String getJson( T object ) {
114 String json = mapper.objectToJson(object);
119 * Write one object into Database
120 * @param object Object with content
121 * @return This object for chained call pattern.
123 public T doWrite( T object) {
125 String json = mapper.objectToJson(object);
126 return doWrite(object, json);
131 * Write one object into Database
132 * @param object Object with content
134 * @return This object for chained call pattern.
136 public T doWrite( T object, String json) {
138 log.debug("doWrite {} {}",object.getClass().getSimpleName(), object.getEsId());
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;
146 log.warn("Can not map object and write to database. {} {}",object.getClass().getSimpleName(), object);
154 * Write a list of Objects to the database.
155 * @param list Object list with content
156 * @return This object for chained call pattern.
158 public HtDataBaseReaderAndWriter<T> doWrite( Collection<T> list) {
161 String indexName = db.getNetworkIndex();
163 log.debug("Write to ES database {}, {} Class: {} {} elements",indexName,dataTypeName, mapper.getClazz().getSimpleName(), list.size());
165 if (indexName == null) {
166 throw new IllegalArgumentException("Missing Index");
169 if (list != null && !list.isEmpty()) {
171 if ( doWrite(s) == null ) {
172 if ( ++writeError > 5 ) {
173 log.warn("Leave because of to >5 write errors");
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
189 public @Nullable T doRead( IsEsObject object ) {
190 T res = mapper.getObjectFromJson( db.doReadJsonData( dataTypeName, object) );
192 res.setEsId(object.getEsId());
198 * Read one object via the object class specific ID
199 * @param objectEsId Object refrence
200 * @return The Object if found or null
202 public @Nullable T doRead( String objectEsId ) {
203 T res = mapper.getObjectFromJson( db.doReadJsonData( dataTypeName, objectEsId ) );
205 res.setEsId(objectEsId);
210 * Get all elements of related type
211 * @return all Elements
213 public List<T> doReadAll() {
214 return doReadAll(null);
217 * Read all existing objects of a type
218 * @param query for the elements
219 * @return the list of all objects
221 public List<T> doReadAll(QueryBuilder query) {
223 List<T> res = new ArrayList<>();
224 int idx = 0; //Idx for getAll
225 int iterateLength = 100; //Step width for iterate
230 log.trace("read data in {} {} with query {}",db.getNetworkIndex(),dataTypeName,query);
231 hits=db.doReadByQueryJsonData(0, 99999, dataTypeName, query);
234 hits = db.doReadAllJsonData(idx, iterateLength, dataTypeName);
236 log.debug("Read: {} elements: {} Failures: {}",dataTypeName,hits.length, mapper.getMappingFailures());
240 for (SearchHit hit : hits) {
242 object = mapper.getObjectFromJson( hit.getSourceRef() );
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() );
249 log.warn("Mapp result null Object: {}\n Source: '{}'\n : '", hit.getId(), hit.getSourceAsString());
252 } while (hits.length == iterateLength); //Do it until end indicated, because less hits than iterateLength allows.