2 * Copyright (c) 2010-2022 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.persistence.jdbc.internal;
15 import java.lang.reflect.InvocationTargetException;
16 import java.util.Collections;
17 import java.util.Enumeration;
19 import java.util.Properties;
21 import java.util.regex.Matcher;
22 import java.util.regex.Pattern;
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.openhab.persistence.jdbc.db.JdbcBaseDAO;
27 import org.openhab.persistence.jdbc.utils.MovingAverage;
28 import org.openhab.persistence.jdbc.utils.StringUtilsExt;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
35 * @author Helmut Lehmeyer - Initial contribution
38 public class JdbcConfiguration {
39 private final Logger logger = LoggerFactory.getLogger(JdbcConfiguration.class);
41 private static final Pattern EXTRACT_CONFIG_PATTERN = Pattern.compile("^(.*?)\\.([0-9.a-zA-Z]+)$");
42 private static final String DB_DAO_PACKAGE = "org.openhab.persistence.jdbc.db.Jdbc";
44 private Map<Object, Object> configuration;
46 private @NonNullByDefault({}) JdbcBaseDAO dBDAO;
47 private @Nullable String dbName;
48 boolean dbConnected = false;
49 boolean driverAvailable = false;
51 private @Nullable String serviceName;
52 private String name = "jdbc";
53 public final boolean valid;
55 // private String url;
56 // private String user;
57 // private String password;
58 private int numberDecimalcount = 3;
59 private boolean tableUseRealItemNames = false;
60 private String tableNamePrefix = "item";
61 private int tableIdDigitCount = 4;
62 private boolean rebuildTableNames = false;
64 private int errReconnectThreshold = 0;
66 public int timerCount = 0;
67 public int time1000Statements = 0;
68 public long timer1000 = 0;
69 public MovingAverage timeAverage50arr = new MovingAverage(50);
70 public MovingAverage timeAverage100arr = new MovingAverage(100);
71 public MovingAverage timeAverage200arr = new MovingAverage(200);
72 public boolean enableLogTime = false;
74 public JdbcConfiguration(Map<Object, Object> configuration) {
75 logger.debug("JDBC::JdbcConfiguration");
76 this.configuration = configuration;
77 valid = updateConfig();
80 private boolean updateConfig() {
81 logger.debug("JDBC::updateConfig: configuration size = {}", configuration.size());
83 String user = (String) configuration.get("user");
84 String password = (String) configuration.get("password");
87 String url = (String) configuration.get("url");
90 logger.error("Mandatory url parameter is missing in configuration!");
94 Properties parsedURL = StringUtilsExt.parseJdbcURL(url);
96 if (user == null || user.isBlank()) {
97 logger.debug("No jdbc:user parameter defined in jdbc.cfg");
99 if (password == null || password.isBlank()) {
100 logger.debug("No jdbc:password parameter defined in jdbc.cfg.");
105 "JDBC url is missing - please configure in jdbc.cfg like 'jdbc:<service>:<host>[:<port>;<attributes>]'");
109 if ("false".equalsIgnoreCase(parsedURL.getProperty("parseValid"))) {
110 Enumeration<?> en = parsedURL.propertyNames();
112 for (Object key : Collections.list(en)) {
113 enstr += key + " = " + parsedURL.getProperty("" + key) + "\n";
116 "JDBC url is not well formatted: {}\nPlease configure in openhab.cfg like 'jdbc:<service>:<host>[:<port>;<attributes>]'",
121 logger.debug("JDBC::updateConfig: user={}", user);
122 logger.debug("JDBC::updateConfig: password exists? {}", password != null && !password.isBlank());
123 logger.debug("JDBC::updateConfig: url={}", url);
125 // set database type and database type class
126 setDBDAOClass(parsedURL.getProperty("dbShortcut")); // derby, h2, hsqldb, mariadb, mysql, postgresql,
127 // sqlite, timescaledb
129 if (user != null && !user.isBlank()) {
130 dBDAO.databaseProps.setProperty("dataSource.user", user);
134 if (password != null && !password.isBlank()) {
135 dBDAO.databaseProps.setProperty("dataSource.password", password);
138 // set sql-types from external config
141 final Pattern isNumericPattern = Pattern.compile("\\d+(\\.\\d+)?");
142 String et = (String) configuration.get("reconnectCnt");
143 if (et != null && !et.isBlank() && isNumericPattern.matcher(et).matches()) {
144 errReconnectThreshold = Integer.parseInt(et);
145 logger.debug("JDBC::updateConfig: errReconnectThreshold={}", errReconnectThreshold);
148 String np = (String) configuration.get("tableNamePrefix");
149 if (np != null && !np.isBlank()) {
150 tableNamePrefix = np;
151 logger.debug("JDBC::updateConfig: tableNamePrefix={}", tableNamePrefix);
154 String dd = (String) configuration.get("numberDecimalcount");
155 if (dd != null && !dd.isBlank() && isNumericPattern.matcher(dd).matches()) {
156 numberDecimalcount = Integer.parseInt(dd);
157 logger.debug("JDBC::updateConfig: numberDecimalcount={}", numberDecimalcount);
160 String rn = (String) configuration.get("tableUseRealItemNames");
161 if (rn != null && !rn.isBlank()) {
162 tableUseRealItemNames = "true".equals(rn) ? Boolean.parseBoolean(rn) : false;
163 logger.debug("JDBC::updateConfig: tableUseRealItemNames={}", tableUseRealItemNames);
166 String td = (String) configuration.get("tableIdDigitCount");
167 if (td != null && !td.isBlank() && isNumericPattern.matcher(td).matches()) {
168 tableIdDigitCount = Integer.parseInt(td);
169 logger.debug("JDBC::updateConfig: tableIdDigitCount={}", tableIdDigitCount);
172 String rt = (String) configuration.get("rebuildTableNames");
173 if (rt != null && !rt.isBlank()) {
174 rebuildTableNames = Boolean.parseBoolean(rt);
175 logger.debug("JDBC::updateConfig: rebuildTableNames={}", rebuildTableNames);
179 String ac = (String) configuration.get("maximumPoolSize");
180 if (ac != null && !ac.isBlank()) {
181 dBDAO.databaseProps.setProperty("maximumPoolSize", ac);
185 String ic = (String) configuration.get("minimumIdle");
186 if (ic != null && !ic.isBlank()) {
187 dBDAO.databaseProps.setProperty("minimumIdle", ic);
191 String it = (String) configuration.get("idleTimeout");
192 if (it != null && !it.isBlank()) {
193 dBDAO.databaseProps.setProperty("idleTimeout", it);
196 String ent = (String) configuration.get("enableLogTime");
197 if (ent != null && !ent.isBlank()) {
198 enableLogTime = "true".equals(ent) ? Boolean.parseBoolean(ent) : false;
200 logger.debug("JDBC::updateConfig: enableLogTime {}", enableLogTime);
203 String fd = (String) configuration.get("driverClassName");
204 if (fd != null && !fd.isBlank()) {
205 dBDAO.databaseProps.setProperty("driverClassName", fd);
209 String ds = (String) configuration.get("dataSourceClassName");
210 if (ds != null && !ds.isBlank()) {
211 dBDAO.databaseProps.setProperty("dataSourceClassName", ds);
215 String dn = dBDAO.databaseProps.getProperty("driverClassName");
217 dn = dBDAO.databaseProps.getProperty("dataSourceClassName");
219 dBDAO.databaseProps.setProperty("jdbcUrl", url);
222 // test if JDBC driver bundle is available
225 logger.debug("JDBC::updateConfig: configuration complete. service={}", getName());
230 private void setDBDAOClass(String sn) {
234 if (sn.isBlank() || sn.length() < 2) {
236 "JDBC::updateConfig: Required database url like 'jdbc:<service>:<host>[:<port>;<attributes>]' - please configure the jdbc:url parameter in openhab.cfg");
237 serviceName = "none";
241 this.serviceName = serviceName;
242 logger.debug("JDBC::updateConfig: found serviceName = '{}'", serviceName);
244 // set class for database type
245 String ddp = DB_DAO_PACKAGE + serviceName.toUpperCase().charAt(0) + serviceName.toLowerCase().substring(1)
248 logger.debug("JDBC::updateConfig: Init Data Access Object Class: '{}'", ddp);
250 dBDAO = (JdbcBaseDAO) Class.forName(ddp).getConstructor().newInstance();
251 logger.debug("JDBC::updateConfig: dBDAO ClassName={}", dBDAO.getClass().getName());
252 } catch (IllegalAccessException | InstantiationException | InvocationTargetException
253 | NoSuchMethodException e) {
254 logger.error("JDBC::updateConfig: Exception: {}", e.getMessage());
255 } catch (ClassNotFoundException e) {
256 logger.warn("JDBC::updateConfig: no Configuration for serviceName '{}' found. ClassNotFoundException: {}",
257 serviceName, e.getMessage());
258 logger.debug("JDBC::updateConfig: using default Database Configuration: JdbcBaseDAO !!");
259 dBDAO = new JdbcBaseDAO();
260 logger.debug("JDBC::updateConfig: dBConfig done");
264 private void setSqlTypes() {
265 Set<Object> keys = configuration.keySet();
267 for (Object k : keys) {
268 String key = (String) k;
269 Matcher matcher = EXTRACT_CONFIG_PATTERN.matcher(key);
270 if (!matcher.matches()) {
275 if (!"sqltype".equals(matcher.group(1))) {
278 String itemType = matcher.group(2);
279 if (!itemType.startsWith("table")) {
280 itemType = itemType.toUpperCase() + "ITEM";
282 String value = (String) configuration.get(key);
283 logger.debug("JDBC::updateConfig: set sqlTypes: itemType={} value={}", itemType, value);
285 dBDAO.sqlTypes.put(itemType, value);
290 private void testJDBCDriver(String driver) {
291 driverAvailable = true;
293 Class.forName(driver);
294 logger.debug("JDBC::updateConfig: load JDBC-driverClass was successful: '{}'", driver);
295 } catch (ClassNotFoundException e) {
296 driverAvailable = false;
298 "JDBC::updateConfig: could NOT load JDBC-driverClassName or JDBC-dataSourceClassName. ClassNotFoundException: '{}'",
301 + "\n\n\t!!!\n\tTo avoid this error, place an appropriate JDBC driver file for serviceName '{}' in addons directory.\n"
302 + "\tCopy missing JDBC-Driver-jar to your openHab/addons Folder.\n\t!!!\n" + "\tDOWNLOAD: \n";
303 String serviceName = this.serviceName;
304 if (serviceName != null) {
305 switch (serviceName) {
307 warn += "\tDerby: version >= 10.14.2.0 from https://mvnrepository.com/artifact/org.apache.derby/derby\n";
310 warn += "\tH2: version >= 1.4.189 from https://mvnrepository.com/artifact/com.h2database/h2\n";
313 warn += "\tHSQLDB: version >= 2.3.3 from https://mvnrepository.com/artifact/org.hsqldb/hsqldb\n";
316 warn += "\tMariaDB: version >= 1.4.6 from https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client\n";
319 warn += "\tMySQL: version >= 8.0.30 from https://mvnrepository.com/artifact/mysql/mysql-connector-java\n";
322 warn += "\tPostgreSQL:version >= 42.4.1 from https://mvnrepository.com/artifact/org.postgresql/postgresql\n";
325 warn += "\tSQLite: version >= 3.16.1 from https://mvnrepository.com/artifact/org.xerial/sqlite-jdbc\n";
329 logger.warn(warn, serviceName);
333 public Properties getHikariConfiguration() {
334 return dBDAO.getConnectionProperties();
337 public String getName() {
338 // return serviceName;
342 public @Nullable String getServiceName() {
346 public String getTableNamePrefix() {
347 return tableNamePrefix;
350 public int getErrReconnectThreshold() {
351 return errReconnectThreshold;
354 public boolean getRebuildTableNames() {
355 return rebuildTableNames;
358 public int getNumberDecimalcount() {
359 return numberDecimalcount;
362 public boolean getTableUseRealItemNames() {
363 return tableUseRealItemNames;
366 public int getTableIdDigitCount() {
367 return tableIdDigitCount;
370 public JdbcBaseDAO getDBDAO() {
374 public @Nullable String getDbName() {
378 public void setDbName(String dbName) {
379 this.dbName = dbName;
382 public boolean isDbConnected() {
386 public void setDbConnected(boolean dbConnected) {
387 logger.debug("JDBC::setDbConnected {}", dbConnected);
388 // Initializing step, after db is connected.
389 // Initialize sqlTypes, depending on DB version for example
390 dBDAO.initAfterFirstDbConnection();
391 // Running once again to prior external configured SqlTypes!
393 this.dbConnected = dbConnected;
396 public boolean isDriverAvailable() {
397 return driverAvailable;