Assign image keyname and pubkey at vnf level
[ccsdk/apps.git] / sdnr / wireless-transport / code-Carbon-SR1 / apps / devicemanager / impl / src / main / java / org / opendaylight / mwtn / base / database / HtDataBaseReaderAndWriter.java
1 /*********************************************************************************
2  *  Copyright © 2015, highstreet technologies GmbH
3  *  All rights reserved!
4  *
5  *  http://www.highstreet-technologies.com/
6  *
7  *  The reproduction, transmission or use of this document or its contents is not
8  *  permitted without express written authority. Offenders will be liable for
9  *  damages. All rights, including rights created by patent grant or registration
10  *  of a utility model or design, are reserved. Technical modifications possible.
11  *  Technical specifications and features are binding only insofar as they are
12  *  specifically and expressly agreed upon in a written contract.
13  *
14  *  @author: Martin Skorupski [martin@skorupski.de]
15  *********************************************************************************/
16 package org.opendaylight.mwtn.base.database;
17
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.List;
21
22 import org.elasticsearch.index.query.QueryBuilder;
23 import org.elasticsearch.search.SearchHit;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 /**
28  * Generic class to write lists of model classes to the database.
29  *
30  */
31 public class HtDataBaseReaderAndWriter<T extends IsEsObject> {
32
33     private static final Logger log = LoggerFactory.getLogger(HtDataBaseReaderAndWriter.class);
34
35
36     private final HtDataBase db;
37     private final String dataTypeName;
38     private final HtMapper<T> mapper;
39
40     /**
41      * Class specific access to database
42      * @param db ES database descriptor
43      * @param dataTypeName datatype name
44      * @param clazz class of datatype
45      */
46     public HtDataBaseReaderAndWriter(HtDataBase db, String dataTypeName, Class<? extends T> clazz) {
47
48         this.db = db;
49         this.dataTypeName = dataTypeName;
50         this.mapper = new HtMapper<>( clazz );
51
52     }
53
54     /**
55      * Remove Object from database
56      * @param object Object with content
57      * @return true if remove is done
58      */
59     public boolean doRemove( T object) {
60
61         return db.doRemove(dataTypeName, object );
62
63     }
64
65     /**
66      * Remove all data that match the filter
67      * @param query to specify data to be deleted
68      * @return number of removed objects
69      */
70     public int doRemoveByQuery(QueryBuilder query) {
71
72         int idx = 0;                //Idx for getAll
73         int iterateLength = 100;    //Step width for iterate
74
75         SearchHit hits[];
76         do {
77             hits = db.doReadByQueryJsonData(idx, iterateLength, dataTypeName, query);
78             log.debug("Found: {} elements: {}  Failures: {}",dataTypeName,hits.length, mapper.getMappingFailures());
79
80             T object;
81             idx += hits.length;
82             for (SearchHit hit : hits) {
83
84                 object = mapper.getObjectFromJson( hit.getSourceRef() );
85
86                 log.debug("Mapp Object: {}\nSource: '{}'\nResult: '{}'\n Failures: {}", hit.getId(), hit.getSourceAsString(), object, mapper.getMappingFailures());
87                 if (object != null) {
88                     object.setEsId( hit.getId() );
89                     doRemove(object);
90                 } else {
91                     log.warn("Mapp result null Object: {}\n Source: '{}'\n : '", hit.getId(), hit.getSourceAsString());
92                 }
93             }
94         } while (hits.length == iterateLength); //Do it until end indicated, because less hits than iterateLength allows.
95
96         return idx;
97     }
98
99
100
101     /**
102      * Write one object into Database
103      * @param object Object with content
104      * @return This object for chained call pattern.
105      */
106     public T doWrite( T object) {
107
108         log.debug("doWrite {} {}",object.getClass().getSimpleName(), object.getEsId());
109
110         String json = mapper.objectToJson(object);
111         if (json != null) {
112             String esId = db.doWrite(dataTypeName, object, json);
113             object.setEsId(esId);
114             log.debug("doWrite done for {} {}",object.getClass().getSimpleName(), object.getEsId());
115             return esId == null ? null : object;
116         } else {
117             log.warn("Can not map object and write to database. {}",object.getClass().getSimpleName());
118             return null;
119         }
120
121     }
122
123     /**
124      * Write a list of Objects to the database.
125      * @param list Object list with content
126      * @return This object for chained call pattern.
127      */
128     public HtDataBaseReaderAndWriter<T> doWrite( Collection<T> list) {
129
130         int writeError = 0;
131         String indexName = db.getNetworkIndex();
132
133         log.debug("Write to ES database {}, {} Class: {}  {} elements",indexName,dataTypeName, mapper.getClazz().getSimpleName(), list.size());
134
135         if (indexName == null) {
136             throw new IllegalArgumentException("Missing Index");
137         }
138
139         if (list != null && !list.isEmpty()) {
140             for( T s : list ) {
141                 if ( doWrite(s) == null )  {
142                     if ( ++writeError > 5 ) {
143                         log.warn("Leave because of to >5 write errors");
144                         break;
145                     }
146                 }
147             }
148
149         }
150
151         return this;
152     }
153
154     /**
155      * Read one object via the object class specific ID
156      * @param object Object refrenced by idString
157      * @return The Object if found or null
158      */
159     public T doRead( IsEsObject object ) {
160         return mapper.getObjectFromJson( db.doReadJsonData( dataTypeName, object) );
161     }
162
163     /**
164      * Read all existing objects of a type
165      * @return the list of all objects
166      */
167     public List<T> doReadAll() {
168
169         List<T> res = new ArrayList<>();
170         int idx = 0;                //Idx for getAll
171         int iterateLength = 100;    //Step width for iterate
172
173         SearchHit hits[];
174
175
176         do {
177             hits = db.doReadAllJsonData(idx, iterateLength, dataTypeName);
178             log.debug("Read: {} elements: {}  Failures: {}",dataTypeName,hits.length, mapper.getMappingFailures());
179
180             T object;
181             idx += hits.length;
182             for (SearchHit hit : hits) {
183
184                 object = mapper.getObjectFromJson( hit.getSourceRef() );
185
186                 log.debug("Mapp Object: {}\nSource: '{}'\nResult: '{}'\n Failures: {}", hit.getId(), hit.getSourceAsString(), object, mapper.getMappingFailures());
187                 if (object != null) {
188                     object.setEsId( hit.getId() );
189                     res.add( object );
190                 } else {
191                     log.warn("Mapp result null Object: {}\n Source: '{}'\n : '", hit.getId(), hit.getSourceAsString());
192                 }
193             }
194         } while (hits.length == iterateLength); //Do it until end indicated, because less hits than iterateLength allows.
195
196         return res;
197     }
198
199 }