Remove Static Abuse - Database package

This commit is contained in:
nossr50 2019-07-02 19:41:32 -07:00
parent 67afdd7efb
commit 1260f4e57a
10 changed files with 109 additions and 76 deletions

View File

@ -49,7 +49,7 @@ public class ConvertCommand implements TabExecutor {
databaseTypes.remove(DatabaseType.CUSTOM.toString()); databaseTypes.remove(DatabaseType.CUSTOM.toString());
if (pluginRef.getDatabaseManager().getDatabaseType() == DatabaseType.CUSTOM) { if (pluginRef.getDatabaseManager().getDatabaseType() == DatabaseType.CUSTOM) {
databaseTypes.add(DatabaseManagerFactory.getCustomDatabaseManagerClass().getName()); databaseTypes.add(pluginRef.getDatabaseManagerFactory().getCustomDatabaseManagerClass().getName());
} }
Collections.sort(formulaTypes); Collections.sort(formulaTypes);

View File

@ -1,6 +1,6 @@
package com.gmail.nossr50.commands; package com.gmail.nossr50.commands;
import com.gmail.nossr50.database.FlatfileDatabaseManager; import com.gmail.nossr50.database.FlatFileDatabaseManager;
import com.gmail.nossr50.database.SQLDatabaseManager; import com.gmail.nossr50.database.SQLDatabaseManager;
import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.mcMMO;
@ -23,17 +23,17 @@ public class ResetUserHealthBarSettingsCommand implements TabExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (pluginRef.getDatabaseManager() instanceof SQLDatabaseManager) { if (pluginRef.getDatabaseManager() instanceof SQLDatabaseManager) {
SQLDatabaseManager m = (SQLDatabaseManager) pluginRef.getDatabaseManager(); SQLDatabaseManager sqlDatabaseManager = (SQLDatabaseManager) pluginRef.getDatabaseManager();
m.resetMobHealthSettings(); sqlDatabaseManager.resetMobHealthSettings();
for (McMMOPlayer player : UserManager.getPlayers()) { for (McMMOPlayer player : UserManager.getPlayers()) {
player.getProfile().setMobHealthbarType(pluginRef.getConfigManager().getConfigMobs().getCombat().getHealthBars().getDisplayBarType()); player.getProfile().setMobHealthbarType(pluginRef.getConfigManager().getConfigMobs().getCombat().getHealthBars().getDisplayBarType());
} }
sender.sendMessage("Mob health reset"); sender.sendMessage("Mob health reset");
return true; return true;
} }
if (pluginRef.getDatabaseManager() instanceof FlatfileDatabaseManager) { if (pluginRef.getDatabaseManager() instanceof FlatFileDatabaseManager) {
FlatfileDatabaseManager m = (FlatfileDatabaseManager) pluginRef.getDatabaseManager(); FlatFileDatabaseManager flatFileDatabaseManager = (FlatFileDatabaseManager) pluginRef.getDatabaseManager();
m.resetMobHealthSettings(); flatFileDatabaseManager.resetMobHealthSettings();
for (McMMOPlayer player : UserManager.getPlayers()) { for (McMMOPlayer player : UserManager.getPlayers()) {
player.getProfile().setMobHealthbarType(pluginRef.getConfigManager().getConfigMobs().getCombat().getHealthBars().getDisplayBarType()); player.getProfile().setMobHealthbarType(pluginRef.getConfigManager().getConfigMobs().getCombat().getHealthBars().getDisplayBarType());
} }

View File

@ -21,7 +21,9 @@ public final class ReloadLocaleCommand implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 0) { if (args.length == 0) {
if (!Permissions.reloadlocale(sender)) { if (!Permissions.reloadlocale(sender)) {
if(command.getPermissionMessage() != null)
sender.sendMessage(command.getPermissionMessage()); sender.sendMessage(command.getPermissionMessage());
return true; return true;
} }

View File

@ -28,12 +28,12 @@ public class ConvertDatabaseCommand implements CommandExecutor {
DatabaseType previousType = DatabaseType.getDatabaseType(args[1]); DatabaseType previousType = DatabaseType.getDatabaseType(args[1]);
DatabaseType newType = pluginRef.getDatabaseManager().getDatabaseType(); DatabaseType newType = pluginRef.getDatabaseManager().getDatabaseType();
if (previousType == newType || (newType == DatabaseType.CUSTOM && DatabaseManagerFactory.getCustomDatabaseManagerClass().getSimpleName().equalsIgnoreCase(args[1]))) { if (previousType == newType || (newType == DatabaseType.CUSTOM && pluginRef.getDatabaseManagerFactory().getCustomDatabaseManagerClass().getSimpleName().equalsIgnoreCase(args[1]))) {
sender.sendMessage(pluginRef.getLocaleManager().getString("Commands.mcconvert.Database.Same", newType.toString())); sender.sendMessage(pluginRef.getLocaleManager().getString("Commands.mcconvert.Database.Same", newType.toString()));
return true; return true;
} }
DatabaseManager oldDatabase = DatabaseManagerFactory.createDatabaseManager(previousType); DatabaseManager oldDatabase = pluginRef.getDatabaseManagerFactory().createDatabaseManager(previousType);
if (previousType == DatabaseType.CUSTOM) { if (previousType == DatabaseType.CUSTOM) {
Class<?> clazz; Class<?> clazz;
@ -46,7 +46,7 @@ public class ConvertDatabaseCommand implements CommandExecutor {
return true; return true;
} }
oldDatabase = DatabaseManagerFactory.createCustomDatabaseManager((Class<? extends DatabaseManager>) clazz); oldDatabase = pluginRef.getDatabaseManagerFactory().createCustomDatabaseManager((Class<? extends DatabaseManager>) clazz);
} catch (Throwable e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
sender.sendMessage(pluginRef.getLocaleManager().getString("Commands.mcconvert.Database.InvalidType", args[1])); sender.sendMessage(pluginRef.getLocaleManager().getString("Commands.mcconvert.Database.InvalidType", args[1]));

View File

@ -20,7 +20,7 @@ public class ShowDatabaseCommand implements TabExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 0) { if (args.length == 0) {
Class<?> clazz = DatabaseManagerFactory.getCustomDatabaseManagerClass(); Class<?> clazz = pluginRef.getDatabaseManagerFactory().getCustomDatabaseManagerClass();
if (clazz != null) { if (clazz != null) {
sender.sendMessage(pluginRef.getLocaleManager().getString("Commands.mmoshowdb", clazz.getName())); sender.sendMessage(pluginRef.getLocaleManager().getString("Commands.mmoshowdb", clazz.getName()));

View File

@ -10,11 +10,6 @@ import java.util.Map;
import java.util.UUID; import java.util.UUID;
public interface DatabaseManager { public interface DatabaseManager {
// One month in milliseconds
long PURGE_TIME = 2630000000L * pluginRef.getDatabaseCleaningSettings().getOldUserCutoffMonths();
// During convertUsers, how often to output a status
int progressInterval = 200;
/** /**
* Purge users with 0 power level from the database. * Purge users with 0 power level from the database.
*/ */

View File

@ -1,11 +1,17 @@
package com.gmail.nossr50.database; package com.gmail.nossr50.database;
import com.gmail.nossr50.datatypes.database.DatabaseType; import com.gmail.nossr50.datatypes.database.DatabaseType;
import com.gmail.nossr50.mcMMO;
public class DatabaseManagerFactory { public class DatabaseManagerFactory {
private static Class<? extends DatabaseManager> customManager = null; private mcMMO pluginRef;
private Class<? extends DatabaseManager> customManager = null;
public static DatabaseManager getDatabaseManager() { public DatabaseManagerFactory(mcMMO pluginRef) {
this.pluginRef = pluginRef;
}
public DatabaseManager getDatabaseManager() {
if (customManager != null) { if (customManager != null) {
try { try {
return createDefaultCustomDatabaseManager(); return createDefaultCustomDatabaseManager();
@ -19,10 +25,10 @@ public class DatabaseManagerFactory {
pluginRef.debug("Falling back on " + (pluginRef.getMySQLConfigSettings().isMySQLEnabled() ? "SQL" : "Flatfile") + " database"); pluginRef.debug("Falling back on " + (pluginRef.getMySQLConfigSettings().isMySQLEnabled() ? "SQL" : "Flatfile") + " database");
} }
return pluginRef.getMySQLConfigSettings().isMySQLEnabled() ? new SQLDatabaseManager() : new FlatfileDatabaseManager(); return pluginRef.getMySQLConfigSettings().isMySQLEnabled() ? new SQLDatabaseManager(pluginRef) : new FlatFileDatabaseManager(pluginRef);
} }
public static Class<? extends DatabaseManager> getCustomDatabaseManagerClass() { public Class<? extends DatabaseManager> getCustomDatabaseManagerClass() {
return customManager; return customManager;
} }
@ -41,7 +47,7 @@ public class DatabaseManagerFactory {
* @throws IllegalArgumentException if the provided class does not have * @throws IllegalArgumentException if the provided class does not have
* an empty constructor * an empty constructor
*/ */
public static void setCustomDatabaseManagerClass(Class<? extends DatabaseManager> clazz) { public void setCustomDatabaseManagerClass(Class<? extends DatabaseManager> clazz) {
try { try {
clazz.getConstructor(); clazz.getConstructor();
customManager = clazz; customManager = clazz;
@ -50,13 +56,13 @@ public class DatabaseManagerFactory {
} }
} }
public static DatabaseManager createDatabaseManager(DatabaseType type) { public DatabaseManager createDatabaseManager(DatabaseType type) {
switch (type) { switch (type) {
case FLATFILE: case FLATFILE:
return new FlatfileDatabaseManager(); return new FlatFileDatabaseManager(pluginRef);
case SQL: case SQL:
return new SQLDatabaseManager(); return new SQLDatabaseManager(pluginRef);
case CUSTOM: case CUSTOM:
try { try {
@ -70,7 +76,7 @@ public class DatabaseManagerFactory {
} }
} }
public static DatabaseManager createDefaultCustomDatabaseManager() throws Throwable { public DatabaseManager createDefaultCustomDatabaseManager() throws Throwable {
return customManager.getConstructor().newInstance(); return customManager.getConstructor().newInstance();
} }

View File

@ -7,6 +7,7 @@ import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.player.UniqueDataType; import com.gmail.nossr50.datatypes.player.UniqueDataType;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.datatypes.skills.SuperAbilityType; import com.gmail.nossr50.datatypes.skills.SuperAbilityType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.StringUtils; import com.gmail.nossr50.util.StringUtils;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
@ -14,60 +15,71 @@ import org.bukkit.OfflinePlayer;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;
public final class FlatfileDatabaseManager implements DatabaseManager { public final class FlatFileDatabaseManager implements DatabaseManager {
private static final Object fileWritingLock = new Object(); private mcMMO pluginRef;
public static int USERNAME = 0; private final Object fileWritingLock = new Object();
public static int SKILLS_MINING = 1; private int USERNAME = 0;
public static int EXP_MINING = 4; private int SKILLS_MINING = 1;
public static int SKILLS_WOODCUTTING = 5; private int EXP_MINING = 4;
public static int EXP_WOODCUTTING = 6; private int SKILLS_WOODCUTTING = 5;
public static int SKILLS_REPAIR = 7; private int EXP_WOODCUTTING = 6;
public static int SKILLS_UNARMED = 8; private int SKILLS_REPAIR = 7;
public static int SKILLS_HERBALISM = 9; private int SKILLS_UNARMED = 8;
public static int SKILLS_EXCAVATION = 10; private int SKILLS_HERBALISM = 9;
public static int SKILLS_ARCHERY = 11; private int SKILLS_EXCAVATION = 10;
public static int SKILLS_SWORDS = 12; private int SKILLS_ARCHERY = 11;
public static int SKILLS_AXES = 13; private int SKILLS_SWORDS = 12;
public static int SKILLS_ACROBATICS = 14; private int SKILLS_AXES = 13;
public static int EXP_REPAIR = 15; private int SKILLS_ACROBATICS = 14;
public static int EXP_UNARMED = 16; private int EXP_REPAIR = 15;
public static int EXP_HERBALISM = 17; private int EXP_UNARMED = 16;
public static int EXP_EXCAVATION = 18; private int EXP_HERBALISM = 17;
public static int EXP_ARCHERY = 19; private int EXP_EXCAVATION = 18;
public static int EXP_SWORDS = 20; private int EXP_ARCHERY = 19;
public static int EXP_AXES = 21; private int EXP_SWORDS = 20;
public static int EXP_ACROBATICS = 22; private int EXP_AXES = 21;
public static int SKILLS_TAMING = 24; private int EXP_ACROBATICS = 22;
public static int EXP_TAMING = 25; private int SKILLS_TAMING = 24;
public static int COOLDOWN_BERSERK = 26; private int EXP_TAMING = 25;
public static int COOLDOWN_GIGA_DRILL_BREAKER = 27; private int COOLDOWN_BERSERK = 26;
public static int COOLDOWN_TREE_FELLER = 28; private int COOLDOWN_GIGA_DRILL_BREAKER = 27;
public static int COOLDOWN_GREEN_TERRA = 29; private int COOLDOWN_TREE_FELLER = 28;
public static int COOLDOWN_SERRATED_STRIKES = 30; private int COOLDOWN_GREEN_TERRA = 29;
public static int COOLDOWN_SKULL_SPLITTER = 31; private int COOLDOWN_SERRATED_STRIKES = 30;
public static int COOLDOWN_SUPER_BREAKER = 32; private int COOLDOWN_SKULL_SPLITTER = 31;
public static int SKILLS_FISHING = 34; private int COOLDOWN_SUPER_BREAKER = 32;
public static int EXP_FISHING = 35; private int SKILLS_FISHING = 34;
public static int COOLDOWN_BLAST_MINING = 36; private int EXP_FISHING = 35;
public static int LAST_LOGIN = 37; private int COOLDOWN_BLAST_MINING = 36;
public static int HEALTHBAR = 38; private int LAST_LOGIN = 37;
public static int SKILLS_ALCHEMY = 39; private int HEALTHBAR = 38;
public static int EXP_ALCHEMY = 40; private int SKILLS_ALCHEMY = 39;
public static int UUID_INDEX = 41; private int EXP_ALCHEMY = 40;
public static int SCOREBOARD_TIPS = 42; private int UUID_INDEX = 41;
public static int COOLDOWN_CHIMAERA_WING = 43; private int SCOREBOARD_TIPS = 42;
private int COOLDOWN_CHIMAERA_WING = 43;
private final HashMap<PrimarySkillType, List<PlayerStat>> playerStatHash = new HashMap<>(); private final HashMap<PrimarySkillType, List<PlayerStat>> playerStatHash = new HashMap<>();
private final List<PlayerStat> powerLevels = new ArrayList<>(); private final List<PlayerStat> powerLevels = new ArrayList<>();
private final File usersFile; private final File usersFile;
private long lastUpdate = 0; private long lastUpdate = 0;
private long updateWaitTime; private long updateWaitTime;
protected FlatfileDatabaseManager() { //How long since a users last login before we purge them
long purgeTime;
// During convertUsers, how often to output a status
int progressInterval;
protected FlatFileDatabaseManager(mcMMO pluginRef) {
this.pluginRef = pluginRef;
purgeTime = 2630000000L * pluginRef.getDatabaseCleaningSettings().getOldUserCutoffMonths();
progressInterval = 200;
updateWaitTime = pluginRef.getConfigManager().getConfigDatabase().getConfigDatabaseFlatFile().getLeaderboardUpdateIntervalMinutes() * (1000 * 60); updateWaitTime = pluginRef.getConfigManager().getConfigDatabase().getConfigDatabaseFlatFile().getLeaderboardUpdateIntervalMinutes() * (1000 * 60);
usersFile = new File(pluginRef.getUsersFilePath()); usersFile = new File(pluginRef.getUsersFilePath());
checkStructure(); checkStructure();
updateLeaderboards(); updateLeaderboards();
/*if (mcMMO.getUpgradeManager().shouldUpgrade(UpgradeType.ADD_UUIDS)) { /*if (mcMMO.getUpgradeManager().shouldUpgrade(UpgradeType.ADD_UUIDS)) {
new UUIDUpdateAsyncTask(mcMMO.p, getStoredUsers()).runTaskAsynchronously(mcMMO.p); new UUIDUpdateAsyncTask(mcMMO.p, getStoredUsers()).runTaskAsynchronously(mcMMO.p);
}*/ }*/
@ -168,7 +180,7 @@ public final class FlatfileDatabaseManager implements DatabaseManager {
rewrite = true; rewrite = true;
} }
if (currentTime - lastPlayed > PURGE_TIME) { if (currentTime - lastPlayed > purgeTime) {
removedPlayers++; removedPlayers++;
} else { } else {
if (rewrite) { if (rewrite) {

View File

@ -9,6 +9,7 @@ import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.player.UniqueDataType; import com.gmail.nossr50.datatypes.player.UniqueDataType;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.datatypes.skills.SuperAbilityType; import com.gmail.nossr50.datatypes.skills.SuperAbilityType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Misc;
import org.apache.tomcat.jdbc.pool.DataSource; import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties; import org.apache.tomcat.jdbc.pool.PoolProperties;
@ -18,17 +19,27 @@ import java.util.*;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
public final class SQLDatabaseManager implements DatabaseManager { public final class SQLDatabaseManager implements DatabaseManager {
public static final String COM_MYSQL_JDBC_DRIVER = "com.mysql.jdbc.Driver"; private mcMMO pluginRef;
private static final String ALL_QUERY_VERSION = "total"; public final String COM_MYSQL_JDBC_DRIVER = "com.mysql.jdbc.Driver";
private final String ALL_QUERY_VERSION = "total";
private final Map<UUID, Integer> cachedUserIDs = new HashMap<>(); private final Map<UUID, Integer> cachedUserIDs = new HashMap<>();
private String tablePrefix = pluginRef.getMySQLConfigSettings().getConfigSectionDatabase().getTablePrefix(); private String tablePrefix = pluginRef.getMySQLConfigSettings().getConfigSectionDatabase().getTablePrefix();
private DataSource miscPool; private DataSource miscPool;
private DataSource loadPool; private DataSource loadPool;
private DataSource savePool; private DataSource savePool;
//How long since a users last login before we purge them
long purgeTime;
// During convertUsers, how often to output a status
int progressInterval;
private ReentrantLock massUpdateLock = new ReentrantLock(); private ReentrantLock massUpdateLock = new ReentrantLock();
protected SQLDatabaseManager() { protected SQLDatabaseManager(mcMMO pluginRef) {
this.pluginRef = pluginRef;
purgeTime = 2630000000L * pluginRef.getDatabaseCleaningSettings().getOldUserCutoffMonths();
progressInterval = 200;
String connectionString = "jdbc:mysql://" + pluginRef.getMySQLConfigSettings().getUserConfigSectionServer().getServerAddress() String connectionString = "jdbc:mysql://" + pluginRef.getMySQLConfigSettings().getUserConfigSectionServer().getServerAddress()
+ ":" + pluginRef.getMySQLConfigSettings().getUserConfigSectionServer().getServerPort() + "/" + pluginRef.getMySQLConfigSettings().getConfigSectionDatabase().getDatabaseName(); + ":" + pluginRef.getMySQLConfigSettings().getUserConfigSectionServer().getServerPort() + "/" + pluginRef.getMySQLConfigSettings().getConfigSectionDatabase().getDatabaseName();
@ -148,7 +159,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
public void purgeOldUsers() { public void purgeOldUsers() {
massUpdateLock.lock(); massUpdateLock.lock();
pluginRef.getLogger().info("Purging inactive users older than " + (PURGE_TIME / 2630000000L) + " months..."); pluginRef.getLogger().info("Purging inactive users older than " + (purgeTime / 2630000000L) + " months...");
Connection connection = null; Connection connection = null;
Statement statement = null; Statement statement = null;
@ -163,7 +174,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
"JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " + "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " +
"JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " + "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " +
"JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " + "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " +
"WHERE ((UNIX_TIMESTAMP() - lastlogin) > " + PURGE_TIME + ")"); "WHERE ((UNIX_TIMESTAMP() - lastlogin) > " + purgeTime + ")");
} catch (SQLException ex) { } catch (SQLException ex) {
printErrors(ex); printErrors(ex);
} finally { } finally {

View File

@ -60,6 +60,7 @@ public class mcMMO extends JavaPlugin {
private ChunkManager placeStore; private ChunkManager placeStore;
private ConfigManager configManager; private ConfigManager configManager;
private DynamicSettingsManager dynamicSettingsManager; private DynamicSettingsManager dynamicSettingsManager;
private DatabaseManagerFactory databaseManagerFactory;
private DatabaseManager databaseManager; private DatabaseManager databaseManager;
private FormulaManager formulaManager; private FormulaManager formulaManager;
private MaterialMapStore materialMapStore; private MaterialMapStore materialMapStore;
@ -120,7 +121,9 @@ public class mcMMO extends JavaPlugin {
getLogger().warning("mcMMO will not work properly alongside NoCheatPlus without CompatNoCheatPlus"); getLogger().warning("mcMMO will not work properly alongside NoCheatPlus without CompatNoCheatPlus");
} }
databaseManager = DatabaseManagerFactory.getDatabaseManager(); //TODO: Strange design...
databaseManagerFactory = new DatabaseManagerFactory(this);
databaseManager = getDatabaseManagerFactory().getDatabaseManager();
//Check for the newer API and tell them what to do if its missing //Check for the newer API and tell them what to do if its missing
CompatibilityCheck.checkForOutdatedAPI(serverAPIOutdated, getServerSoftwareStr()); CompatibilityCheck.checkForOutdatedAPI(serverAPIOutdated, getServerSoftwareStr());
@ -651,4 +654,8 @@ public class mcMMO extends JavaPlugin {
public CommandTools getCommandTools() { public CommandTools getCommandTools() {
return commandTools; return commandTools;
} }
public DatabaseManagerFactory getDatabaseManagerFactory() {
return databaseManagerFactory;
}
} }