From 7fefa5f89c76a1b1ce9cf1424962e6f76bc670c2 Mon Sep 17 00:00:00 2001 From: Matthew Cech Date: Thu, 23 May 2019 01:12:32 -0700 Subject: [PATCH 01/11] = Made table name generic --- src/core/DatabaseDriver.java | 12 ++++++++++-- src/main/Superintendent.java | 22 +++++++++++----------- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/src/core/DatabaseDriver.java b/src/core/DatabaseDriver.java index be95113..eb4d499 100644 --- a/src/core/DatabaseDriver.java +++ b/src/core/DatabaseDriver.java @@ -28,14 +28,22 @@ public class DatabaseDriver driver = null; } + // Makes sure a table exists with the specified name. + // The keyName specifies the key column label, and the valueName specifies the value column label. + public void EnsureTableExists(String tableName, String keyName, String valueName) + { + // Require a global table if it doesn't exist already + driver.ExecuteStatement("CREATE TABLE IF NOT EXISTS " + tableName + " (" + keyName + " text PRIMARY KEY, " + valueName + " text);", null); + } + // Set up and create a table in the database public boolean Connect() { driver = new JDBCDriverSQLite(); driver.Connect(); - // Require a global table if it doesn't exist already - driver.ExecuteStatement("CREATE TABLE IF NOT EXISTS " + globalTableName + " (" + globalKeyName + " text PRIMARY KEY, " + globalValueName + " text);", null); + // Verify tables we want to use exist + EnsureTableExists(globalTableName, globalKeyName, globalValueName); // General table. Do not remove. return true; } diff --git a/src/main/Superintendent.java b/src/main/Superintendent.java index 84da5fc..7a93c29 100644 --- a/src/main/Superintendent.java +++ b/src/main/Superintendent.java @@ -68,6 +68,17 @@ public class Superintendent return true; } + // Only called once per command. Good for lazily updating. + // Happens just before the command / plugin runs. + public static boolean PerCommandUpkeepPre() + { + // Upkeep localization system's file monitoring + LocStrings.Upkeep(); + LocCommands.Upkeep(); + + return true; + } + // This is for stuff that we need to do on a regular basis, but don't // necessarily want running at all points in time. // Happens just after the command / plugin runs. @@ -81,15 +92,4 @@ public class Superintendent return true; } - - // Only called once per command. Good for lazily updating. - // Happens just before the command / plugin runs. - public static boolean PerCommandUpkeepPre() - { - // Upkeep localization system's file monitoring - LocStrings.Upkeep(); - LocCommands.Upkeep(); - - return true; - } } From 2ee17dcc7932ac12c7eb5e24fc311998273861cb Mon Sep 17 00:00:00 2001 From: Matthew Cech Date: Fri, 24 May 2019 00:08:12 -0700 Subject: [PATCH 02/11] = Database patching for thread safety (Should be non-issue but could be in the future) --- src/core/DatabaseDriver.java | 5 +++- src/core/DatabaseManager.java | 48 ++++++++++++++++++++++++----------- 2 files changed, 37 insertions(+), 16 deletions(-) diff --git a/src/core/DatabaseDriver.java b/src/core/DatabaseDriver.java index eb4d499..ee2b84a 100644 --- a/src/core/DatabaseDriver.java +++ b/src/core/DatabaseDriver.java @@ -40,7 +40,10 @@ public class DatabaseDriver public boolean Connect() { driver = new JDBCDriverSQLite(); - driver.Connect(); + if(driver.Connect() == false) + { + return false; + } // Verify tables we want to use exist EnsureTableExists(globalTableName, globalKeyName, globalValueName); // General table. Do not remove. diff --git a/src/core/DatabaseManager.java b/src/core/DatabaseManager.java index b1f72ec..d8afd5a 100644 --- a/src/core/DatabaseManager.java +++ b/src/core/DatabaseManager.java @@ -1,7 +1,6 @@ package core; -import java.util.ArrayList; - +import java.util.Vector; import utils.GlobalLog; import utils.LogFilter; @@ -11,11 +10,13 @@ public class DatabaseManager public static DatabaseManager instance = null; // Private internal variables - private ArrayList trackedObjects; + private Vector trackedObjects; private DatabaseDriver driver; public DatabaseManager() { + GlobalLog.Log(LogFilter.Database, "Creating database manager"); + if(instance == null) { instance = this; @@ -26,40 +27,57 @@ public class DatabaseManager return; } - trackedObjects = new ArrayList(); + trackedObjects = new Vector(); driver = new DatabaseDriver(); - driver.Connect(); + + if(driver.Connect() == false) + { + GlobalLog.Error("Database failed to connect. Currently, without the DB, this bot can not run."); + System.exit(1); + } } // Thumbs through registered objects and syncs them with the database. // Consider moving this operation to a separate thread. public void Upkeep() { - for(int i = 0 ; i < trackedObjects.size(); ++i) + synchronized(trackedObjects) { - DatabaseTrackedObject dto = trackedObjects.get(i); - - if(dto.IsDirty()) + for(int i = 0 ; i < trackedObjects.size(); ++i) { - SetRemoteValue(dto.identifier, dto.Serialize()); - dto.Resolve(); + DatabaseTrackedObject dto = trackedObjects.get(i); + + if(dto.IsDirty()) + { + SetRemoteValue(dto.identifier, dto.Serialize()); + dto.Resolve(); + } } } } public void Register(DatabaseTrackedObject tracked) { - trackedObjects.add(tracked); - tracked.DeSerialzie(GetRemoteValue(tracked.identifier)); + synchronized(trackedObjects) + { + trackedObjects.add(tracked); + tracked.DeSerialzie(GetRemoteValue(tracked.identifier)); + } } public String GetRemoteValue(String key) { - return driver.CreateGetKey(key); + synchronized(driver) + { + return driver.CreateGetKey(key); + } } public void SetRemoteValue(String key, String value) { - driver.CreateSetKey(key, value); + synchronized(driver) + { + driver.CreateSetKey(key, value); + } } } From 434ff1b46b5be0a27dd6cd1ce16b51b8b4f8fbae Mon Sep 17 00:00:00 2001 From: Matthew Cech Date: Fri, 24 May 2019 00:17:18 -0700 Subject: [PATCH 03/11] + Added database flush command --- src/commands/CommandDBFlush.java | 36 ++++++++++++++++++++++++++++++ src/core/DatabaseManager.java | 7 +++++- src/core/ObjectBuilderFactory.java | 6 ++++- 3 files changed, 47 insertions(+), 2 deletions(-) create mode 100644 src/commands/CommandDBFlush.java diff --git a/src/commands/CommandDBFlush.java b/src/commands/CommandDBFlush.java new file mode 100644 index 0000000..b50ccf9 --- /dev/null +++ b/src/commands/CommandDBFlush.java @@ -0,0 +1,36 @@ +package commands; + +import java.awt.Color; + +import core.Command; +import core.DatabaseManager; +import core.LocStrings; +import dataStructures.KittyChannel; +import dataStructures.KittyEmbed; +import dataStructures.KittyGuild; +import dataStructures.KittyRating; +import dataStructures.KittyRole; +import dataStructures.KittyUser; +import dataStructures.Response; +import dataStructures.UserInput; + +public class CommandDBFlush extends Command +{ + public CommandDBFlush(KittyRole level, KittyRating rating) { super(level, rating); } + + @Override + public String HelpText() { return LocStrings.Stub("DBFlushInfo"); } + + @Override + public void OnRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input, Response res) + { + int numUpdated = DatabaseManager.instance.Upkeep(); + + KittyEmbed embed = new KittyEmbed(); + embed.title = "Database queue flushed"; + embed.descriptionText = "flushed: " + numUpdated; + embed.color = new Color(7*16, 8*16, 9*16); + + res.CallEmbed(embed); + } +} diff --git a/src/core/DatabaseManager.java b/src/core/DatabaseManager.java index d8afd5a..54e4749 100644 --- a/src/core/DatabaseManager.java +++ b/src/core/DatabaseManager.java @@ -39,10 +39,12 @@ public class DatabaseManager // Thumbs through registered objects and syncs them with the database. // Consider moving this operation to a separate thread. - public void Upkeep() + public int Upkeep() { synchronized(trackedObjects) { + int numUpdated = 0; + for(int i = 0 ; i < trackedObjects.size(); ++i) { DatabaseTrackedObject dto = trackedObjects.get(i); @@ -51,8 +53,11 @@ public class DatabaseManager { SetRemoteValue(dto.identifier, dto.Serialize()); dto.Resolve(); + ++numUpdated; } } + + return numUpdated; } } diff --git a/src/core/ObjectBuilderFactory.java b/src/core/ObjectBuilderFactory.java index 92aeadb..785b2e6 100644 --- a/src/core/ObjectBuilderFactory.java +++ b/src/core/ObjectBuilderFactory.java @@ -328,22 +328,27 @@ public class ObjectBuilderFactory CommandManager manager = new CommandManager(commandEnabler); + // Dev manager.Register(LocCommands.Stub("work"), new CommandDoWork(KittyRole.Dev, KittyRating.Safe)); manager.Register(LocCommands.Stub("shutdown"), new CommandShutdown(KittyRole.Dev, KittyRating.Safe)); manager.Register(LocCommands.Stub("stats"), new CommandStats(KittyRole.Dev, KittyRating.Safe)); manager.Register(LocCommands.Stub("invite"), new CommandInvite(KittyRole.Dev, KittyRating.Safe)); manager.Register(LocCommands.Stub("buildHelp"), new CommandHelpBuilder(KittyRole.Dev, KittyRating.Safe)); manager.Register(LocCommands.Stub("tweet"), new CommandTweet(KittyRole.Dev, KittyRating.Safe)); + manager.Register(LocCommands.Stub("dbflush"), new CommandDBFlush(KittyRole.Dev, KittyRating.Safe)); + // Admin manager.Register(LocCommands.Stub("rating"), new CommandRating(KittyRole.Admin, KittyRating.Safe)); manager.Register(LocCommands.Stub("indicator"), new CommandChangeIndicator(KittyRole.Admin, KittyRating.Safe)); manager.Register(LocCommands.Stub("guildroleallowed"), new CommandGuildRoleAllowed(KittyRole.Admin, KittyRating.Safe)); manager.Register(LocCommands.Stub("guildrolenotallowed"), new CommandGuildRoleNotAllowed(KittyRole.Admin, KittyRating.Safe)); + // Mod manager.Register(LocCommands.Stub("poll"), new CommandPollManage(KittyRole.Mod, KittyRating.Safe)); manager.Register(LocCommands.Stub("givebeans"), new CommandGiveBeans(KittyRole.Mod, KittyRating.Safe)); manager.Register(LocCommands.Stub("rpg"), new CommandRPG(KittyRole.Mod, KittyRating.Safe)); + // General manager.Register(LocCommands.Stub("fetch"), new CommandFetch(KittyRole.General, KittyRating.Safe)); manager.Register(LocCommands.Stub("guildroleadd"), new CommandGuildRoleAdd(KittyRole.General, KittyRating.Safe)); manager.Register(LocCommands.Stub("guildroleremove"), new CommandGuildRoleRemove(KittyRole.General, KittyRating.Safe)); @@ -375,7 +380,6 @@ public class ObjectBuilderFactory manager.Register(LocCommands.Stub("guildrolelist"), new CommandGuildRoleList(KittyRole.General, KittyRating.Safe)); manager.Register(LocCommands.Stub("bethistory"), new CommandBetHistory(KittyRole.General, KittyRating.Safe)); manager.Register(LocCommands.Stub("crouton"), new CommandCrouton(KittyRole.General, KittyRating.Safe)); - manager.Register(LocCommands.Stub("benchmark, bench"), new CommandBenchmark(KittyRole.General, KittyRating.Safe)); return manager; From 634d67917f15587aa520de0d9c38adb1fcab3f5b Mon Sep 17 00:00:00 2001 From: Matthew Cech Date: Fri, 24 May 2019 00:39:07 -0700 Subject: [PATCH 04/11] = Updated DB info --- commands.config | 2 ++ locCommands.config | 2 ++ locStrings.config | 6 +++++ src/commands/CommandCrouton.java | 2 +- src/commands/CommandDBFlush.java | 2 +- src/commands/CommandDBStats.java | 43 ++++++++++++++++++++++++++++++ src/core/DatabaseManager.java | 15 +++++++++++ src/core/ObjectBuilderFactory.java | 1 + 8 files changed, 71 insertions(+), 2 deletions(-) create mode 100644 src/commands/CommandDBStats.java diff --git a/commands.config b/commands.config index 63fd985..fe343af 100644 --- a/commands.config +++ b/commands.config @@ -45,3 +45,5 @@ guildrolelist=1 benchmark, bench=1 bethistory=1 crouton=1 +dbstats=1 +dbflush=1 diff --git a/locCommands.config b/locCommands.config index d71456e..5ef2ec1 100644 --- a/locCommands.config +++ b/locCommands.config @@ -20,6 +20,7 @@ perish, thenperish= teey= guildrolelist= stats= +dbstats= beans= eightball, 8ball= catch= @@ -43,6 +44,7 @@ buildHelp= fetch= crouton= invite= +dbflush= shutdown= diff --git a/locStrings.config b/locStrings.config index 14e8611..23c4205 100644 --- a/locStrings.config +++ b/locStrings.config @@ -138,6 +138,9 @@ RatingWarning=Warning: NSFW may slip through, images are only based on tags on t RatingChanged=Kittybot content set to RatingInvalid=Invalid content rating +[CommandDBStats] +DBStatsInfo= + [CommandGiveBeans] GiveBeansNoneMentioned=You didn't mention anyone! GiveBeansSuccess=Gave %s %s beans! @@ -229,6 +232,9 @@ WolframError=Something went wrong! WolframInfo=Will query wolframalpha with your question and give a full image output of the answer WolframNoArgs=You need to provide some arguments! +[CommandDBFlush] +DBFlushInfo= + [CommandMap] MapInfo=Generates a map! You can pass additional information if you want with the flags `-s-w-h`. If one of the fields isn't provided, its default will be used. Note that adjusting the width and height impacts the map outcomes.\n\nDefault seed: Random,\nDefault Width: 35(max %s),\nDefault Height: 25(max %s) MapSeed=Seed diff --git a/src/commands/CommandCrouton.java b/src/commands/CommandCrouton.java index e86d47c..e08821c 100644 --- a/src/commands/CommandCrouton.java +++ b/src/commands/CommandCrouton.java @@ -13,7 +13,7 @@ import dataStructures.KittyUser; import dataStructures.Response; import dataStructures.UserInput; -public class CommandCrouton extends Command +public class CommandCrouton extends Command { public CommandCrouton(KittyRole level, KittyRating rating) { super(level, rating); } diff --git a/src/commands/CommandDBFlush.java b/src/commands/CommandDBFlush.java index b50ccf9..484ac61 100644 --- a/src/commands/CommandDBFlush.java +++ b/src/commands/CommandDBFlush.java @@ -28,7 +28,7 @@ public class CommandDBFlush extends Command KittyEmbed embed = new KittyEmbed(); embed.title = "Database queue flushed"; - embed.descriptionText = "flushed: " + numUpdated; + embed.descriptionText = "**Dirty:** " + numUpdated; embed.color = new Color(7*16, 8*16, 9*16); res.CallEmbed(embed); diff --git a/src/commands/CommandDBStats.java b/src/commands/CommandDBStats.java new file mode 100644 index 0000000..ae8c012 --- /dev/null +++ b/src/commands/CommandDBStats.java @@ -0,0 +1,43 @@ +package commands; + +import java.awt.Color; +import java.text.DateFormat; +import java.text.SimpleDateFormat; + +import core.Command; +import core.DatabaseManager; +import core.LocStrings; +import dataStructures.KittyChannel; +import dataStructures.KittyEmbed; +import dataStructures.KittyGuild; +import dataStructures.KittyRating; +import dataStructures.KittyRole; +import dataStructures.KittyUser; +import dataStructures.Response; +import dataStructures.UserInput; + +public class CommandDBStats extends Command +{ + DateFormat dateFormat; + public CommandDBStats(KittyRole level, KittyRating rating) + { + super(level, rating); + dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + } + + @Override + public String HelpText() { return LocStrings.Stub("DBStatsInfo"); } + + @Override + public void OnRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input, Response res) + { + KittyEmbed embed = new KittyEmbed(); + embed.title = "Database Info"; + embed.descriptionText = "**Tracked Items:** " + DatabaseManager.instance.GetTrackedObjectsSize(); + embed.descriptionText += "\n"; + embed.descriptionText += "**Last Upkeep:** " + dateFormat.format(DatabaseManager.instance.GetLastUpkeep()) + " UTC-7"; + embed.color = new Color(7*16, 8*16, 9*16); + + res.CallEmbed(embed); + } +} diff --git a/src/core/DatabaseManager.java b/src/core/DatabaseManager.java index 54e4749..638fe2b 100644 --- a/src/core/DatabaseManager.java +++ b/src/core/DatabaseManager.java @@ -1,5 +1,6 @@ package core; +import java.util.Date; import java.util.Vector; import utils.GlobalLog; import utils.LogFilter; @@ -12,6 +13,7 @@ public class DatabaseManager // Private internal variables private Vector trackedObjects; private DatabaseDriver driver; + private Date lastUpkeep; public DatabaseManager() { @@ -27,6 +29,7 @@ public class DatabaseManager return; } + lastUpkeep = new Date(); trackedObjects = new Vector(); driver = new DatabaseDriver(); @@ -57,6 +60,8 @@ public class DatabaseManager } } + lastUpkeep = new Date(); + return numUpdated; } } @@ -85,4 +90,14 @@ public class DatabaseManager driver.CreateSetKey(key, value); } } + + public Date GetLastUpkeep() + { + return lastUpkeep; + } + + public int GetTrackedObjectsSize() + { + return trackedObjects.size(); + } } diff --git a/src/core/ObjectBuilderFactory.java b/src/core/ObjectBuilderFactory.java index 785b2e6..63ffa4c 100644 --- a/src/core/ObjectBuilderFactory.java +++ b/src/core/ObjectBuilderFactory.java @@ -336,6 +336,7 @@ public class ObjectBuilderFactory manager.Register(LocCommands.Stub("buildHelp"), new CommandHelpBuilder(KittyRole.Dev, KittyRating.Safe)); manager.Register(LocCommands.Stub("tweet"), new CommandTweet(KittyRole.Dev, KittyRating.Safe)); manager.Register(LocCommands.Stub("dbflush"), new CommandDBFlush(KittyRole.Dev, KittyRating.Safe)); + manager.Register(LocCommands.Stub("dbstats"), new CommandDBStats(KittyRole.Dev, KittyRating.Safe)); // Admin manager.Register(LocCommands.Stub("rating"), new CommandRating(KittyRole.Admin, KittyRating.Safe)); From 9e9759394edc0956b4699bc74daf7f09280762c4 Mon Sep 17 00:00:00 2001 From: Matthew Cech Date: Fri, 24 May 2019 01:06:11 -0700 Subject: [PATCH 05/11] = Statement type updates --- src/core/DatabaseDriver.java | 6 ++++-- src/network/JDBCDriverSQLite.java | 3 +++ src/network/JDBCStatementType.java | 25 +++++++++++++++++++++++++ 3 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 src/network/JDBCStatementType.java diff --git a/src/core/DatabaseDriver.java b/src/core/DatabaseDriver.java index ee2b84a..83fd0eb 100644 --- a/src/core/DatabaseDriver.java +++ b/src/core/DatabaseDriver.java @@ -87,7 +87,8 @@ public class DatabaseDriver private void UpdateKey(String key, String value) { String command = "UPDATE " + globalTableName + " SET " + globalValueName + " = ? WHERE " + globalKeyName + " = ?;"; - driver.ExecuteStatement(command, new String[] { key, value }); + boolean status = driver.ExecuteStatement(command, new String[] { key, value }); + GlobalLog.Log(LogFilter.Database, "UpdateKey status: " + status); } // Protoype updating for seeing if a key exists @@ -111,7 +112,8 @@ public class DatabaseDriver private void CreateKey(String key, String value) { String command = "INSERT INTO " + globalTableName + " (GlobalKey, GlobalValue) VALUES (?, ?);"; - driver.ExecuteStatement(command, new String[] { key, value }); + boolean status = driver.ExecuteStatement(command, new String[] { key, value }); + GlobalLog.Log(LogFilter.Database, "CreateKey status: " + status); } // Transforms a result into a string if possible. diff --git a/src/network/JDBCDriverSQLite.java b/src/network/JDBCDriverSQLite.java index 98a9688..ef3115a 100644 --- a/src/network/JDBCDriverSQLite.java +++ b/src/network/JDBCDriverSQLite.java @@ -7,6 +7,8 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; + +import jdk.nashorn.internal.runtime.logging.DebugLogger; import utils.GlobalLog; import utils.LogFilter; @@ -119,6 +121,7 @@ public class JDBCDriverSQLite extends JDBCDriver if(args != null && args.length > 0) { PreparedStatement statement = connection.prepareStatement(command); + GlobalLog.Log("COMMAND" + command); for(int i = 0; i < args.length; ++i) statement.setString(i + 1, args[i]); diff --git a/src/network/JDBCStatementType.java b/src/network/JDBCStatementType.java new file mode 100644 index 0000000..2e08c33 --- /dev/null +++ b/src/network/JDBCStatementType.java @@ -0,0 +1,25 @@ +package network; + +import java.util.Arrays; +import java.util.Optional; + +public enum JDBCStatementType +{ + Insert (0), Update(1), Select(2); + + private final int value; + private JDBCStatementType(int value) + { + this.value = value; + } + + public int getValue() + { + return value; + } + + public static Optional valueOf(int value) + { + return Arrays.stream(values()).filter(role -> role.value == value).findFirst(); + } +} From 5dd8821d51486558a328430cab14fc0a80e31796 Mon Sep 17 00:00:00 2001 From: Matthew Cech Date: Fri, 24 May 2019 01:35:04 -0700 Subject: [PATCH 06/11] = Updated Update statement --- src/core/DatabaseDriver.java | 19 ++++++----- src/dataStructures/KittyRole.java | 8 ++--- src/network/JDBCDriver.java | 4 +-- src/network/JDBCDriverMySQL.java | 4 +-- src/network/JDBCDriverPostgreSQL.java | 4 +-- src/network/JDBCDriverSQLite.java | 47 ++++++++++++++++++++++----- src/network/JDBCStatementType.java | 2 +- 7 files changed, 60 insertions(+), 28 deletions(-) diff --git a/src/core/DatabaseDriver.java b/src/core/DatabaseDriver.java index 83fd0eb..b751e32 100644 --- a/src/core/DatabaseDriver.java +++ b/src/core/DatabaseDriver.java @@ -5,6 +5,7 @@ import java.sql.SQLException; import network.JDBCDriver; import network.JDBCDriverSQLite; +import network.JDBCStatementType; import utils.GlobalLog; import utils.LogFilter; @@ -33,7 +34,7 @@ public class DatabaseDriver public void EnsureTableExists(String tableName, String keyName, String valueName) { // Require a global table if it doesn't exist already - driver.ExecuteStatement("CREATE TABLE IF NOT EXISTS " + tableName + " (" + keyName + " text PRIMARY KEY, " + valueName + " text);", null); + driver.ExecuteStatement(JDBCStatementType.Create, "CREATE TABLE IF NOT EXISTS " + tableName + " (" + keyName + " text PRIMARY KEY, " + valueName + " text)", null); } // Set up and create a table in the database @@ -86,16 +87,16 @@ public class DatabaseDriver // Prototype formatting for key updating private void UpdateKey(String key, String value) { - String command = "UPDATE " + globalTableName + " SET " + globalValueName + " = ? WHERE " + globalKeyName + " = ?;"; - boolean status = driver.ExecuteStatement(command, new String[] { key, value }); + String command = "UPDATE " + globalTableName + " SET " + globalValueName + " = ? WHERE " + globalKeyName + " = ?"; + boolean status = driver.ExecuteStatement(JDBCStatementType.Update, command, new String[] { value, key }); GlobalLog.Log(LogFilter.Database, "UpdateKey status: " + status); } // Protoype updating for seeing if a key exists private boolean HasKey(String key) { - String command = "SELECT COUNT(1) as count FROM " + globalTableName + " WHERE " + globalKeyName + " = ?;"; - ResultSet set = driver.ExecuteReturningStatement(command, new String[] { key }); + String command = "SELECT COUNT(1) as count FROM " + globalTableName + " WHERE " + globalKeyName + " = ?"; + ResultSet set = driver.ExecuteReturningStatement(JDBCStatementType.Select, command, new String[] { key }); String out = ResultAsString(set, "count"); return out.charAt(0) == '1'; } @@ -103,16 +104,16 @@ public class DatabaseDriver // Prototype for getting a key private String GetKey(String key) { - String command = "SELECT " + globalValueName + " as searchedKey FROM " + globalTableName +" WHERE " + globalKeyName + " = ?;"; - ResultSet set = driver.ExecuteReturningStatement(command, new String[] { key }); + String command = "SELECT " + globalValueName + " as searchedKey FROM " + globalTableName +" WHERE " + globalKeyName + " = ?"; + ResultSet set = driver.ExecuteReturningStatement(JDBCStatementType.Select, command, new String[] { key }); return ResultAsString(set, "searchedKey"); } // Prototype for creating a key private void CreateKey(String key, String value) { - String command = "INSERT INTO " + globalTableName + " (GlobalKey, GlobalValue) VALUES (?, ?);"; - boolean status = driver.ExecuteStatement(command, new String[] { key, value }); + String command = "INSERT INTO " + globalTableName + " (GlobalKey, GlobalValue) VALUES (?, ?)"; + boolean status = driver.ExecuteStatement(JDBCStatementType.Insert, command, new String[] { key, value }); GlobalLog.Log(LogFilter.Database, "CreateKey status: " + status); } diff --git a/src/dataStructures/KittyRole.java b/src/dataStructures/KittyRole.java index baec91c..edda23e 100644 --- a/src/dataStructures/KittyRole.java +++ b/src/dataStructures/KittyRole.java @@ -18,8 +18,8 @@ public enum KittyRole return value; } - public static Optional valueOf(int value) - { - return Arrays.stream(values()).filter(role -> role.value == value).findFirst(); - } + public static Optional valueOf(int value) + { + return Arrays.stream(values()).filter(role -> role.value == value).findFirst(); + } } diff --git a/src/network/JDBCDriver.java b/src/network/JDBCDriver.java index 639c1dd..bd99ee1 100644 --- a/src/network/JDBCDriver.java +++ b/src/network/JDBCDriver.java @@ -15,6 +15,6 @@ public abstract class JDBCDriver // Executes a SQL command with the database. Returns if it was executed successfully, or in the // case of the returning statement, returns the ResultSet. Args are placed into the prepared statement // in place of each '?' places into it. - public abstract boolean ExecuteStatement(String command, String[] args); - public abstract ResultSet ExecuteReturningStatement(String command, String[] args); + public abstract boolean ExecuteStatement(JDBCStatementType type, String command, String[] args); + public abstract ResultSet ExecuteReturningStatement(JDBCStatementType type, String command, String[] args); } diff --git a/src/network/JDBCDriverMySQL.java b/src/network/JDBCDriverMySQL.java index 2a29596..5fbb404 100644 --- a/src/network/JDBCDriverMySQL.java +++ b/src/network/JDBCDriverMySQL.java @@ -17,13 +17,13 @@ public class JDBCDriverMySQL extends JDBCDriver } @Override - public boolean ExecuteStatement(String statement, String[] args) { + public boolean ExecuteStatement(JDBCStatementType type, String statement, String[] args) { // TODO Auto-generated method stub return false; } @Override - public ResultSet ExecuteReturningStatement(String statement, String[] args) { + public ResultSet ExecuteReturningStatement(JDBCStatementType type, String statement, String[] args) { // TODO Auto-generated method stub return null; } diff --git a/src/network/JDBCDriverPostgreSQL.java b/src/network/JDBCDriverPostgreSQL.java index 823530a..b6765eb 100644 --- a/src/network/JDBCDriverPostgreSQL.java +++ b/src/network/JDBCDriverPostgreSQL.java @@ -17,13 +17,13 @@ public class JDBCDriverPostgreSQL extends JDBCDriver } @Override - public boolean ExecuteStatement(String statement, String[] args) { + public boolean ExecuteStatement(JDBCStatementType type, String statement, String[] args) { // TODO Auto-generated method stub return false; } @Override - public ResultSet ExecuteReturningStatement(String statement, String[] args) { + public ResultSet ExecuteReturningStatement(JDBCStatementType type, String statement, String[] args) { // TODO Auto-generated method stub return null; } diff --git a/src/network/JDBCDriverSQLite.java b/src/network/JDBCDriverSQLite.java index ef3115a..56c4bac 100644 --- a/src/network/JDBCDriverSQLite.java +++ b/src/network/JDBCDriverSQLite.java @@ -66,7 +66,7 @@ public class JDBCDriverSQLite extends JDBCDriver } @Override - public ResultSet ExecuteReturningStatement(String command, String[] args) + public ResultSet ExecuteReturningStatement(JDBCStatementType type, String command, String[] args) { if(connection == null) return null; @@ -79,11 +79,21 @@ public class JDBCDriverSQLite extends JDBCDriver if(args != null && args.length > 0) { PreparedStatement statement = connection.prepareStatement(command); + ResultSet set = null; for(int i = 0; i < args.length; ++i) statement.setString(i + 1, args[i]); - ResultSet set = statement.executeQuery(); + switch(type) + { + case Select: + set = statement.executeQuery(); + break; + + default: + throw new Exception("Unsupported statement type for this function!"); + } + return set; } else @@ -93,7 +103,7 @@ public class JDBCDriverSQLite extends JDBCDriver return set; } } - catch (SQLException e) + catch (Exception e) { try { @@ -108,7 +118,7 @@ public class JDBCDriverSQLite extends JDBCDriver } } - public boolean ExecuteStatement(String command, String[] args) + public boolean ExecuteStatement(JDBCStatementType type, String command, String[] args) { if(connection == null) return false; @@ -120,13 +130,34 @@ public class JDBCDriverSQLite extends JDBCDriver { if(args != null && args.length > 0) { + boolean executed = false; PreparedStatement statement = connection.prepareStatement(command); - GlobalLog.Log("COMMAND" + command); + //GlobalLog.Log("COMMAND IS -- " + command); for(int i = 0; i < args.length; ++i) + { + //GlobalLog.Log("Args: " + args[i]); statement.setString(i + 1, args[i]); - - boolean executed = statement.execute(); + } + + switch(type) + { + case Create: + executed = statement.executeUpdate() == 1; + break; + + case Update: + executed = statement.executeUpdate() == 1; + break; + + case Insert: + executed = statement.executeUpdate() == 1; + break; + + default: + throw new Exception("Unsupported statement type for this function!"); + } + return executed; } else @@ -136,7 +167,7 @@ public class JDBCDriverSQLite extends JDBCDriver return executed; } } - catch (SQLException e) + catch (Exception e) { try { diff --git a/src/network/JDBCStatementType.java b/src/network/JDBCStatementType.java index 2e08c33..96aa884 100644 --- a/src/network/JDBCStatementType.java +++ b/src/network/JDBCStatementType.java @@ -5,7 +5,7 @@ import java.util.Optional; public enum JDBCStatementType { - Insert (0), Update(1), Select(2); + Insert (0), Update(1), Select(2), Create(4); private final int value; private JDBCStatementType(int value) From 25c3327651576cdc635531856cb5c14e45b20567 Mon Sep 17 00:00:00 2001 From: Matthew Cech Date: Fri, 24 May 2019 01:46:51 -0700 Subject: [PATCH 07/11] = Cleaned up warnings and added config header --- commands.config | 1 + src/core/CommandEnabler.java | 5 +++++ src/network/JDBCDriverSQLite.java | 2 -- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/commands.config b/commands.config index fe343af..54d7a91 100644 --- a/commands.config +++ b/commands.config @@ -1,3 +1,4 @@ +[CommandEnabler] indicator=1 boop=1 tony, stark, dontfeelgood, dontfeelsogood=1 diff --git a/src/core/CommandEnabler.java b/src/core/CommandEnabler.java index a45f047..e39eed3 100644 --- a/src/core/CommandEnabler.java +++ b/src/core/CommandEnabler.java @@ -18,6 +18,7 @@ import utils.LogFilter; public class CommandEnabler { // Config/const variables + public static final String header = "[CommandEnabler]"; // For consistency in files public static final String filename = "commands.config"; public static final String pairSplit = "="; public static final char pairSeparator = '\n'; @@ -51,6 +52,9 @@ public class CommandEnabler for(int i = 0; i < lines.length; ++i) { + if(lines[i].contains(header)) + continue; + String[] pair = lines[i].split(pairSplit); if(pair.length < 2) @@ -92,6 +96,7 @@ public class CommandEnabler try { String outString = ""; + outString += header + pairSeparator; for(int i = 0; i < keyList.size(); ++i) { String key = keyList.get(i); diff --git a/src/network/JDBCDriverSQLite.java b/src/network/JDBCDriverSQLite.java index 56c4bac..8fc64ee 100644 --- a/src/network/JDBCDriverSQLite.java +++ b/src/network/JDBCDriverSQLite.java @@ -7,8 +7,6 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; - -import jdk.nashorn.internal.runtime.logging.DebugLogger; import utils.GlobalLog; import utils.LogFilter; From 6cf5a03186fe4556dd1e85b4c72d5d0e96af4d87 Mon Sep 17 00:00:00 2001 From: Matthew Cech Date: Fri, 24 May 2019 02:01:28 -0700 Subject: [PATCH 08/11] = Updated naming and created base class stub for kv pair file --- src/core/BaseKeyValueFile.java | 6 ++++++ src/core/{LocBase.java => BaseLocFile.java} | 4 ++-- src/core/CommandEnabler.java | 9 +++++++-- src/core/LocCommands.java | 2 +- src/core/LocStrings.java | 2 +- src/core/Settings.java | 5 +++++ src/utils/FileUtils.java | 9 +++++++++ src/utils/GlobalLog.java | 6 +++++- 8 files changed, 36 insertions(+), 7 deletions(-) create mode 100644 src/core/BaseKeyValueFile.java rename src/core/{LocBase.java => BaseLocFile.java} (98%) create mode 100644 src/core/Settings.java diff --git a/src/core/BaseKeyValueFile.java b/src/core/BaseKeyValueFile.java new file mode 100644 index 0000000..febb891 --- /dev/null +++ b/src/core/BaseKeyValueFile.java @@ -0,0 +1,6 @@ +package core; + +public class BaseKeyValueFile +{ + +} diff --git a/src/core/LocBase.java b/src/core/BaseLocFile.java similarity index 98% rename from src/core/LocBase.java rename to src/core/BaseLocFile.java index 15f6c8f..261eb16 100644 --- a/src/core/LocBase.java +++ b/src/core/BaseLocFile.java @@ -17,7 +17,7 @@ import utils.io.MonitoredFile; // A quick-and-dirty localization tool that scrapes the project for calls to itself, then // generates/updates a file externally with all the stub values as keys that are localized. -public abstract class LocBase +public abstract class BaseLocFile { // Pre-defined values public static final String KittySourceDirectory = "./src"; @@ -38,7 +38,7 @@ public abstract class LocBase protected FileMonitor fileMonitor; // Ok... so this is an array because if it's not an array, the parser will parse the string - public LocBase(String filename, String functionName) + public BaseLocFile(String filename, String functionName) { this.filename = filename; this.functionName = functionName; diff --git a/src/core/CommandEnabler.java b/src/core/CommandEnabler.java index e39eed3..3e78bd6 100644 --- a/src/core/CommandEnabler.java +++ b/src/core/CommandEnabler.java @@ -15,10 +15,11 @@ import utils.LogFilter; // commands that are being looked up will behave slightly differently so trimming // rules for this file are different than the localization ones - this is more // aggresive with whitespace removal. -public class CommandEnabler +public class CommandEnabler extends BaseKeyValueFile { // Config/const variables - public static final String header = "[CommandEnabler]"; // For consistency in files + public static final String headerStart = "["; + public static final String headerEnd = "]"; public static final String filename = "commands.config"; public static final String pairSplit = "="; public static final char pairSeparator = '\n'; @@ -29,13 +30,17 @@ public class CommandEnabler // Local variables private HashMap enabledMap; // Quick lookup private ArrayList keyList; // Tracking ordering for later + private final String header; public CommandEnabler() { + // Create/Init variables GlobalLog.Log(LogFilter.Core, "Initializing " + this.getClass().getSimpleName()); enabledMap = new HashMap<>(); keyList = new ArrayList<>(); + header = headerStart + this.getClass().getSimpleName() + headerEnd; + // Startup ReadIn(); GetTrackedCommands(); WriteOut(); diff --git a/src/core/LocCommands.java b/src/core/LocCommands.java index 7d75228..6d5b9bd 100644 --- a/src/core/LocCommands.java +++ b/src/core/LocCommands.java @@ -8,7 +8,7 @@ import dataStructures.Pair; // Performs the same localization for the strings associated with command names as // is performed with general strings in the application -public class LocCommands extends LocBase +public class LocCommands extends BaseLocFile { public static final String fileName = "locCommands.config"; public static final String function = "LocCommands.Stub"; diff --git a/src/core/LocStrings.java b/src/core/LocStrings.java index d4a0bd0..7b95573 100644 --- a/src/core/LocStrings.java +++ b/src/core/LocStrings.java @@ -7,7 +7,7 @@ import utils.io.FileMonitor; // A quick-and-dirty localization tool that scrapes the project for calls to itself, then // generates/updates a file externally (phrases.config) with all the stub values as keys that // can then be localized. -public class LocStrings extends LocBase +public class LocStrings extends BaseLocFile { public static final String fileName = "locStrings.config"; public static final String function = "LocStrings.Stub"; diff --git a/src/core/Settings.java b/src/core/Settings.java new file mode 100644 index 0000000..9ffdf42 --- /dev/null +++ b/src/core/Settings.java @@ -0,0 +1,5 @@ +package core; + +public class Settings { + +} diff --git a/src/utils/FileUtils.java b/src/utils/FileUtils.java index 97fe636..04ce890 100644 --- a/src/utils/FileUtils.java +++ b/src/utils/FileUtils.java @@ -11,6 +11,15 @@ import java.util.stream.Stream; public class FileUtils { + public static void CreateDirectoryIfDoesntExist(String directoryName) + { + File directory = new File(directoryName); + + if (! directory.exists()){ + directory.mkdir(); + } + } + // Reads all lines from a file as a string public static String ReadContent(File file) { return ReadContent(file.toPath()); } public static String ReadContent(Path filePath) diff --git a/src/utils/GlobalLog.java b/src/utils/GlobalLog.java index 5914d59..171bb03 100644 --- a/src/utils/GlobalLog.java +++ b/src/utils/GlobalLog.java @@ -9,6 +9,7 @@ import java.util.Date; public class GlobalLog { + private static final String directory = "logs/"; private static final String log = "Log"; private static final String warn = "Warning"; private static final String error = "ERROR"; @@ -19,7 +20,10 @@ public class GlobalLog { DateFormat dF = new SimpleDateFormat("yyyy_MM_dd_HH-mm"); Date today = new Date(); - outputLog = new PrintWriter((dF.format(today) + ".log"), "UTF-8"); + + FileUtils.CreateDirectoryIfDoesntExist(directory); + outputLog = new PrintWriter(directory + (dF.format(today) + ".log"), "UTF-8"); + GlobalLog.Log(LogFilter.Util, "Finished initializing logging system"); } private static void Write(String status, LogFilter filter, String body) From ad6def8e93762ee0a076d326ac75b75097fcf131 Mon Sep 17 00:00:00 2001 From: Matthew Cech Date: Fri, 24 May 2019 02:31:09 -0700 Subject: [PATCH 09/11] = Base commands config class, and command standardization --- commands.config | 87 +++++++++++----------- src/core/BaseKeyValueFile.java | 86 +++++++++++++++++++++- src/core/BaseLocFile.java | 4 +- src/core/CommandEnabler.java | 93 +++++++++--------------- src/core/benchmark/BenchmarkManager.java | 2 +- src/utils/GlobalLog.java | 2 + src/utils/io/DirectoryMonitor.java | 2 - src/utils/io/FileMonitor.java | 2 - src/utils/{ => io}/FileUtils.java | 5 +- 9 files changed, 170 insertions(+), 113 deletions(-) rename src/utils/{ => io}/FileUtils.java (96%) diff --git a/commands.config b/commands.config index 54d7a91..ab5a939 100644 --- a/commands.config +++ b/commands.config @@ -1,50 +1,49 @@ [CommandEnabler] -indicator=1 -boop=1 -tony, stark, dontfeelgood, dontfeelsogood=1 -yeet=1 -role=1 -ping=1 -rating=1 -roll=1 -blur=1 -choose=1 -poll=1 -rpstart=1 -bet=1 -perish, thenperish=1 -teey=1 -stats=1 beans=1 -eightball, 8ball=1 -vote=1 -results=1 -wolfram=1 -map=1 -info, about=1 -givebeans=1 +benchmark, bench=1 +bet=1 +bethistory=1 +blur=1 +boop=1 +buildhelp=1 +buildhelp=1 c++, g++, cplus, cpp=1 -work=1 -showpoll=1 -rpend=1 -rpg=1 -tweet=1 -java, jdoodle=1 -help=1 -buildHelp=1 -invite=1 -shutdown=1 -addguildrole=1 -allowedguildrole=1 -guildroleremove=1 +catch=1 +choose=1 +crouton=1 +dbflush=1 +dbstats=1 +eightball, 8ball=1 +fetch=1 +givebeans=1 guildroleadd=1 guildroleallowed=1 -fetch=1 -guildrolenotallowed=1 -catch=1 guildrolelist=1 -benchmark, bench=1 -bethistory=1 -crouton=1 -dbstats=1 -dbflush=1 +guildrolenotallowed=1 +guildroleremove=1 +help=1 +indicator=1 +info, about=1 +invite=1 +java, jdoodle=1 +map=1 +perish, thenperish=1 +ping=1 +poll=1 +rating=1 +results=1 +role=1 +roll=1 +rpend=1 +rpg=1 +rpstart=1 +showpoll=1 +shutdown=1 +stats=1 +teey=1 +tony, stark, dontfeelgood, dontfeelsogood=1 +tweet=1 +vote=1 +wolfram=1 +work=1 +yeet=1 diff --git a/src/core/BaseKeyValueFile.java b/src/core/BaseKeyValueFile.java index febb891..cb27fc5 100644 --- a/src/core/BaseKeyValueFile.java +++ b/src/core/BaseKeyValueFile.java @@ -1,6 +1,90 @@ package core; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.List; +import java.util.ListIterator; +import java.util.function.Consumer; + +import dataStructures.Pair; +import utils.GlobalLog; +import utils.LogFilter; +import utils.io.FileUtils; + public class BaseKeyValueFile { - + // Variables + public static final String headerStart = "["; + public static final String headerEnd = "]"; + public static final String pairSplit = "="; + public static final char pairSeparator = '\n'; + + protected final String filename; + protected final String header; + + + // Constructor + public BaseKeyValueFile(String filename) + { + this.filename = filename; + this.header = headerStart + this.getClass().getSimpleName() + headerEnd; + } + + // Reads in and calls the specifid function for each keyvalue pair we find + protected void Parse(Consumer> keyValueCallback) + { + File f = new File(filename); + if(f.isFile() && f.canRead()) + { + String content = FileUtils.ReadContent(f).trim(); + String[] lines = content.split("" + pairSeparator); + + for(int i = 0; i < lines.length; ++i) + { + if(lines[i].contains(header)) + continue; + + String[] pair = lines[i].split(pairSplit); + + if(pair.length < 2) + continue; + + String key = pair[0].trim().toLowerCase(); + String value = pair[1].trim().toLowerCase(); + + keyValueCallback.accept(new Pair(key, value)); + } + } + } + + // Writes out a set of keyvalue pairs + protected void Write(List> toWrite) + { + try + { + ListIterator> iter = toWrite.listIterator(); + + String outString = ""; + outString += header + pairSeparator; + + while(iter.hasNext()) + { + Pair pair = iter.next(); + String key = pair.First.toLowerCase(); + String value = pair.Second.toLowerCase(); + + outString += key + pairSplit + value + pairSeparator; + } + + BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); + writer.write(outString); + writer.close(); + } + catch (IOException e) + { + GlobalLog.Error(LogFilter.Core, "Issue writing file " + filename + ": " + e.getMessage()); + } + } } diff --git a/src/core/BaseLocFile.java b/src/core/BaseLocFile.java index 261eb16..7525e27 100644 --- a/src/core/BaseLocFile.java +++ b/src/core/BaseLocFile.java @@ -9,10 +9,10 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import dataStructures.TaggedPairStore; -import utils.FileUtils; import utils.GlobalLog; import utils.LogFilter; import utils.io.FileMonitor; +import utils.io.FileUtils; import utils.io.MonitoredFile; // A quick-and-dirty localization tool that scrapes the project for calls to itself, then @@ -37,7 +37,7 @@ public abstract class BaseLocFile // File monitoring protected FileMonitor fileMonitor; - // Ok... so this is an array because if it's not an array, the parser will parse the string + // Constructor public BaseLocFile(String filename, String functionName) { this.filename = filename; diff --git a/src/core/CommandEnabler.java b/src/core/CommandEnabler.java index 3e78bd6..6a1d675 100644 --- a/src/core/CommandEnabler.java +++ b/src/core/CommandEnabler.java @@ -1,13 +1,11 @@ package core; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; - -import utils.FileUtils; +import java.util.List; +import java.util.Vector; +import dataStructures.Pair; import utils.GlobalLog; import utils.LogFilter; @@ -18,11 +16,6 @@ import utils.LogFilter; public class CommandEnabler extends BaseKeyValueFile { // Config/const variables - public static final String headerStart = "["; - public static final String headerEnd = "]"; - public static final String filename = "commands.config"; - public static final String pairSplit = "="; - public static final char pairSeparator = '\n'; public static final String enabled = "1"; public static final String disabled = "0"; public static final boolean defaultEnabledState = true; @@ -30,15 +23,16 @@ public class CommandEnabler extends BaseKeyValueFile // Local variables private HashMap enabledMap; // Quick lookup private ArrayList keyList; // Tracking ordering for later - private final String header; + private final static String name = "commands.config"; public CommandEnabler() { + super(name); + // Create/Init variables GlobalLog.Log(LogFilter.Core, "Initializing " + this.getClass().getSimpleName()); enabledMap = new HashMap<>(); keyList = new ArrayList<>(); - header = headerStart + this.getClass().getSimpleName() + headerEnd; // Startup ReadIn(); @@ -49,33 +43,17 @@ public class CommandEnabler extends BaseKeyValueFile // Reads in the config file and parses it, keeping tabs on the order it read things private void ReadIn() { - File f = new File(filename); - if(f.isFile() && f.canRead()) - { - String content = FileUtils.ReadContent(f).trim(); - String[] lines = content.split("" + pairSeparator); + Parse((pair) ->{ + String key = pair.First; + String value = pair.Second; - for(int i = 0; i < lines.length; ++i) - { - if(lines[i].contains(header)) - continue; - - String[] pair = lines[i].split(pairSplit); - - if(pair.length < 2) - continue; - - String key = pair[0].trim(); - String value = pair[1].trim().toLowerCase(); - - keyList.add(key); + keyList.add(key); - if(value.equalsIgnoreCase(enabled)) - enabledMap.putIfAbsent(key, true); - else - enabledMap.putIfAbsent(key, false); - } - } + if(value.equalsIgnoreCase(enabled)) + enabledMap.putIfAbsent(key, true); + else + enabledMap.putIfAbsent(key, false); + }); } // Look up the already scraped values from the localizer and store them if they @@ -98,36 +76,31 @@ public class CommandEnabler extends BaseKeyValueFile // Write out enabled/disabled file info. private void WriteOut() { - try + List> list = new Vector>(); + + for(int i = 0; i < keyList.size(); ++i) { - String outString = ""; - outString += header + pairSeparator; - for(int i = 0; i < keyList.size(); ++i) - { - String key = keyList.get(i); - String value = enabled; - - if(enabledMap.get(key) == false) - value = disabled; - - outString += key + pairSplit + value + pairSeparator; - } + String key = keyList.get(i).toLowerCase(); + String value = enabled.toLowerCase(); - BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); - writer.write(outString); - writer.close(); - } - catch (IOException e) - { - GlobalLog.Error(LogFilter.Core, "Command enabler issue writing file! " + e.getMessage()); + if(enabledMap.get(key) == false) + value = disabled.toLowerCase(); + + list.add(new Pair(key, value)); } + + Collections.sort(list, (c1, c2) -> { return c1.First.compareTo(c2.First); }); + + Write(list); } // Looks up a key to see if it's enabled or not public boolean IsEnabled(String key) { - if(enabledMap.containsKey(key)) - return enabledMap.get(key); + String toCheck = key.toLowerCase(); + + if(enabledMap.containsKey(toCheck)) + return enabledMap.get(toCheck); return true; } diff --git a/src/core/benchmark/BenchmarkManager.java b/src/core/benchmark/BenchmarkManager.java index 166cab4..dcf5612 100644 --- a/src/core/benchmark/BenchmarkManager.java +++ b/src/core/benchmark/BenchmarkManager.java @@ -6,8 +6,8 @@ import java.util.Collections; import java.util.List; import dataStructures.Pair; -import utils.FileUtils; import utils.io.DirectoryMonitor; +import utils.io.FileUtils; import utils.io.MonitoredFile; // All things considered, this doesn't need to be particularly efficient since anything diff --git a/src/utils/GlobalLog.java b/src/utils/GlobalLog.java index 171bb03..0131587 100644 --- a/src/utils/GlobalLog.java +++ b/src/utils/GlobalLog.java @@ -7,6 +7,8 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; +import utils.io.FileUtils; + public class GlobalLog { private static final String directory = "logs/"; diff --git a/src/utils/io/DirectoryMonitor.java b/src/utils/io/DirectoryMonitor.java index 3f7c493..28f33f2 100644 --- a/src/utils/io/DirectoryMonitor.java +++ b/src/utils/io/DirectoryMonitor.java @@ -9,8 +9,6 @@ import java.util.List; import java.util.function.Consumer; import java.util.stream.Stream; -import utils.FileUtils; - // NOTE: Consider shifting internal behavior to https://docs.oracle.com/javase/tutorial/essential/io/notification.html // for external stability and support public class DirectoryMonitor diff --git a/src/utils/io/FileMonitor.java b/src/utils/io/FileMonitor.java index 283052a..80de434 100644 --- a/src/utils/io/FileMonitor.java +++ b/src/utils/io/FileMonitor.java @@ -3,8 +3,6 @@ package utils.io; import java.nio.file.Paths; import java.util.function.Consumer; -import utils.FileUtils; - // Monitors a single file for changes - the file must exist and is expected to continue to exist. public class FileMonitor { diff --git a/src/utils/FileUtils.java b/src/utils/io/FileUtils.java similarity index 96% rename from src/utils/FileUtils.java rename to src/utils/io/FileUtils.java index 04ce890..21edfd6 100644 --- a/src/utils/FileUtils.java +++ b/src/utils/io/FileUtils.java @@ -1,4 +1,4 @@ -package utils; +package utils.io; import java.io.File; import java.io.IOException; @@ -9,6 +9,9 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.stream.Stream; +import utils.GlobalLog; +import utils.LogFilter; + public class FileUtils { public static void CreateDirectoryIfDoesntExist(String directoryName) From 0ca4160d7b3ded2ad75546e8d3efdd983d97551d Mon Sep 17 00:00:00 2001 From: Matthew Cech Date: Fri, 24 May 2019 04:01:56 -0700 Subject: [PATCH 10/11] = Updated db upkeep frequency --- src/main/Superintendent.java | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/main/Superintendent.java b/src/main/Superintendent.java index 7a93c29..207a642 100644 --- a/src/main/Superintendent.java +++ b/src/main/Superintendent.java @@ -1,5 +1,7 @@ package main; +import java.util.concurrent.atomic.AtomicInteger; + import core.DatabaseManager; import core.LocCommands; import core.LocStrings; @@ -79,13 +81,20 @@ public class Superintendent return true; } + private static final Integer delayTimerReset = 5; + private static AtomicInteger delayTimerCurrent = new AtomicInteger(delayTimerReset); + // This is for stuff that we need to do on a regular basis, but don't // necessarily want running at all points in time. // Happens just after the command / plugin runs. public static boolean PerCommandUpkeepPost(JDA bot, DatabaseManager databaseManager) { - // Upkeep database - databaseManager.Upkeep(); + // Upkeep database lazily on occasion + if(delayTimerCurrent.decrementAndGet() < 0) + { + databaseManager.Upkeep(); + delayTimerCurrent.set(delayTimerReset); + } // Update command-specific RPManager.Upkeep(bot); From 18b7fd84af1d04ef06a8d9ac3c85dec066c3c252 Mon Sep 17 00:00:00 2001 From: Matthew Cech Date: Fri, 24 May 2019 19:04:04 -0700 Subject: [PATCH 11/11] = Fixed multi-command accumulation issue --- commands.config | 1 - src/core/CommandEnabler.java | 3 ++- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/commands.config b/commands.config index ab5a939..db12800 100644 --- a/commands.config +++ b/commands.config @@ -6,7 +6,6 @@ bethistory=1 blur=1 boop=1 buildhelp=1 -buildhelp=1 c++, g++, cplus, cpp=1 catch=1 choose=1 diff --git a/src/core/CommandEnabler.java b/src/core/CommandEnabler.java index 6a1d675..25a83cc 100644 --- a/src/core/CommandEnabler.java +++ b/src/core/CommandEnabler.java @@ -64,7 +64,8 @@ public class CommandEnabler extends BaseKeyValueFile for(int i = 0; i < unloc.size(); ++i) { - String command = unloc.get(i); + String command = unloc.get(i).toLowerCase(); + if(enabledMap.putIfAbsent(command, defaultEnabledState) == null) { GlobalLog.Log(LogFilter.Strings, "Identified new toggleable raw command: " + command);