From b71a9ad5e7af9f5e4e73cc603c9ee80002ee0a56 Mon Sep 17 00:00:00 2001 From: Kai Kreuzer Date: Sun, 5 Apr 2020 18:20:30 +0200 Subject: [PATCH 1/2] removed mysql persistence service Signed-off-by: Kai Kreuzer --- .../org.openhab.persistence.mysql/.classpath | 27 - bundles/org.openhab.persistence.mysql/NOTICE | 13 - .../org.openhab.persistence.mysql/README.md | 25 - bundles/org.openhab.persistence.mysql/pom.xml | 29 - .../src/main/feature/feature.xml | 11 - .../persistence/mysql/internal/MysqlItem.java | 58 -- .../internal/MysqlPersistenceService.java | 715 ------------------ bundles/pom.xml | 1 - features/openhab-addons-external/pom.xml | 1 - .../src/main/resources/conf/mysql.cfg | 19 - 10 files changed, 899 deletions(-) delete mode 100644 bundles/org.openhab.persistence.mysql/.classpath delete mode 100644 bundles/org.openhab.persistence.mysql/NOTICE delete mode 100644 bundles/org.openhab.persistence.mysql/README.md delete mode 100644 bundles/org.openhab.persistence.mysql/pom.xml delete mode 100644 bundles/org.openhab.persistence.mysql/src/main/feature/feature.xml delete mode 100644 bundles/org.openhab.persistence.mysql/src/main/java/org/openhab/persistence/mysql/internal/MysqlItem.java delete mode 100644 bundles/org.openhab.persistence.mysql/src/main/java/org/openhab/persistence/mysql/internal/MysqlPersistenceService.java delete mode 100644 features/openhab-addons-external/src/main/resources/conf/mysql.cfg diff --git a/bundles/org.openhab.persistence.mysql/.classpath b/bundles/org.openhab.persistence.mysql/.classpath deleted file mode 100644 index d6a726fe71017..0000000000000 --- a/bundles/org.openhab.persistence.mysql/.classpath +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/bundles/org.openhab.persistence.mysql/NOTICE b/bundles/org.openhab.persistence.mysql/NOTICE deleted file mode 100644 index 38d625e349232..0000000000000 --- a/bundles/org.openhab.persistence.mysql/NOTICE +++ /dev/null @@ -1,13 +0,0 @@ -This content is produced and maintained by the openHAB project. - -* Project home: https://www.openhab.org - -== Declared Project Licenses - -This program and the accompanying materials are made available under the terms -of the Eclipse Public License 2.0 which is available at -https://www.eclipse.org/legal/epl-2.0/. - -== Source Code - -https://github.com/openhab/openhab-addons diff --git a/bundles/org.openhab.persistence.mysql/README.md b/bundles/org.openhab.persistence.mysql/README.md deleted file mode 100644 index 64b3629b2cc70..0000000000000 --- a/bundles/org.openhab.persistence.mysql/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# MySQL Persistence - -This service allows you to persist state updates using the [MySQL](https://www.mysql.com/) database. -Note that other SQL databases need a separate service due to incompatibilities between different SQL databases. - -This persistence service supports writing information to MySQL relational database systems, as well as querying from them. - -The service will create a mapping table called `Items` to link each item to a table, and a separate table is generated for each item. -The item data tables include the time and data - the data type is dependent on the item type and allows the item state to be recovered back into openHAB in the same way it was stored. - -## Configuration - -This service can be configured in the file `services/mysql.cfg`. - -| Property | Default | Required | Description | -| -------------- | ------- | :-------: | ------------------------------------------------------------ | -| url | | Yes | database URL, in the format `jdbc:mysql://:/`. For example, `jdbc:mysql://127.0.0.1/openhab` | -| user | | if needed | database user | -| password | | if needed | database password | -| reconnectCnt | | No | reconnection counter. Setting this to 1 will cause the service to close the connection and reconnect if there are any errors. | -| waitTimeout | | No | connection timeout (in seconds). This sets the number of seconds that MySQL will keep the session open without any transactions. It should default to 8 hours within mySQL, but some implementations may use lower values (possibly as low as 60 seconds) which would cause unnecessary reconnections. This value needs to be set higher than the maximum logging period. | -| sqltype.string | | No | mapping of an openHAB item type to an SQL data type. See [this issue](https://github.com/openhab/openhab1-addons/issues/710) for more information. | -| localtime | `false` | No | use MySQL server time to store item values (if set to `false`) or use openHAB server time (if set to `true`). For new installations, setting this to `true` is recommended. | - -All item and event related configuration is done in the file `persistence/mysql.persist`. diff --git a/bundles/org.openhab.persistence.mysql/pom.xml b/bundles/org.openhab.persistence.mysql/pom.xml deleted file mode 100644 index aa9e0650fe38d..0000000000000 --- a/bundles/org.openhab.persistence.mysql/pom.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - 4.0.0 - - - org.openhab.addons.bundles - org.openhab.addons.reactor.bundles - 3.0.0-SNAPSHOT - - - org.openhab.persistence.mysql - - openHAB Add-ons :: Bundles :: Persistence Service :: MySQL - - - !com.mongodb.*,!io.netty.*,!com.bea.*,!io.reactivex.*,!org.reactivestreams.*,!de.erichseifert.*,!org.w3c.*,!org.jvnet.*,!com.ctc.*,!com.sun.*,!com.sleepycat.*,!dagger.*,!org.codehaus.*,!org.glassfish.*,!com.ibm.*,!javax.xml.*,!net.sf.*,!nu.xom.*,!org.bson.*,!org.dom4j.*,!org.jdom.*,!org.jdom2.*,!org.kxml2.io.*,!org.xmlpull.*,!sun.*,!com.mchange.*,!org.jboss.*,!com.google.protobuf - - - - - - mysql - mysql-connector-java - 8.0.13 - - - diff --git a/bundles/org.openhab.persistence.mysql/src/main/feature/feature.xml b/bundles/org.openhab.persistence.mysql/src/main/feature/feature.xml deleted file mode 100644 index 9a21f0d59d72f..0000000000000 --- a/bundles/org.openhab.persistence.mysql/src/main/feature/feature.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - mvn:org.openhab.core.features.karaf/org.openhab.core.features.karaf.openhab-core/${ohc.version}/xml/features - - - openhab-runtime-base - mvn:org.openhab.addons.bundles/org.openhab.persistence.mysql/${project.version} - mvn:${project.groupId}/openhab-addons-external3/${project.version}/cfg/mysql - - - diff --git a/bundles/org.openhab.persistence.mysql/src/main/java/org/openhab/persistence/mysql/internal/MysqlItem.java b/bundles/org.openhab.persistence.mysql/src/main/java/org/openhab/persistence/mysql/internal/MysqlItem.java deleted file mode 100644 index 8d67c1a21c51a..0000000000000 --- a/bundles/org.openhab.persistence.mysql/src/main/java/org/openhab/persistence/mysql/internal/MysqlItem.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright (c) 2010-2020 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.mysql.internal; - -import java.text.DateFormat; -import java.util.Date; - -import org.openhab.core.persistence.HistoricItem; -import org.openhab.core.types.State; - -/** - * This is a Java bean used to return historic items from a SQL database. - * - * @author Chris Jackson - Initial contribution - */ -public class MysqlItem implements HistoricItem { - - private final String name; - private final State state; - private final Date timestamp; - - public MysqlItem(String name, State state, Date timestamp) { - this.name = name; - this.state = state; - this.timestamp = timestamp; - } - - @Override - public String getName() { - return name; - } - - @Override - public State getState() { - return state; - } - - @Override - public Date getTimestamp() { - return timestamp; - } - - @Override - public String toString() { - return DateFormat.getDateTimeInstance().format(timestamp) + ": " + name + " -> " + state.toString(); - } - -} diff --git a/bundles/org.openhab.persistence.mysql/src/main/java/org/openhab/persistence/mysql/internal/MysqlPersistenceService.java b/bundles/org.openhab.persistence.mysql/src/main/java/org/openhab/persistence/mysql/internal/MysqlPersistenceService.java deleted file mode 100644 index 9d2b9ffc77d80..0000000000000 --- a/bundles/org.openhab.persistence.mysql/src/main/java/org/openhab/persistence/mysql/internal/MysqlPersistenceService.java +++ /dev/null @@ -1,715 +0,0 @@ -/** - * Copyright (c) 2010-2020 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.mysql.internal; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.Formatter; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.lang.StringUtils; -import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; -import org.openhab.core.items.GroupItem; -import org.openhab.core.items.Item; -import org.openhab.core.items.ItemNotFoundException; -import org.openhab.core.items.ItemRegistry; -import org.openhab.core.library.items.ColorItem; -import org.openhab.core.library.items.ContactItem; -import org.openhab.core.library.items.DateTimeItem; -import org.openhab.core.library.items.DimmerItem; -import org.openhab.core.library.items.NumberItem; -import org.openhab.core.library.items.RollershutterItem; -import org.openhab.core.library.items.SwitchItem; -import org.openhab.core.library.types.DateTimeType; -import org.openhab.core.library.types.DecimalType; -import org.openhab.core.library.types.HSBType; -import org.openhab.core.library.types.OnOffType; -import org.openhab.core.library.types.OpenClosedType; -import org.openhab.core.library.types.PercentType; -import org.openhab.core.library.types.StringType; -import org.openhab.core.persistence.FilterCriteria; -import org.openhab.core.persistence.FilterCriteria.Ordering; -import org.openhab.core.persistence.HistoricItem; -import org.openhab.core.persistence.PersistenceItemInfo; -import org.openhab.core.persistence.PersistenceService; -import org.openhab.core.persistence.QueryablePersistenceService; -import org.openhab.core.persistence.strategy.PersistenceStrategy; -import org.openhab.core.types.State; -import org.openhab.core.types.UnDefType; -import org.osgi.framework.BundleContext; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.ConfigurationPolicy; -import org.osgi.service.component.annotations.Deactivate; -import org.osgi.service.component.annotations.Reference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This is the implementation of the mySQL {@link PersistenceService}. - * - * Data is persisted with the following conversions: - * - * Item-Type Data-Type MySQL-Type - * ========= ========= ========== - * ColorItem HSBType CHAR(25) - * ContactItem OnOffType CHAR(6) - * DateTimeItem DateTimeType DATETIME - * DimmerItem PercentType TINYINT - * NumberItem DecimalType DOUBLE - * RollershutterItem PercentType TINYINT - * StringItem StringType VARCHAR(20000) - * SwitchItem OnOffType CHAR(3) - * - * In the store method, type conversion is performed where the default type for - * an item is not as above. For example, DimmerType can return OnOffType, so to - * keep the best resolution, we store as a number in SQL and convert to - * DecimalType before persisting to MySQL. - * - * @author Henrik Sjöstrand - Initial contribution - * @author Thomas.Eichstaedt-Engelen - Enhancements - * @author Chris Jackson - Enhancements - * @author Helmut Lehmeyer - Enhancements - */ -@NonNullByDefault -@Component(service = { PersistenceService.class, - QueryablePersistenceService.class }, configurationPid = "org.openhab.mysql", configurationPolicy = ConfigurationPolicy.REQUIRE) -public class MysqlPersistenceService implements QueryablePersistenceService { - - private static final Pattern EXTRACT_CONFIG_PATTERN = Pattern.compile("^(.*?)\\.([0-9.a-zA-Z]+)$"); - - private final Logger logger = LoggerFactory.getLogger(MysqlPersistenceService.class); - - private String driverClass = "com.mysql.jdbc.Driver"; - private @NonNullByDefault({}) String url; - private @NonNullByDefault({}) String user; - private @NonNullByDefault({}) String password; - - private boolean initialized = false; - - @Reference - protected @NonNullByDefault({}) ItemRegistry itemRegistry; - - // Error counter - used to reconnect to database on error - private int errCnt; - private int errReconnectThreshold = 0; - - private int waitTimeout = -1; - - // Time used for persisting items, False: MySQL Server time (default), True: openHAB Server time - private boolean localtime = false; - - private @NonNullByDefault({}) Connection connection = null; - - private Map sqlTables = new HashMap<>(); - private Map sqlTypes = new HashMap<>(); - - /** - * Initialise the type array - * If other Types like DOUBLE or INT needed for serialisation it can be set in openhab.cfg - */ - @Activate - public void activate(final BundleContext bundleContext, final Map config) { - sqlTypes.put("CALLITEM", "VARCHAR(200)"); - sqlTypes.put("COLORITEM", "VARCHAR(70)"); - sqlTypes.put("CONTACTITEM", "VARCHAR(6)"); - sqlTypes.put("DATETIMEITEM", "DATETIME"); - sqlTypes.put("DIMMERITEM", "TINYINT"); - sqlTypes.put("LOCATIONITEM", "VARCHAR(30)"); - sqlTypes.put("NUMBERITEM", "DOUBLE"); - sqlTypes.put("ROLLERSHUTTERITEM", "TINYINT"); - sqlTypes.put("STRINGITEM", "VARCHAR(20000)"); - sqlTypes.put("SWITCHITEM", "CHAR(3)"); - - Iterator keys = config.keySet().iterator(); - while (keys.hasNext()) { - String key = keys.next(); - - Matcher matcher = EXTRACT_CONFIG_PATTERN.matcher(key); - - if (!matcher.matches()) { - continue; - } - - matcher.reset(); - matcher.find(); - - if (!matcher.group(1).equals("sqltype")) { - continue; - } - - String itemType = matcher.group(2).toUpperCase() + "ITEM"; - String value = (String) config.get(key); - - sqlTypes.put(itemType, value); - } - - disconnectFromDatabase(); - - url = (String) config.get("url"); - if (StringUtils.isBlank(url)) { - logger.warn("The mySQL database URL is missing. Please configure the url parameter in the configuration."); - return; - } - - user = (String) config.get("user"); - if (StringUtils.isBlank(user)) { - logger.warn("The mySQL user is missing. Please configure the user parameter in the configuration."); - return; - } - - password = (String) config.get("password"); - if (StringUtils.isBlank(password)) { - logger.warn( - "The mySQL password is missing; attempting to connect without password. To specify a password, configure the password parameter in the configuration."); - } - - String tmpString = (String) config.get("reconnectCnt"); - if (StringUtils.isNotBlank(tmpString)) { - errReconnectThreshold = Integer.parseInt(tmpString); - } - - tmpString = (String) config.get("waitTimeout"); - if (StringUtils.isNotBlank(tmpString)) { - waitTimeout = Integer.parseInt(tmpString); - } - - tmpString = (String) config.get("localtime"); - if (StringUtils.isNotBlank(tmpString)) { - localtime = Boolean.parseBoolean(tmpString); - } - - // reconnect to the database in case the configuration has changed. - connectToDatabase(); - - // connection has been established ... initialization completed! - initialized = true; - - logger.debug("mySQL configuration complete."); - } - - @Deactivate - public void deactivate(final int reason) { - logger.debug("mySQL persistence bundle stopping. Disconnecting from database."); - disconnectFromDatabase(); - } - - @Override - public String getId() { - return "mysql"; - } - - @Override - public String getLabel(@Nullable Locale locale) { - return "MySQL"; - } - - /** - * - * @param i - * @return - */ - private @Nullable String getItemType(Item i) { - Item item = i; - if (i instanceof GroupItem) { - item = ((GroupItem) i).getBaseItem(); - if (item == null) {// if GroupItem: is not defined in *.items using StringType - logger.debug( - "mySQL: Cannot detect ItemType for {} because the GroupItems' base type isn't set in *.items file.", - i.getName()); - item = ((GroupItem) i).getMembers().iterator().next(); - } - } - String itemType = item.getClass().getSimpleName().toUpperCase(); - if (sqlTypes.get(itemType) == null) { - logger.debug("mySQL: No sqlType found for ItemType {}, use ItemType STRINGITEM ({}) as Fallback for {}", - itemType, sqlTypes.get("STRINGITEM"), i.getName()); - return sqlTypes.get("STRINGITEM"); - } - - logger.debug("mySQL: Use ItemType {} ({}) for Item {}", itemType, sqlTypes.get(itemType), i.getName()); - return sqlTypes.get(itemType); - } - - private @Nullable String getTable(Item item) { - String sqlCmd = null; - int rowId = 0; - - String itemName = item.getName(); - String tableName = sqlTables.get(itemName); - - // Table already exists - return the name - if (tableName != null) { - return tableName; - } - - logger.debug("mySQL: no Table found for itemName={} get:{}", itemName, sqlTables.get(itemName)); - - sqlCmd = new String("INSERT INTO Items (ItemName) VALUES (?)"); - - // Create a new entry in the Items table. This is the translation of - // item name to table - try (PreparedStatement statement = connection.prepareStatement(sqlCmd, Statement.RETURN_GENERATED_KEYS)) { - statement.setString(1, itemName); - statement.executeUpdate(); - - ResultSet resultSet = statement.getGeneratedKeys(); - if (resultSet != null && resultSet.next()) { - rowId = resultSet.getInt(1); - } - - if (rowId == 0) { - throw new SQLException("mySQL: Creating table for item '{}' failed.", itemName); - } - - // Create the table name - tableName = new String("Item" + rowId); - logger.debug("mySQL: new item {} is Item{}", itemName, rowId); - } catch (SQLException e) { - errCnt++; - logger.error("mySQL: Could not create entry for '{}' in table 'Items' with statement '{}': {}", itemName, - sqlCmd, e.getMessage()); - } - - // An error occurred adding the item name into the index list! - if (tableName == null) { - logger.error("mySQL: tableName was null"); - return null; - } - - String mysqlType = getItemType(item); - - // We have a rowId, create the table for the data - sqlCmd = new String( - "CREATE TABLE " + tableName + " (Time DATETIME, Value " + mysqlType + ", PRIMARY KEY(Time));"); - logger.debug("mySQL: query: {}", sqlCmd); - - try (PreparedStatement statement = connection.prepareStatement(sqlCmd)) { - statement.executeUpdate(); - - logger.debug("mySQL: Table created for item '{}' with datatype {} in SQL database.", itemName, mysqlType); - sqlTables.put(itemName, tableName); - } catch (Exception e) { - errCnt++; - logger.error("mySQL: Could not create table for item '{}' with statement '{}': {}", itemName, sqlCmd, - e.getMessage()); - } - - // Check if the new entry is in the table list - // If it's not in the list, then there was an error and we need to do some tidying up - // The item needs to be removed from the index table to avoid duplicates - if (sqlTables.get(itemName) == null) { - logger.error("mySQL: Item '{}' was not added to the table - removing index", itemName); - sqlCmd = new String("DELETE FROM Items WHERE ItemName=?"); - logger.debug("mySQL: query: {}", sqlCmd); - - try (PreparedStatement statement = connection.prepareStatement(sqlCmd);) { - statement.setString(1, itemName); - statement.executeUpdate(); - } catch (Exception e) { - errCnt++; - - logger.error("mySQL: Could not remove index for item '{}' with statement '{}': ", itemName, sqlCmd, e); - } - } - - return tableName; - } - - /** - * @{inheritDoc - */ - @Override - public void store(Item item, @Nullable String alias) { - // Don't log undefined/uninitialized data - if (item.getState() instanceof UnDefType) { - return; - } - - // If we've not initialized the bundle, then return - if (!initialized) { - return; - } - - // Connect to mySQL server if we're not already connected - if (!isConnected()) { - connectToDatabase(); - } - - // If we still didn't manage to connect, then return! - if (!isConnected()) { - logger.warn( - "mySQL: No connection to database. Cannot persist item '{}'! " - + "Will retry connecting to database when error count:{} equals errReconnectThreshold:{}", - item, errCnt, errReconnectThreshold); - return; - } - - // Get the table name for this item - String tableName = getTable(item); - if (tableName == null) { - logger.error("Unable to store item '{}'.", item.getName()); - return; - } - - // Do some type conversion to ensure we know the data type. - // This is necessary for items that have multiple types and may return their - // state in a format that's not preferred or compatible with the MySQL type. - // eg. DimmerItem can return OnOffType (ON, OFF), or PercentType (0-100). - // We need to make sure we cover the best type for serialisation. - String value; - if (item instanceof ColorItem) { - value = item.getStateAs(HSBType.class).toString(); - } else if (item instanceof RollershutterItem) { - value = item.getStateAs(PercentType.class).toString(); - } else { - /* - * !!ATTENTION!! - * - * 1. - * DimmerItem.getStateAs(PercentType.class).toString() always returns 0 - * RollershutterItem.getStateAs(PercentType.class).toString() works as expected - * - * 2. - * (item instanceof ColorItem) == (item instanceof DimmerItem) = true - * Therefore for instance tests ColorItem always has to be tested before DimmerItem - * - * !!ATTENTION!! - */ - - // All other items should return the best format by default - value = item.getState().toString(); - } - - // Get current timestamp - long timeNow = Calendar.getInstance().getTimeInMillis(); - Timestamp timestamp = new Timestamp(timeNow); - - String sqlCmd = null; - PreparedStatement statement = null; - try { - if (localtime) { - sqlCmd = new String( - "INSERT INTO " + tableName + " (TIME, VALUE) VALUES(?,?) ON DUPLICATE KEY UPDATE VALUE=?;"); - statement = connection.prepareStatement(sqlCmd); - statement.setTimestamp(1, timestamp); - statement.setString(2, value); - statement.setString(3, value); - } else { - sqlCmd = new String( - "INSERT INTO " + tableName + " (TIME, VALUE) VALUES(NOW(),?) ON DUPLICATE KEY UPDATE VALUE=?;"); - statement = connection.prepareStatement(sqlCmd); - statement.setString(1, value); - statement.setString(2, value); - } - - statement.executeUpdate(); - - logger.debug("mySQL: Stored item '{}' as '{}'[{}] in SQL database at {}.", item.getName(), - item.getState().toString(), value, timestamp.toString()); - logger.debug("mySQL: query: {}", sqlCmd); - - // Success - errCnt = 0; - } catch (Exception e) { - errCnt++; - - logger.error("mySQL: Could not store item '{}' in database with statement '{}': {}", item.getName(), sqlCmd, - e.getMessage()); - } finally { - if (statement != null) { - try { - statement.close(); - } catch (Exception hidden) { - } - } - } - } - - @Override - public void store(Item item) { - store(item, null); - } - - /** - * Checks if we have a database connection - * - * @return true if connection has been established, false otherwise - */ - private boolean isConnected() { - // Check if connection is valid - try { - if (connection != null && !connection.isValid(5000)) { - errCnt++; - logger.error("mySQL: Connection is not valid!"); - } - } catch (SQLException e) { - errCnt++; - - logger.error("mySQL: Error while checking connection.", e); - } - - // Error check. If we have 'errReconnectThreshold' errors in a row, then - // reconnect to the database - if (errReconnectThreshold != 0 && errCnt >= errReconnectThreshold) { - logger.error("mySQL: Error count exceeded {}. Disconnecting database.", errReconnectThreshold); - disconnectFromDatabase(); - } - return connection != null; - } - - /** - * Connects to the database - */ - private void connectToDatabase() { - try { - // Reset the error counter - errCnt = 0; - - logger.debug("mySQL: Attempting to connect to database {}", url); - Class.forName(driverClass).newInstance(); - connection = DriverManager.getConnection(url, user, password); - logger.debug("mySQL: Connected to database {}", url); - - int result; - try (Statement st = connection.createStatement()) { - result = st.executeUpdate("SHOW TABLES LIKE 'Items'"); - } - if (waitTimeout != -1) { - logger.debug("mySQL: Setting wait_timeout to {} seconds.", waitTimeout); - try (Statement st = connection.createStatement()) { - st.executeUpdate("SET SESSION wait_timeout=" + waitTimeout); - } - } - if (result == 0) { - try (Statement st = connection.createStatement()) { - st.executeUpdate( - "CREATE TABLE Items (ItemId INT NOT NULL AUTO_INCREMENT,ItemName VARCHAR(200) NOT NULL,PRIMARY KEY (ItemId));", - Statement.RETURN_GENERATED_KEYS); - } - } - - // Retrieve the table array - try (Statement st = connection.createStatement()) { - // Turn use of the cursor on. - st.setFetchSize(50); - try (ResultSet rs = st.executeQuery("SELECT ItemId, ItemName FROM Items")) { - while (rs.next()) { - sqlTables.put(rs.getString(2), "Item" + rs.getInt(1)); - } - } - } - } catch (Exception e) { - logger.error("mySQL: Failed connecting to the SQL database using: driverClass={}, url={}, user={}", - driverClass, url, user, e); - } - } - - /** - * Disconnects from the database - */ - private void disconnectFromDatabase() { - if (connection != null) { - try { - connection.close(); - logger.debug("mySQL: Disconnected from database {}", url); - } catch (Exception e) { - logger.error("mySQL: Failed disconnecting from the SQL database.", e); - } - connection = null; - } - } - - /** - * Formats the given alias by utilizing {@link Formatter}. - * - * @param alias - * the alias String which contains format strings - * @param values - * the values which will be replaced in the alias String - * - * @return the formatted value. All format strings are replaced by - * appropriate values - * @see java.util.Formatter for detailed information on format Strings. - */ - protected String formatAlias(String alias, Object... values) { - return String.format(alias, values); - } - - @Override - public Iterable query(FilterCriteria filter) { - if (!initialized) { - logger.debug("Query aborted on item {} - mySQL not initialised!", filter.getItemName()); - return Collections.emptyList(); - } - - if (!isConnected()) { - connectToDatabase(); - } - - if (!isConnected()) { - logger.debug("Query aborted on item {} - mySQL not connected!", filter.getItemName()); - return Collections.emptyList(); - } - - SimpleDateFormat mysqlDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - - // Get the item name from the filter - // Also get the Item object so we can determine the type - Item item = null; - String itemName = filter.getItemName(); - logger.debug("mySQL query: item is {}", itemName); - try { - if (itemRegistry != null) { - item = itemRegistry.getItem(itemName); - } - } catch (ItemNotFoundException e1) { - logger.error("Unable to get item type for {}", itemName); - - // Set type to null - data will be returned as StringType - item = null; - } - - if (item instanceof GroupItem) { - // For Group Items is BaseItem needed to get correct Type of Value. - item = GroupItem.class.cast(item).getBaseItem(); - } - - String table = sqlTables.get(itemName); - if (table == null) { - logger.error("mySQL: Unable to find table for query '{}'.", itemName); - return Collections.emptyList(); - } - - String filterString = new String(); - - if (filter.getBeginDate() != null) { - if (filterString.isEmpty()) { - filterString += " WHERE"; - } else { - filterString += " AND"; - } - filterString += " TIME>'" + mysqlDateFormat.format(filter.getBeginDate()) + "'"; - } - if (filter.getEndDate() != null) { - if (filterString.isEmpty()) { - filterString += " WHERE"; - } else { - filterString += " AND"; - } - filterString += " TIME<'" + mysqlDateFormat.format(filter.getEndDate().getTime()) + "'"; - } - - if (filter.getOrdering() == Ordering.ASCENDING) { - filterString += " ORDER BY Time ASC"; - } else { - filterString += " ORDER BY Time DESC"; - } - - if (filter.getPageSize() != 0x7fffffff) { - filterString += " LIMIT " + filter.getPageNumber() * filter.getPageSize() + "," + filter.getPageSize(); - } - - try { - long timerStart = System.currentTimeMillis(); - - // Retrieve the table array - Statement st = connection.createStatement(); - - String queryString = new String(); - queryString = "SELECT Time, Value FROM " + table; - if (!filterString.isEmpty()) { - queryString += filterString; - } - - logger.debug("mySQL: query: {}", queryString); - - // Turn use of the cursor on. - st.setFetchSize(50); - - ResultSet rs = st.executeQuery(queryString); - - long count = 0; - List items = new ArrayList<>(); - State state; - while (rs.next()) { - count++; - - if (item instanceof NumberItem) { - state = new DecimalType(rs.getDouble(2)); - } else if (item instanceof ColorItem) { - state = new HSBType(rs.getString(2)); - } else if (item instanceof DimmerItem) { - state = new PercentType(rs.getInt(2)); - } else if (item instanceof SwitchItem) { - state = OnOffType.valueOf(rs.getString(2)); - } else if (item instanceof ContactItem) { - state = OpenClosedType.valueOf(rs.getString(2)); - } else if (item instanceof RollershutterItem) { - state = new PercentType(rs.getInt(2)); - } else if (item instanceof DateTimeItem) { - Calendar calendar = Calendar.getInstance(); - calendar.setTimeInMillis(rs.getTimestamp(2).getTime()); - state = new DateTimeType(calendar); - } else { - state = new StringType(rs.getString(2)); - } - - MysqlItem mysqlItem = new MysqlItem(itemName, state, rs.getTimestamp(1)); - items.add(mysqlItem); - } - - rs.close(); - st.close(); - - long timerStop = System.currentTimeMillis(); - logger.debug("mySQL: query returned {} rows in {} ms", count, timerStop - timerStart); - - // Success - errCnt = 0; - - return items; - } catch (SQLException e) { - errCnt++; - logger.error("mySQL: Error running querying.", e); - } - return Collections.emptySet(); - } - - @Override - public Set getItemInfo() { - return Collections.emptySet(); - } - - @Override - public List getDefaultStrategies() { - return Collections.emptyList(); - } -} diff --git a/bundles/pom.xml b/bundles/pom.xml index e45b89d31ade8..f0e9e38e3bae6 100644 --- a/bundles/pom.xml +++ b/bundles/pom.xml @@ -23,7 +23,6 @@ org.openhab.persistence.jpa org.openhab.persistence.mapdb org.openhab.persistence.mongodb - org.openhab.persistence.mysql org.openhab.persistence.rrd4j diff --git a/features/openhab-addons-external/pom.xml b/features/openhab-addons-external/pom.xml index 7d59ca88fb2bc..61f567e7c1218 100644 --- a/features/openhab-addons-external/pom.xml +++ b/features/openhab-addons-external/pom.xml @@ -35,7 +35,6 @@ src/main/resources/conf/jdbc.cfgcfgjdbc src/main/resources/conf/jpa.cfgcfgjpa src/main/resources/conf/mapdb.cfgcfgmapdb - src/main/resources/conf/mysql.cfgcfgmysql src/main/resources/conf/rrd4j.cfgcfgrrd4j diff --git a/features/openhab-addons-external/src/main/resources/conf/mysql.cfg b/features/openhab-addons-external/src/main/resources/conf/mysql.cfg deleted file mode 100644 index 8229622f8ad38..0000000000000 --- a/features/openhab-addons-external/src/main/resources/conf/mysql.cfg +++ /dev/null @@ -1,19 +0,0 @@ -# the database url like 'jdbc:mysql://:/' (without quotes) -#url= - -# the database user -#user= - -# the database password -#password= - -# the reconnection counter -#reconnectCnt= - -# the connection timeout (in seconds) -#waitTimeout= - -# Use MySQL Server time to store item values (=false) or use openHAB Server time (=true). -# For new installations, its recommend to set "localtime=true". -# (optional, defaults to false) -#localtime=true From 18a6809dc9acedbc9f0e9515f068a60dcd43bf21 Mon Sep 17 00:00:00 2001 From: Kai Kreuzer Date: Sun, 5 Apr 2020 18:37:44 +0200 Subject: [PATCH 2/2] removed from bom Signed-off-by: Kai Kreuzer --- bom/openhab-addons/pom.xml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/bom/openhab-addons/pom.xml b/bom/openhab-addons/pom.xml index 68e0ff4939941..dbf2341a4c64e 100644 --- a/bom/openhab-addons/pom.xml +++ b/bom/openhab-addons/pom.xml @@ -46,11 +46,6 @@ org.openhab.persistence.mongodb ${project.version} - - org.openhab.addons.bundles - org.openhab.persistence.mysql - ${project.version} - org.openhab.addons.bundles org.openhab.persistence.rrd4j