forked from openhab/openhab-addons
-
Notifications
You must be signed in to change notification settings - Fork 1
/
JdbcConfiguration.java
419 lines (356 loc) · 15.8 KB
/
JdbcConfiguration.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/**
* Copyright (c) 2010-2022 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.persistence.jdbc.internal;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.persistence.jdbc.db.JdbcBaseDAO;
import org.openhab.persistence.jdbc.utils.MovingAverage;
import org.openhab.persistence.jdbc.utils.StringUtilsExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Configuration class
*
* @author Helmut Lehmeyer - Initial contribution
*/
@NonNullByDefault
public class JdbcConfiguration {
private final Logger logger = LoggerFactory.getLogger(JdbcConfiguration.class);
private static final Pattern EXTRACT_CONFIG_PATTERN = Pattern.compile("^(.*?)\\.([0-9.a-zA-Z]+)$");
private static final String DB_DAO_PACKAGE = "org.openhab.persistence.jdbc.db.Jdbc";
private Map<Object, Object> configuration;
private @NonNullByDefault({}) JdbcBaseDAO dBDAO;
private @Nullable String dbName;
boolean dbConnected = false;
boolean driverAvailable = false;
private @Nullable String serviceName;
private String name = "jdbc";
public final boolean valid;
// private String url;
// private String user;
// private String password;
private int numberDecimalcount = 3;
private boolean tableUseRealItemNames = false;
private boolean tableCaseSensitiveItemNames = false;
private String tableNamePrefix = "item";
private int tableIdDigitCount = 4;
private boolean rebuildTableNames = false;
private int errReconnectThreshold = 0;
public int timerCount = 0;
public int time1000Statements = 0;
public long timer1000 = 0;
public MovingAverage timeAverage50arr = new MovingAverage(50);
public MovingAverage timeAverage100arr = new MovingAverage(100);
public MovingAverage timeAverage200arr = new MovingAverage(200);
public boolean enableLogTime = false;
public JdbcConfiguration(Map<Object, Object> configuration) {
logger.debug("JDBC::JdbcConfiguration");
this.configuration = configuration;
valid = updateConfig();
}
private boolean updateConfig() {
logger.debug("JDBC::updateConfig: configuration size = {}", configuration.size());
String user = (String) configuration.get("user");
String password = (String) configuration.get("password");
// mandatory url
String url = (String) configuration.get("url");
if (url == null) {
logger.error("Mandatory url parameter is missing in configuration!");
return false;
}
Properties parsedURL = StringUtilsExt.parseJdbcURL(url);
if (user == null || user.isBlank()) {
logger.debug("No jdbc:user parameter defined in jdbc.cfg");
}
if (password == null || password.isBlank()) {
logger.debug("No jdbc:password parameter defined in jdbc.cfg.");
}
if (url.isBlank()) {
logger.debug(
"JDBC url is missing - please configure in jdbc.cfg like 'jdbc:<service>:<host>[:<port>;<attributes>]'");
return false;
}
if ("false".equalsIgnoreCase(parsedURL.getProperty("parseValid"))) {
Enumeration<?> en = parsedURL.propertyNames();
String enstr = "";
for (Object key : Collections.list(en)) {
enstr += key + " = " + parsedURL.getProperty("" + key) + "\n";
}
logger.warn(
"JDBC url is not well formatted: {}\nPlease configure in openhab.cfg like 'jdbc:<service>:<host>[:<port>;<attributes>]'",
enstr);
return false;
}
logger.debug("JDBC::updateConfig: user={}", user);
logger.debug("JDBC::updateConfig: password exists? {}", password != null && !password.isBlank());
logger.debug("JDBC::updateConfig: url={}", url);
// set database type and database type class
setDBDAOClass(parsedURL.getProperty("dbShortcut")); // derby, h2, hsqldb, mariadb, mysql, postgresql,
// sqlite, timescaledb
// set user
if (user != null && !user.isBlank()) {
dBDAO.databaseProps.setProperty("dataSource.user", user);
}
// set password
if (password != null && !password.isBlank()) {
dBDAO.databaseProps.setProperty("dataSource.password", password);
}
// set sql-types from external config
setSqlTypes();
final Pattern isNumericPattern = Pattern.compile("\\d+(\\.\\d+)?");
String et = (String) configuration.get("reconnectCnt");
if (et != null && !et.isBlank() && isNumericPattern.matcher(et).matches()) {
errReconnectThreshold = Integer.parseInt(et);
logger.debug("JDBC::updateConfig: errReconnectThreshold={}", errReconnectThreshold);
}
String np = (String) configuration.get("tableNamePrefix");
if (np != null && !np.isBlank()) {
tableNamePrefix = np;
logger.debug("JDBC::updateConfig: tableNamePrefix={}", tableNamePrefix);
}
String dd = (String) configuration.get("numberDecimalcount");
if (dd != null && !dd.isBlank() && isNumericPattern.matcher(dd).matches()) {
numberDecimalcount = Integer.parseInt(dd);
logger.debug("JDBC::updateConfig: numberDecimalcount={}", numberDecimalcount);
}
String rn = (String) configuration.get("tableUseRealItemNames");
if (rn != null && !rn.isBlank()) {
tableUseRealItemNames = "true".equals(rn) ? Boolean.parseBoolean(rn) : false;
logger.debug("JDBC::updateConfig: tableUseRealItemNames={}", tableUseRealItemNames);
}
String lc = (String) configuration.get("tableCaseSensitiveItemNames");
if (lc != null && !lc.isBlank()) {
tableCaseSensitiveItemNames = Boolean.parseBoolean(lc);
logger.debug("JDBC::updateConfig: tableCaseSensitiveItemNames={}", tableCaseSensitiveItemNames);
}
String td = (String) configuration.get("tableIdDigitCount");
if (td != null && !td.isBlank() && isNumericPattern.matcher(td).matches()) {
tableIdDigitCount = Integer.parseInt(td);
logger.debug("JDBC::updateConfig: tableIdDigitCount={}", tableIdDigitCount);
}
String rt = (String) configuration.get("rebuildTableNames");
if (rt != null && !rt.isBlank()) {
rebuildTableNames = Boolean.parseBoolean(rt);
logger.debug("JDBC::updateConfig: rebuildTableNames={}", rebuildTableNames);
}
// undocumented
String ac = (String) configuration.get("maximumPoolSize");
if (ac != null && !ac.isBlank()) {
dBDAO.databaseProps.setProperty("maximumPoolSize", ac);
}
// undocumented
String ic = (String) configuration.get("minimumIdle");
if (ic != null && !ic.isBlank()) {
dBDAO.databaseProps.setProperty("minimumIdle", ic);
}
// undocumented
String it = (String) configuration.get("idleTimeout");
if (it != null && !it.isBlank()) {
dBDAO.databaseProps.setProperty("idleTimeout", it);
}
// undocumented
String ent = (String) configuration.get("enableLogTime");
if (ent != null && !ent.isBlank()) {
enableLogTime = "true".equals(ent) ? Boolean.parseBoolean(ent) : false;
}
logger.debug("JDBC::updateConfig: enableLogTime {}", enableLogTime);
// undocumented
String fd = (String) configuration.get("driverClassName");
if (fd != null && !fd.isBlank()) {
dBDAO.databaseProps.setProperty("driverClassName", fd);
}
// undocumented
String ds = (String) configuration.get("dataSourceClassName");
if (ds != null && !ds.isBlank()) {
dBDAO.databaseProps.setProperty("dataSourceClassName", ds);
}
// undocumented
String dn = dBDAO.databaseProps.getProperty("driverClassName");
if (dn == null) {
dn = dBDAO.databaseProps.getProperty("dataSourceClassName");
} else {
dBDAO.databaseProps.setProperty("jdbcUrl", url);
}
// test if JDBC driver bundle is available
testJDBCDriver(dn);
logger.debug("JDBC::updateConfig: configuration complete. service={}", getName());
return true;
}
private void setDBDAOClass(String sn) {
String serviceName;
// set database type
if (sn.isBlank() || sn.length() < 2) {
logger.error(
"JDBC::updateConfig: Required database url like 'jdbc:<service>:<host>[:<port>;<attributes>]' - please configure the jdbc:url parameter in openhab.cfg");
serviceName = "none";
} else {
serviceName = sn;
}
this.serviceName = serviceName;
logger.debug("JDBC::updateConfig: found serviceName = '{}'", serviceName);
// set class for database type
String ddp = DB_DAO_PACKAGE + serviceName.toUpperCase().charAt(0) + serviceName.toLowerCase().substring(1)
+ "DAO";
logger.debug("JDBC::updateConfig: Init Data Access Object Class: '{}'", ddp);
try {
dBDAO = (JdbcBaseDAO) Class.forName(ddp).getConstructor().newInstance();
logger.debug("JDBC::updateConfig: dBDAO ClassName={}", dBDAO.getClass().getName());
} catch (IllegalAccessException | InstantiationException | InvocationTargetException
| NoSuchMethodException e) {
logger.error("JDBC::updateConfig: Exception: {}", e.getMessage());
} catch (ClassNotFoundException e) {
logger.warn("JDBC::updateConfig: no Configuration for serviceName '{}' found. ClassNotFoundException: {}",
serviceName, e.getMessage());
logger.debug("JDBC::updateConfig: using default Database Configuration: JdbcBaseDAO !!");
dBDAO = new JdbcBaseDAO();
logger.debug("JDBC::updateConfig: dBConfig done");
}
}
private void setSqlTypes() {
Set<Object> keys = configuration.keySet();
for (Object k : keys) {
String key = (String) k;
Matcher matcher = EXTRACT_CONFIG_PATTERN.matcher(key);
if (!matcher.matches()) {
continue;
}
matcher.reset();
matcher.find();
if (!"sqltype".equals(matcher.group(1))) {
continue;
}
String itemType = matcher.group(2);
if (!itemType.startsWith("table")) {
itemType = itemType.toUpperCase() + "ITEM";
}
String value = (String) configuration.get(key);
logger.debug("JDBC::updateConfig: set sqlTypes: itemType={} value={}", itemType, value);
if (value != null) {
dBDAO.sqlTypes.put(itemType, value);
}
}
}
private void testJDBCDriver(String driver) {
driverAvailable = true;
try {
Class.forName(driver);
logger.debug("JDBC::updateConfig: load JDBC-driverClass was successful: '{}'", driver);
} catch (ClassNotFoundException e) {
driverAvailable = false;
logger.error(
"JDBC::updateConfig: could NOT load JDBC-driverClassName or JDBC-dataSourceClassName. ClassNotFoundException: '{}'",
e.getMessage());
String warn = ""
+ "\n\n\t!!!\n\tTo avoid this error, place an appropriate JDBC driver file for serviceName '{}' in addons directory.\n"
+ "\tCopy missing JDBC-Driver-jar to your openHab/addons Folder.\n\t!!!\n" + "\tDOWNLOAD: \n";
String serviceName = this.serviceName;
if (serviceName != null) {
switch (serviceName) {
case "derby":
warn += "\tDerby: version >= 10.14.2.0 from https://mvnrepository.com/artifact/org.apache.derby/derby\n";
break;
case "h2":
warn += "\tH2: version >= 1.4.189 from https://mvnrepository.com/artifact/com.h2database/h2\n";
break;
case "hsqldb":
warn += "\tHSQLDB: version >= 2.3.3 from https://mvnrepository.com/artifact/org.hsqldb/hsqldb\n";
break;
case "mariadb":
warn += "\tMariaDB: version >= 3.0.8 from https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client\n";
break;
case "mysql":
warn += "\tMySQL: version >= 8.0.30 from https://mvnrepository.com/artifact/mysql/mysql-connector-java\n";
break;
case "postgresql":
warn += "\tPostgreSQL:version >= 42.4.1 from https://mvnrepository.com/artifact/org.postgresql/postgresql\n";
break;
case "sqlite":
warn += "\tSQLite: version >= 3.16.1 from https://mvnrepository.com/artifact/org.xerial/sqlite-jdbc\n";
break;
}
}
logger.warn(warn, serviceName);
}
}
public Properties getHikariConfiguration() {
return dBDAO.getConnectionProperties();
}
public String getName() {
// return serviceName;
return name;
}
public @Nullable String getServiceName() {
return serviceName;
}
public String getTableNamePrefix() {
return tableNamePrefix;
}
public int getErrReconnectThreshold() {
return errReconnectThreshold;
}
public boolean getRebuildTableNames() {
return rebuildTableNames;
}
public int getNumberDecimalcount() {
return numberDecimalcount;
}
public boolean getTableUseRealItemNames() {
return tableUseRealItemNames;
}
public boolean getTableCaseSensitiveItemNames() {
return tableCaseSensitiveItemNames;
}
/**
* Checks if real item names (without number suffix) is enabled.
*
* @return true if both tableUseRealItemNames and tableCaseSensitiveItemNames are enabled.
*/
public boolean getTableUseRealCaseSensitiveItemNames() {
return tableUseRealItemNames && tableCaseSensitiveItemNames;
}
public int getTableIdDigitCount() {
return tableIdDigitCount;
}
public JdbcBaseDAO getDBDAO() {
return dBDAO;
}
public @Nullable String getDbName() {
return dbName;
}
public void setDbName(String dbName) {
this.dbName = dbName;
}
public boolean isDbConnected() {
return dbConnected;
}
public void setDbConnected(boolean dbConnected) {
logger.debug("JDBC::setDbConnected {}", dbConnected);
// Initializing step, after db is connected.
// Initialize sqlTypes, depending on DB version for example
dBDAO.initAfterFirstDbConnection();
// Running once again to prior external configured SqlTypes!
setSqlTypes();
this.dbConnected = dbConnected;
}
public boolean isDriverAvailable() {
return driverAvailable;
}
}