Moved everything related to the properties to its own manager

Signed-off-by: Louis Vallat <louis@louis-vallat.xyz>
This commit is contained in:
Louis Vallat 2020-10-27 22:50:33 +01:00
parent 8f1ae7a5fe
commit 0fc84bd2a3
3 changed files with 90 additions and 64 deletions

View File

@ -4,8 +4,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import xyz.vallat.louis.MovieQuoteBot; import xyz.vallat.louis.MovieQuoteBot;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection; import java.sql.Connection;
import java.sql.DriverManager; import java.sql.DriverManager;
import java.sql.SQLException; import java.sql.SQLException;
@ -13,6 +11,7 @@ import java.sql.Statement;
import static xyz.vallat.louis.database.LanguageManager.importLanguageIfNeeded; import static xyz.vallat.louis.database.LanguageManager.importLanguageIfNeeded;
import static xyz.vallat.louis.database.LanguageManager.initializeLanguages; import static xyz.vallat.louis.database.LanguageManager.initializeLanguages;
import static xyz.vallat.louis.database.PropertyManager.initializeProperties;
public final class DBManager { public final class DBManager {
@ -34,7 +33,7 @@ public final class DBManager {
} }
// TODO: EXIT CODES AS ENUM // TODO: EXIT CODES AS ENUM
private static Connection getConnection() { public static Connection getConnection() {
try { try {
return DriverManager.getConnection("jdbc:" + CONNECTION_PREFIX + "://" + HOST + ":" + PORT + "/" return DriverManager.getConnection("jdbc:" + CONNECTION_PREFIX + "://" + HOST + ":" + PORT + "/"
+ DATABASE, USERNAME, PASSWORD); + DATABASE, USERNAME, PASSWORD);
@ -53,8 +52,7 @@ public final class DBManager {
public static void initDatabase() { public static void initDatabase() {
logger.debug("Initializing database if not done yet."); logger.debug("Initializing database if not done yet.");
Connection connection = getConnection(); try (Connection connection = getConnection()) {
try {
initializeProperties(connection); initializeProperties(connection);
initializeLanguages(connection); initializeLanguages(connection);
initializeFilm(connection); initializeFilm(connection);
@ -64,23 +62,6 @@ public final class DBManager {
} catch (SQLException e) { } catch (SQLException e) {
logger.error("An error happened while initializing the database. Reason: {}", e.getMessage()); logger.error("An error happened while initializing the database. Reason: {}", e.getMessage());
System.exit(5); System.exit(5);
} catch (NoSuchAlgorithmException | IOException e) {
e.printStackTrace();
}
}
private static void initializeProperties(Connection connection) throws SQLException {
logger.debug("Creating properties table.");
try (Statement stmt = connection.createStatement()) {
String query = "CREATE TABLE IF NOT EXISTS properties\n" +
"(\n" +
" id int GENERATED ALWAYS AS IDENTITY,\n" +
" app_key text NOT NULL,\n" +
" app_value text NOT NULL,\n" +
" PRIMARY KEY (id),\n" +
" UNIQUE (app_key)\n" +
");";
stmt.executeUpdate(query);
} }
} }

View File

@ -16,6 +16,9 @@ import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import static xyz.vallat.louis.database.PropertyManager.getPropertyValue;
import static xyz.vallat.louis.database.PropertyManager.saveProperty;
public final class LanguageManager { public final class LanguageManager {
private static final Logger logger = LoggerFactory.getLogger(LanguageManager.class.getCanonicalName()); private static final Logger logger = LoggerFactory.getLogger(LanguageManager.class.getCanonicalName());
@ -25,35 +28,22 @@ public final class LanguageManager {
private LanguageManager() { private LanguageManager() {
} }
public static void importLanguageIfNeeded(Connection connection) throws SQLException, IOException, NoSuchAlgorithmException { public static void importLanguageIfNeeded(Connection connection) {
String storedHash = "";
try {
logger.debug("Checking if we need to import languages again."); logger.debug("Checking if we need to import languages again.");
String storedHash = getStoredHash(connection); storedHash = getPropertyValue(HASH_KEY);
logger.debug("Stored hash was '{}'.", storedHash); logger.debug("Stored hash was '{}'.", storedHash);
String actualHash = getActualHash(); String actualHash = getActualHash();
logger.debug("Actual hash is '{}'.", actualHash); logger.debug("Actual hash is '{}'.", actualHash);
logger.info("Importing new language file."); logger.info("Importing new language file.");
if (!storedHash.equals(actualHash)) importLanguageFile(connection); if (!storedHash.equals(actualHash)) importLanguageFile(connection);
logger.debug("Saving new hash in database."); logger.debug("Saving new hash in database.");
saveNewHash(connection, actualHash); saveProperty(HASH_KEY, actualHash);
} } catch (SQLException | IOException | NoSuchAlgorithmException e) {
logger.error("Cannot update the languages right now. Reason: {}", e.getMessage());
private static void saveNewHash(Connection connection, String actualHash) throws SQLException { if (storedHash.isEmpty()) System.exit(7);
String query; logger.warn("Using language already in database. Please contact this bot's administrator to fix this issue.");
if (doesPropertyExist(connection, HASH_KEY)) query = "UPDATE properties SET app_value = ? WHERE app_key = ?;";
else query = "INSERT INTO properties(app_value, app_key) VALUES (?, ?)";
try (PreparedStatement stmt = connection.prepareStatement(query)) {
stmt.setString(1, actualHash);
stmt.setString(2, HASH_KEY);
stmt.execute();
}
}
private static boolean doesPropertyExist(Connection connection, String key) throws SQLException {
String query = "SELECT id FROM properties WHERE app_key=?;";
try (PreparedStatement stmt = connection.prepareStatement(query)){
stmt.setString(1, key);
stmt.execute();
return stmt.getResultSet().next();
} }
} }
@ -100,8 +90,8 @@ public final class LanguageManager {
} }
private static boolean isInDatabase(Connection connection, String alpha3b) throws SQLException { private static boolean isInDatabase(Connection connection, String alpha3b) throws SQLException {
String query = "SELECT id FROM languages WHERE alpha3_b = ?;"; String query = "SELECT 1 FROM languages WHERE alpha3_b = ?;";
try (PreparedStatement stmt = connection.prepareStatement(query)){ try (PreparedStatement stmt = connection.prepareStatement(query)) {
stmt.setString(1, alpha3b); stmt.setString(1, alpha3b);
stmt.execute(); stmt.execute();
return stmt.getResultSet().next(); return stmt.getResultSet().next();
@ -121,17 +111,6 @@ public final class LanguageManager {
} }
} }
private static String getStoredHash(Connection connection) throws SQLException {
logger.debug("Getting current hash");
String query = "SELECT app_value FROM properties WHERE app_key=?;";
try (PreparedStatement stmt = connection.prepareStatement(query)) {
stmt.setString(1, HASH_KEY);
stmt.execute();
if (stmt.getResultSet().next()) return stmt.getResultSet().getString(1);
else return "";
}
}
private static String getActualHash() throws NoSuchAlgorithmException, IOException { private static String getActualHash() throws NoSuchAlgorithmException, IOException {
logger.debug("Computing the actual language source file's hash."); logger.debug("Computing the actual language source file's hash.");
return getFileChecksum(MessageDigest.getInstance("MD5")); return getFileChecksum(MessageDigest.getInstance("MD5"));

View File

@ -0,0 +1,66 @@
package xyz.vallat.louis.database;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public final class PropertyManager {
private static final Logger logger = LoggerFactory.getLogger(PropertyManager.class.getCanonicalName());
private PropertyManager() {
}
public static void saveProperty(String key, String value) {
logger.debug("Saving property '{}' with value '{}'.", key, value);
try (Connection connection = DBManager.getConnection()) {
String query;
if (getPropertyValue(key) == null)
query = "UPDATE properties SET app_value = ? WHERE app_key = ?;";
else query = "INSERT INTO properties(app_value, app_key) VALUES (?, ?)";
try (PreparedStatement stmt = connection.prepareStatement(query)) {
stmt.setString(1, value);
stmt.setString(2, key);
stmt.execute();
}
} catch (SQLException e) {
logger.error("Cannot save properties right now. Reason: {}", e.getMessage());
}
}
public static String getPropertyValue(String key) {
logger.debug("Checking if property '{}' exists.", key);
String query = "SELECT app_value FROM properties WHERE app_key = ?;";
try (Connection connection = DBManager.getConnection()) {
try (PreparedStatement stmt = connection.prepareStatement(query)) {
stmt.setString(1, key);
stmt.execute();
if (stmt.getResultSet().next()) return stmt.getResultSet().getString(1);
}
return null;
} catch (SQLException e) {
logger.error("Cannot get property right now. Reason: {}.", e.getMessage());
System.exit(6);
}
return null;
}
public static void initializeProperties(Connection connection) throws SQLException {
logger.debug("Creating properties table.");
try (Statement stmt = connection.createStatement()) {
String query = "CREATE TABLE IF NOT EXISTS properties\n" +
"(\n" +
" id int GENERATED ALWAYS AS IDENTITY,\n" +
" app_key text NOT NULL,\n" +
" app_value text NOT NULL,\n" +
" PRIMARY KEY (id),\n" +
" UNIQUE (app_key)\n" +
");";
stmt.executeUpdate(query);
}
}
}