d033e45f71d5a1f90f4b9df9bb32a6b7adf8ec81
[ccsdk/features.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : ccsdk features
4  * ================================================================================
5  * Copyright (C) 2021 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 java.lang.reflect.InvocationTargetException;
26 import java.sql.Connection;
27 import java.sql.PreparedStatement;
28 import java.sql.ResultSet;
29 import java.sql.SQLException;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.List;
33 import java.util.Optional;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.SqlDBClient;
36 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.data.rpctypehelper.QueryResult;
37 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.query.DeleteQuery;
38 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.query.InsertQuery;
39 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.query.SelectQuery;
40 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.query.SqlQuery;
41 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.query.UpdateQuery;
42 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.query.UpsertQuery;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.Entity;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.EntityInput;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.Filter;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.entity.input.FilterBuilder;
47 import org.opendaylight.yangtools.yang.binding.DataObject;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 public class SqlDBReaderWriter<T extends DataObject> {
52
53     private static final Logger LOG = LoggerFactory.getLogger(SqlDBReaderWriter.class);
54
55     protected final Entity entity;
56     private final Class<T> clazz;
57     protected final SqlDBClient dbService;
58     private final String dbName;
59     protected final String controllerId;
60     protected final String tableName;
61
62     public SqlDBReaderWriter(SqlDBClient dbService, Entity e, String dbSuffix, Class<T> clazz, String dbName,
63             String controllerId) {
64         this.dbService = dbService;
65         this.entity = e;
66         this.clazz = clazz;
67         this.dbName = dbName;
68         this.tableName = this.entity.getName() + dbSuffix;
69         this.controllerId = controllerId;
70     }
71
72     public long count(List<Filter> filter) throws SQLException {
73         String query;
74         if (filter == null || filter.isEmpty()) {
75             query = String.format("SELECT table_rows FROM `information_schema`.`tables` "
76                     + "WHERE `table_schema` = '%s' AND `table_name` = '%s'", this.dbName, this.tableName);
77         } else {
78             query = String.format("SELECT COUNT(`id`) FROM `%s` %s", this.tableName,
79                     SqlQuery.getWhereExpression(filter));
80         }
81         ResultSet data = this.dbService.read(query);
82         long cnt = 0;
83         if (data.next()) {
84             cnt = data.getLong(1);
85         }
86         return cnt;
87     }
88
89     public long count(List<Filter> list, String controllerId) throws SQLException {
90         if (list == null) {
91             list = new ArrayList<>();
92         }
93         Optional<Filter> cFilter =
94                 list.stream().filter(e -> SqlDBMapper.ODLID_DBCOL.equals(e.getProperty())).findFirst();
95         if (!cFilter.isEmpty()) {
96             list.remove(cFilter.get());
97         }
98         if (controllerId != null) {
99             list.add(new FilterBuilder().setProperty(SqlDBMapper.ODLID_DBCOL).setFiltervalue(this.controllerId)
100                     .build());
101         }
102         return this.count(list);
103     }
104
105     public QueryResult<T> getData(EntityInput input) {
106         SelectQuery query = new SelectQuery(this.tableName, input, this.controllerId);
107         LOG.info("query={}", query.toSql());
108         try {
109             ResultSet data = this.dbService.read(query.toSql());
110             List<T> mappedData = SqlDBMapper.read(data, clazz);
111             long total = this.count(input.getFilter() != null ? new ArrayList<>(input.getFilter().values()) : null,
112                     this.controllerId);
113             return new QueryResult<T>(mappedData, query.getPage(), query.getPageSize(), total);
114         } catch (SQLException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
115                 | InstantiationException | SecurityException | NoSuchMethodException | JsonProcessingException e) {
116             LOG.warn("problem reading data {}: ", this.entity, e);
117         }
118         return null;
119     }
120
121
122
123     public <S extends DataObject> String write(S object, String id) {
124         if (id == null) {
125             return this.writeWithoutId(object);
126         }
127         InsertQuery<S> query = new InsertQuery<S>(this.entity, object, this.controllerId);
128         query.setId(id);
129         boolean success = false;
130         try {
131             success = this.dbService.write(query.toSql());
132         } catch (SQLException e) {
133             LOG.warn("problem writing data into db: ", e);
134         }
135
136         return success ? id : null;
137     }
138
139     private <S extends DataObject> String writeWithoutId(S object) {
140
141         InsertQuery<S> query = new InsertQuery<S>(this.entity, object, this.controllerId);
142         try {
143             return this.dbService.writeAndReturnId(query.toSql());
144         } catch (SQLException e) {
145             LOG.warn("problem writing data into db: ", e);
146         }
147         return null;
148     }
149
150     public <S extends DataObject> String update(S object, String id) {
151         UpdateQuery<S> query = new UpdateQuery<S>(this.entity, object, this.controllerId);
152         query.setId(id);
153         String insertedId = null;
154         try {
155             Connection connection = this.dbService.getConnection();
156             PreparedStatement stmt = connection.prepareStatement(query.toSql());
157             stmt.execute();
158
159             int affectedRows = stmt.getUpdateCount();
160             connection.close();
161             if (affectedRows > 0) {
162                 insertedId = id;
163             }
164         } catch (SQLException e) {
165             LOG.warn("problem writing data into db: ", e);
166         }
167
168         return insertedId;
169     }
170
171     public <S extends DataObject> String updateOrInsert(S object, String id) {
172         UpsertQuery<S> query = new UpsertQuery<S>(this.entity, object, this.controllerId);
173         query.setId(id);
174         String insertedId = null;
175         LOG.info("query={}", query.toSql());
176         try {
177             Connection connection = this.dbService.getConnection();
178             PreparedStatement stmt = connection.prepareStatement(query.toSql());
179             stmt.execute();
180
181             int affectedRows = stmt.getUpdateCount();
182             connection.close();
183             if (affectedRows > 0) {
184                 insertedId = id;
185             }
186         } catch (SQLException e) {
187             LOG.warn("problem writing data into db: ", e);
188         }
189         return insertedId;
190     }
191
192     public SqlDBReaderWriter<T> setWriteInterface(Class<? extends DataObject> writeInterfaceClazz) {
193         LOG.debug("Set write interface to {}", writeInterfaceClazz);
194         if (writeInterfaceClazz == null) {
195             throw new IllegalArgumentException("Null not allowed here.");
196         }
197
198         //      this.writeInterfaceClazz = writeInterfaceClazz;
199         return this;
200     }
201
202     public int remove(List<Filter> filters) {
203         DeleteQuery query = new DeleteQuery(this.entity, filters);
204         int affectedRows = 0;
205         try {
206             Connection connection = this.dbService.getConnection();
207             PreparedStatement stmt = connection.prepareStatement(query.toSql());
208             stmt.execute();
209             affectedRows = stmt.getUpdateCount();
210             connection.close();
211         } catch (SQLException e) {
212             LOG.warn("problem execute delete query: ", e);
213         }
214         return affectedRows;
215     }
216
217     public int remove(@Nullable String id) {
218         return this.remove(Arrays.asList(new FilterBuilder().setProperty("id").setFiltervalue(id).build()));
219     }
220
221     public <S extends DataObject> List<S> readAll(Class<S> clazz) {
222         SelectQuery query = new SelectQuery(this.tableName);
223         try {
224             ResultSet data = this.dbService.read(query.toSql());
225             List<S> mappedData = SqlDBMapper.read(data, clazz);
226             return mappedData;
227         } catch (SQLException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
228                 | InstantiationException | SecurityException | NoSuchMethodException | JsonProcessingException e) {
229             LOG.warn("problem reading data {}: ", this.entity, e);
230         }
231         return null;
232     }
233
234     public List<String> readAll(String key) {
235         SelectQuery query = new SelectQuery(this.tableName, key, this.controllerId).groupBy(key);
236         try {
237             ResultSet data = this.dbService.read(query.toSql());
238             List<String> mappedData = SqlDBMapper.read(data, String.class, key);
239             return mappedData;
240         } catch (SQLException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
241                 | InstantiationException | SecurityException | NoSuchMethodException | JsonProcessingException e) {
242             LOG.warn("problem reading data {}: ", this.entity, e);
243         }
244         return null;
245     }
246 }