9798d12f8803623f18393eb1c2dd6ed83b2be012
[ccsdk/features.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : ccsdk features
4  * ================================================================================
5  * Copyright (C) 2023 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.sqldb.database;
23
24 import com.fasterxml.jackson.core.JsonProcessingException;
25 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.SqlDBClient;
26 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.data.PropertyList;
27 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.data.rpctypehelper.QueryResult;
28 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.query.SelectQuery;
29 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.query.SqlQuery;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.Entity;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.EntityInput;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.Filter;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.FilterBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.FilterKey;
35 import org.opendaylight.yangtools.yang.binding.DataObject;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 import java.lang.reflect.InvocationTargetException;
40 import java.sql.ResultSet;
41 import java.sql.SQLException;
42 import java.util.ArrayList;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.Optional;
46
47 public class SqlDBReader<T extends DataObject> {
48     private static final Logger LOG = LoggerFactory.getLogger(SqlDBReader.class);
49
50     protected final Entity entity;
51     private final Class<T> clazz;
52     protected final SqlDBClient dbService;
53     protected final String controllerId;
54     protected final String tableName;
55     protected final boolean ignoreControllerId;
56     protected final PropertyList propertyList;
57     public SqlDBReader(SqlDBClient dbService, Entity e, String dbSuffix, Class<T> clazz,
58                        String controllerId) {
59         this(dbService, e, dbSuffix, clazz, controllerId, false);
60     }
61
62     public SqlDBReader(SqlDBClient dbService, Entity e, String dbSuffix, Class<T> clazz,
63                        String controllerId, boolean ignoreControllerId) {
64         this.dbService = dbService;
65         this.entity = e;
66         this.clazz = clazz;
67         this.tableName = this.entity.getName() + dbSuffix;
68         this.controllerId = controllerId;
69         this.ignoreControllerId = ignoreControllerId;
70         this.propertyList = new PropertyList(clazz);
71     }
72
73     public long count(List<Filter> filter) throws SQLException {
74         String query;
75         if (filter == null || filter.isEmpty()) {
76             //            query = String.format("SELECT table_rows FROM `information_schema`.`tables` "
77             //                    + "WHERE `table_schema` = '%s' AND `table_name` = '%s'", this.dbName, this.tableName);
78             query = String.format("SELECT COUNT(`id`) FROM `%s`", this.tableName);
79         } else {
80             query = String.format("SELECT COUNT(`id`) FROM `%s` %s", this.tableName,
81                     SqlQuery.getWhereExpression(filter));
82         }
83         ResultSet data = this.dbService.read(query);
84         if (data == null) {
85             return 0;
86         }
87         long cnt = 0;
88         if (data.next()) {
89             cnt = data.getLong(1);
90         }
91         try {
92             data.close();
93         } catch (SQLException ignore) {
94         }
95         return cnt;
96     }
97
98     public long count(List<Filter> list, String controllerId) throws SQLException {
99         if (list == null) {
100             list = new ArrayList<>();
101         }
102         Optional<Filter> cFilter =
103                 list.stream().filter(e -> SqlDBMapper.ODLID_DBCOL.equals(e.getProperty())).findFirst();
104         if (!cFilter.isEmpty()) {
105             list.remove(cFilter.get());
106         }
107         if (controllerId != null) {
108             list.add(
109                     new FilterBuilder().setProperty(SqlDBMapper.ODLID_DBCOL).setFiltervalue(this.controllerId).build());
110         }
111         return this.count(list);
112     }
113
114     public QueryResult<T> getData(EntityInput input) {
115         SelectQuery query = new SelectQuery(this.tableName, input, this.controllerId);
116         if (LOG.isTraceEnabled()) {
117             LOG.trace("query={}", query.toSql());
118         }
119         try {
120             ResultSet data = this.dbService.read(query.toSql());
121             List<T> mappedData = SqlDBMapper.read(data, clazz);
122             final Map<FilterKey, Filter> filter = input.getFilter();
123             try {
124                 if (data != null) {
125                     data.close();
126                 }
127             } catch (SQLException ignore) {
128             }
129             long total = this.count(filter != null ? new ArrayList<>(filter.values()) : null, this.controllerId);
130             return new QueryResult<T>(mappedData, query.getPage(), query.getPageSize(), total);
131         } catch (SQLException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
132                  | InstantiationException | SecurityException | NoSuchMethodException | JsonProcessingException e) {
133             LOG.warn("problem reading data {}: ", this.entity, e);
134         }
135         return QueryResult.createEmpty();
136     }
137
138     public <S extends DataObject> List<S> readAll(Class<S> clazz) {
139         SelectQuery query = new SelectQuery(this.tableName, this.controllerId);
140         if (LOG.isTraceEnabled()) {
141             LOG.trace("query={}", query.toSql());
142         }
143         return this.readAll(clazz, query);
144     }
145
146     public <S extends DataObject> List<S> readAll(Class<S> clazz, EntityInput input) {
147         SelectQuery query = new SelectQuery(this.tableName, input, this.controllerId);
148         return this.readAll(clazz, query);
149     }
150     public  <S extends DataObject> List<S> searchAll(Class<S> clazz, EntityInput input, String searchTerm) {
151         SelectQuery query = new SelectQuery(this.tableName, input, this.controllerId);
152         if(searchTerm!=null && !searchTerm.isEmpty()) {
153             query.setAllPropertyFilter(searchTerm, this.propertyList);
154         }
155         return this.readAll(clazz, query);
156     }
157     public <S extends DataObject> List<S> readAll(Class<S> clazz, SelectQuery query) {
158         try {
159             ResultSet data = this.dbService.read(query.toSql());
160             List<S> mappedData = SqlDBMapper.read(data, clazz);
161             try {
162                 data.close();
163             } catch (SQLException ignore) {
164             }
165             return mappedData;
166         } catch (SQLException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
167                  | InstantiationException | SecurityException | NoSuchMethodException | JsonProcessingException e) {
168             LOG.warn("problem reading all data{}: ", this.entity, e);
169         }
170         return null;
171     }
172
173     public List<String> readAll(String key) {
174         SelectQuery query = new SelectQuery(this.tableName, key, this.controllerId).groupBy(key);
175         if (LOG.isTraceEnabled()) {
176             LOG.trace("query={}", query.toSql());
177         }
178         try {
179             ResultSet data = this.dbService.read(query.toSql());
180             List<String> mappedData = SqlDBMapper.read(data, String.class, key);
181             try {
182                 data.close();
183             } catch (SQLException ignore) {
184             }
185             return mappedData;
186         } catch (SQLException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
187                  | InstantiationException | SecurityException | NoSuchMethodException | JsonProcessingException e) {
188             LOG.warn("problem reading all data {} for key: ", this.entity, key, e);
189         }
190         return null;
191     }
192
193     public T read(String id) {
194         SelectQuery query =
195                 new SelectQuery(this.tableName, this.controllerId).addFilter(SqlDBMapper.ID_DBCOL, id);
196         if (LOG.isTraceEnabled()) {
197             LOG.trace("query={}", query.toSql());
198         }
199         T item = null;
200         try {
201             ResultSet data = this.dbService.read(query.toSql());
202             List<T> mappedData = SqlDBMapper.read(data, clazz);
203             item = mappedData.size() > 0 ? mappedData.get(0) : null;
204         } catch (SQLException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
205                  | InstantiationException | SecurityException | NoSuchMethodException | JsonProcessingException e) {
206             LOG.warn("problem reading data {}: ", this.entity, e);
207         }
208         return item;
209     }
210 }