Removed static uses in database package and Database.getActive

This commit is contained in:
Rsl1122 2018-08-29 16:56:11 +03:00
parent 23f679802e
commit 17e8bc105e
52 changed files with 401 additions and 367 deletions

View File

@ -31,8 +31,6 @@ import com.djrapitops.plan.modules.server.bukkit.BukkitSuperClassBindingModule;
import com.djrapitops.plan.system.PlanSystem; import com.djrapitops.plan.system.PlanSystem;
import com.djrapitops.plan.system.locale.Locale; import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.PluginLang; import com.djrapitops.plan.system.locale.lang.PluginLang;
import com.djrapitops.plan.system.processing.importing.ImporterManager;
import com.djrapitops.plan.system.processing.importing.importers.OfflinePlayerImporter;
import com.djrapitops.plan.system.settings.theme.PlanColorScheme; import com.djrapitops.plan.system.settings.theme.PlanColorScheme;
import com.djrapitops.plan.utilities.metrics.BStatsBukkit; import com.djrapitops.plan.utilities.metrics.BStatsBukkit;
import com.djrapitops.plugin.BukkitPlugin; import com.djrapitops.plugin.BukkitPlugin;
@ -83,11 +81,13 @@ interface PlanComponent {
class BukkitPlanModule { class BukkitPlanModule {
@Provides @Provides
PlanPlugin providePlanPlugin(Plan plan) { @Singleton
return plan; PlanPlugin providePlanPlugin(Plan plugin) {
return plugin;
} }
@Provides @Provides
@Singleton
@Named("mainCommand") @Named("mainCommand")
CommandNode provideMainCommand(PlanCommand command) { CommandNode provideMainCommand(PlanCommand command) {
return command; return command;
@ -124,7 +124,8 @@ public class Plan extends BukkitPlugin implements PlanPlugin {
locale = system.getLocaleSystem().getLocale(); locale = system.getLocaleSystem().getLocale();
system.enable(); system.enable();
ImporterManager.registerImporter(new OfflinePlayerImporter()); // TODO Refactor into ImportSystem
// ImporterManager.registerImporter(new OfflinePlayerImporter());
new BStatsBukkit(this).registerMetrics(); new BStatsBukkit(this).registerMetrics();

View File

@ -63,11 +63,13 @@ interface PlanBungeeComponent {
class BungeePlanModule { class BungeePlanModule {
@Provides @Provides
PlanPlugin providePlanPlugin(PlanBungee plan) { @Singleton
return plan; PlanPlugin providePlanPlugin(PlanBungee plugin) {
return plugin;
} }
@Provides @Provides
@Singleton
@Named("mainCommand") @Named("mainCommand")
CommandNode provideMainCommand(PlanBungeeCommand command) { CommandNode provideMainCommand(PlanBungeeCommand command) {
return command; return command;

View File

@ -71,11 +71,13 @@ interface PlanSpongeComponent {
class SpongePlanModule { class SpongePlanModule {
@Provides @Provides
PlanPlugin providePlanPlugin(PlanSponge plan) { @Singleton
return plan; PlanPlugin providePlanPlugin(PlanSponge plugin) {
return plugin;
} }
@Provides @Provides
@Singleton
@Named("mainCommand") @Named("mainCommand")
CommandNode provideMainCommand(PlanCommand command) { CommandNode provideMainCommand(PlanCommand command) {
return command; return command;

View File

@ -25,15 +25,23 @@ public class InfoCommand extends CommandNode {
private final PlanPlugin plugin; private final PlanPlugin plugin;
private final Locale locale; private final Locale locale;
private final Database database;
private final ConnectionSystem connectionSystem; private final ConnectionSystem connectionSystem;
private final VersionCheckSystem versionCheckSystem; private final VersionCheckSystem versionCheckSystem;
@Inject @Inject
public InfoCommand(PlanPlugin plugin, Locale locale, ConnectionSystem connectionSystem, VersionCheckSystem versionCheckSystem) { public InfoCommand(
PlanPlugin plugin,
Locale locale,
Database database,
ConnectionSystem connectionSystem,
VersionCheckSystem versionCheckSystem
) {
super("info", Permissions.INFO.getPermission(), CommandType.CONSOLE); super("info", Permissions.INFO.getPermission(), CommandType.CONSOLE);
this.plugin = plugin; this.plugin = plugin;
this.locale = locale; this.locale = locale;
this.database = database;
this.connectionSystem = connectionSystem; this.connectionSystem = connectionSystem;
this.versionCheckSystem = versionCheckSystem; this.versionCheckSystem = versionCheckSystem;
@ -52,7 +60,7 @@ public class InfoCommand extends CommandNode {
"", "",
locale.getString(CommandLang.INFO_VERSION, plugin.getVersion()), locale.getString(CommandLang.INFO_VERSION, plugin.getVersion()),
locale.getString(CommandLang.INFO_UPDATE, updateAvailable), locale.getString(CommandLang.INFO_UPDATE, updateAvailable),
locale.getString(CommandLang.INFO_DATABASE, Database.getActive().getName()), locale.getString(CommandLang.INFO_DATABASE, database.getName()),
locale.getString(CommandLang.INFO_BUNGEE_CONNECTION, connectedToBungee), locale.getString(CommandLang.INFO_BUNGEE_CONNECTION, connectedToBungee),
"", "",
">" ">"

View File

@ -26,8 +26,7 @@ public class GeoInfo implements DateHolder, Serializable {
private final String ipHash; private final String ipHash;
private final long date; private final long date;
public GeoInfo(InetAddress address, String geolocation, long lastUsed) public GeoInfo(InetAddress address, String geolocation, long lastUsed) throws NoSuchAlgorithmException {
throws NoSuchAlgorithmException {
this(FormatUtils.formatIP(address), geolocation, lastUsed, new SHA256Hash(address.getHostAddress()).create()); this(FormatUtils.formatIP(address), geolocation, lastUsed, new SHA256Hash(address.getHostAddress()).create());
} }

View File

@ -1,6 +1,5 @@
package com.djrapitops.plan.data.store.containers; package com.djrapitops.plan.data.store.containers;
import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.data.store.Key; import com.djrapitops.plan.data.store.Key;
import com.djrapitops.plan.data.store.Type; import com.djrapitops.plan.data.store.Type;
import com.djrapitops.plan.data.store.keys.AnalysisKeys; import com.djrapitops.plan.data.store.keys.AnalysisKeys;
@ -12,9 +11,9 @@ import com.djrapitops.plan.data.store.mutators.formatting.Formatters;
import com.djrapitops.plan.data.store.mutators.health.HealthInformation; import com.djrapitops.plan.data.store.mutators.health.HealthInformation;
import com.djrapitops.plan.data.time.WorldTimes; import com.djrapitops.plan.data.time.WorldTimes;
import com.djrapitops.plan.system.database.databases.Database; import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.info.server.ServerInfo;
import com.djrapitops.plan.system.info.server.properties.ServerProperties; import com.djrapitops.plan.system.info.server.properties.ServerProperties;
import com.djrapitops.plan.system.settings.Settings; import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plan.system.settings.config.PlanConfig;
import com.djrapitops.plan.system.settings.theme.Theme; import com.djrapitops.plan.system.settings.theme.Theme;
import com.djrapitops.plan.system.settings.theme.ThemeVal; import com.djrapitops.plan.system.settings.theme.ThemeVal;
import com.djrapitops.plan.utilities.MiscUtils; import com.djrapitops.plan.utilities.MiscUtils;
@ -50,6 +49,12 @@ public class AnalysisContainer extends DataContainer {
private final ServerContainer serverContainer; private final ServerContainer serverContainer;
private String version;
private PlanConfig config;
private Theme theme;
private Database database;
private ServerProperties serverProperties;
private static final Key<Map<UUID, String>> serverNames = new Key<>(new Type<Map<UUID, String>>() {}, "SERVER_NAMES"); private static final Key<Map<UUID, String>> serverNames = new Key<>(new Type<Map<UUID, String>>() {}, "SERVER_NAMES");
public AnalysisContainer(ServerContainer serverContainer) { public AnalysisContainer(ServerContainer serverContainer) {
@ -90,11 +95,11 @@ public class AnalysisContainer extends DataContainer {
putRawData(AnalysisKeys.ANALYSIS_TIME_MONTH_AGO, now - TimeAmount.MONTH.ms()); putRawData(AnalysisKeys.ANALYSIS_TIME_MONTH_AGO, now - TimeAmount.MONTH.ms());
putSupplier(AnalysisKeys.REFRESH_TIME_F, () -> Formatters.second().apply(() -> getUnsafe(AnalysisKeys.ANALYSIS_TIME))); putSupplier(AnalysisKeys.REFRESH_TIME_F, () -> Formatters.second().apply(() -> getUnsafe(AnalysisKeys.ANALYSIS_TIME)));
putRawData(AnalysisKeys.VERSION, PlanPlugin.getInstance().getVersion()); putRawData(AnalysisKeys.VERSION, version);
putSupplier(AnalysisKeys.TIME_ZONE, MiscUtils::getTimeZoneOffsetHours); putSupplier(AnalysisKeys.TIME_ZONE, MiscUtils::getTimeZoneOffsetHours);
putRawData(AnalysisKeys.FIRST_DAY, 1); putRawData(AnalysisKeys.FIRST_DAY, 1);
putRawData(AnalysisKeys.TPS_MEDIUM, Settings.THEME_GRAPH_TPS_THRESHOLD_MED.getNumber()); putRawData(AnalysisKeys.TPS_MEDIUM, config.getNumber(Settings.THEME_GRAPH_TPS_THRESHOLD_MED));
putRawData(AnalysisKeys.TPS_HIGH, Settings.THEME_GRAPH_TPS_THRESHOLD_HIGH.getNumber()); putRawData(AnalysisKeys.TPS_HIGH, config.getNumber(Settings.THEME_GRAPH_TPS_THRESHOLD_HIGH));
addServerProperties(); addServerProperties();
addThemeColors(); addThemeColors();
@ -105,24 +110,23 @@ public class AnalysisContainer extends DataContainer {
getUnsafe(serverNames).getOrDefault(serverContainer.getUnsafe(ServerKeys.SERVER_UUID), "Plan") getUnsafe(serverNames).getOrDefault(serverContainer.getUnsafe(ServerKeys.SERVER_UUID), "Plan")
); );
ServerProperties serverProperties = ServerInfo.getServerProperties_Old();
putRawData(AnalysisKeys.PLAYERS_MAX, serverProperties.getMaxPlayers()); putRawData(AnalysisKeys.PLAYERS_MAX, serverProperties.getMaxPlayers());
putRawData(AnalysisKeys.PLAYERS_ONLINE, serverProperties.getOnlinePlayers()); putRawData(AnalysisKeys.PLAYERS_ONLINE, serverProperties.getOnlinePlayers());
} }
private void addThemeColors() { private void addThemeColors() {
putRawData(AnalysisKeys.ACTIVITY_PIE_COLORS, Theme.getValue_Old(ThemeVal.GRAPH_ACTIVITY_PIE)); putRawData(AnalysisKeys.ACTIVITY_PIE_COLORS, theme.getValue(ThemeVal.GRAPH_ACTIVITY_PIE));
putRawData(AnalysisKeys.GM_PIE_COLORS, Theme.getValue_Old(ThemeVal.GRAPH_GM_PIE)); putRawData(AnalysisKeys.GM_PIE_COLORS, theme.getValue(ThemeVal.GRAPH_GM_PIE));
putRawData(AnalysisKeys.PLAYERS_GRAPH_COLOR, Theme.getValue_Old(ThemeVal.GRAPH_PLAYERS_ONLINE)); putRawData(AnalysisKeys.PLAYERS_GRAPH_COLOR, theme.getValue(ThemeVal.GRAPH_PLAYERS_ONLINE));
putRawData(AnalysisKeys.TPS_LOW_COLOR, Theme.getValue_Old(ThemeVal.GRAPH_TPS_LOW)); putRawData(AnalysisKeys.TPS_LOW_COLOR, theme.getValue(ThemeVal.GRAPH_TPS_LOW));
putRawData(AnalysisKeys.TPS_MEDIUM_COLOR, Theme.getValue_Old(ThemeVal.GRAPH_TPS_MED)); putRawData(AnalysisKeys.TPS_MEDIUM_COLOR, theme.getValue(ThemeVal.GRAPH_TPS_MED));
putRawData(AnalysisKeys.TPS_HIGH_COLOR, Theme.getValue_Old(ThemeVal.GRAPH_TPS_HIGH)); putRawData(AnalysisKeys.TPS_HIGH_COLOR, theme.getValue(ThemeVal.GRAPH_TPS_HIGH));
putRawData(AnalysisKeys.WORLD_MAP_LOW_COLOR, Theme.getValue_Old(ThemeVal.WORLD_MAP_LOW)); putRawData(AnalysisKeys.WORLD_MAP_LOW_COLOR, theme.getValue(ThemeVal.WORLD_MAP_LOW));
putRawData(AnalysisKeys.WORLD_MAP_HIGH_COLOR, Theme.getValue_Old(ThemeVal.WORLD_MAP_HIGH)); putRawData(AnalysisKeys.WORLD_MAP_HIGH_COLOR, theme.getValue(ThemeVal.WORLD_MAP_HIGH));
putRawData(AnalysisKeys.WORLD_PIE_COLORS, Theme.getValue_Old(ThemeVal.GRAPH_WORLD_PIE)); putRawData(AnalysisKeys.WORLD_PIE_COLORS, theme.getValue(ThemeVal.GRAPH_WORLD_PIE));
putRawData(AnalysisKeys.AVG_PING_COLOR, Theme.getValue_Old(ThemeVal.GRAPH_AVG_PING)); putRawData(AnalysisKeys.AVG_PING_COLOR, theme.getValue(ThemeVal.GRAPH_AVG_PING));
putRawData(AnalysisKeys.MAX_PING_COLOR, Theme.getValue_Old(ThemeVal.GRAPH_MAX_PING)); putRawData(AnalysisKeys.MAX_PING_COLOR, theme.getValue(ThemeVal.GRAPH_MAX_PING));
putRawData(AnalysisKeys.MIN_PING_COLOR, Theme.getValue_Old(ThemeVal.GRAPH_MIN_PING)); putRawData(AnalysisKeys.MIN_PING_COLOR, theme.getValue(ThemeVal.GRAPH_MIN_PING));
} }
private void addPlayerSuppliers() { private void addPlayerSuppliers() {
@ -260,7 +264,7 @@ public class AnalysisContainer extends DataContainer {
private void addSessionSuppliers() { private void addSessionSuppliers() {
Key<SessionAccordion> sessionAccordion = new Key<>(SessionAccordion.class, "SESSION_ACCORDION"); Key<SessionAccordion> sessionAccordion = new Key<>(SessionAccordion.class, "SESSION_ACCORDION");
putSupplier(serverNames, () -> Database.getActive().fetch().getServerNames()); putSupplier(serverNames, () -> database.fetch().getServerNames());
putSupplier(sessionAccordion, () -> SessionAccordion.forServer( putSupplier(sessionAccordion, () -> SessionAccordion.forServer(
getUnsafe(AnalysisKeys.SESSIONS_MUTATOR).all(), getUnsafe(AnalysisKeys.SESSIONS_MUTATOR).all(),
getSupplier(serverNames), getSupplier(serverNames),

View File

@ -40,6 +40,8 @@ public class NetworkContainer extends DataContainer {
private final ServerContainer bungeeContainer; private final ServerContainer bungeeContainer;
private Database database;
private final Map<UUID, AnalysisContainer> serverContainers; private final Map<UUID, AnalysisContainer> serverContainers;
public NetworkContainer(ServerContainer bungeeContainer) { public NetworkContainer(ServerContainer bungeeContainer) {
@ -70,7 +72,7 @@ public class NetworkContainer extends DataContainer {
return Optional.of(container); return Optional.of(container);
} }
try { try {
AnalysisContainer analysisContainer = new AnalysisContainer(Database.getActive().fetch().getServerContainer(serverUUID)); AnalysisContainer analysisContainer = new AnalysisContainer(database.fetch().getServerContainer(serverUUID));
serverContainers.put(serverUUID, analysisContainer); serverContainers.put(serverUUID, analysisContainer);
return Optional.of(analysisContainer); return Optional.of(analysisContainer);
} catch (DBOpException e) { } catch (DBOpException e) {

View File

@ -6,6 +6,10 @@ package com.djrapitops.plan.system;
* @author Rsl1122 * @author Rsl1122
*/ */
public class DebugChannels { public class DebugChannels {
public static final String INFO_REQUESTS = "InfoRequests"; public static final String INFO_REQUESTS = "InfoRequests";
public static final String CONNECTIONS = "Connections"; public static final String CONNECTIONS = "Connections";
public static final String WEB_REQUESTS = "Web Requests";
public static final String SQL = "SQL";
} }

View File

@ -33,6 +33,7 @@ public class DataCache extends SessionCache implements SubSystem {
@Inject @Inject
public DataCache(Database database) { public DataCache(Database database) {
super(database);
playerNames = new HashMap<>(); playerNames = new HashMap<>();
displayNames = new HashMap<>(); displayNames = new HashMap<>();
uuids = new HashMap<>(); uuids = new HashMap<>();

View File

@ -1,10 +1,8 @@
package com.djrapitops.plan.system.cache; package com.djrapitops.plan.system.cache;
import com.djrapitops.plan.api.exceptions.database.DBOpException;
import com.djrapitops.plan.data.container.Session; import com.djrapitops.plan.data.container.Session;
import com.djrapitops.plan.data.store.keys.SessionKeys; import com.djrapitops.plan.data.store.keys.SessionKeys;
import com.djrapitops.plan.system.database.databases.Database; import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.utilities.Verify; import com.djrapitops.plugin.utilities.Verify;
import java.util.HashMap; import java.util.HashMap;
@ -22,6 +20,12 @@ public class SessionCache {
private static final Map<UUID, Session> activeSessions = new HashMap<>(); private static final Map<UUID, Session> activeSessions = new HashMap<>();
private final Database database;
public SessionCache(Database database) {
this.database = database;
}
@Deprecated @Deprecated
public static SessionCache getInstance() { public static SessionCache getInstance() {
SessionCache dataCache = CacheSystem.getInstance().getDataCache(); SessionCache dataCache = CacheSystem.getInstance().getDataCache();
@ -60,6 +64,13 @@ public class SessionCache {
activeSessions.put(uuid, session); activeSessions.put(uuid, session);
} }
/**
* End a session and save it to database.
*
* @param uuid UUID of the player.
* @param time Time the session ended.
* @throws com.djrapitops.plan.api.exceptions.database.DBOpException If saving failed.
*/
public void endSession(UUID uuid, long time) { public void endSession(UUID uuid, long time) {
Session session = activeSessions.get(uuid); Session session = activeSessions.get(uuid);
if (session == null) { if (session == null) {
@ -70,9 +81,8 @@ public class SessionCache {
} }
try { try {
session.endSession(time); session.endSession(time);
Database.getActive().save().session(uuid, session); // Might throw a DBOpException
} catch (DBOpException e) { database.save().session(uuid, session);
Log.toLog(this.getClass(), e);
} finally { } finally {
removeSessionFromCache(uuid); removeSessionFromCache(uuid);
} }

View File

@ -7,13 +7,12 @@ package com.djrapitops.plan.system.database;
import com.djrapitops.plan.api.exceptions.EnableException; import com.djrapitops.plan.api.exceptions.EnableException;
import com.djrapitops.plan.api.exceptions.database.DBException; import com.djrapitops.plan.api.exceptions.database.DBException;
import com.djrapitops.plan.api.exceptions.database.DBInitException; import com.djrapitops.plan.api.exceptions.database.DBInitException;
import com.djrapitops.plan.system.PlanSystem;
import com.djrapitops.plan.system.SubSystem; import com.djrapitops.plan.system.SubSystem;
import com.djrapitops.plan.system.database.databases.Database; import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.locale.Locale; import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.PluginLang; import com.djrapitops.plan.system.locale.lang.PluginLang;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.benchmarking.Timings; import com.djrapitops.plugin.benchmarking.Timings;
import com.djrapitops.plugin.logging.L;
import com.djrapitops.plugin.logging.console.PluginLogger; import com.djrapitops.plugin.logging.console.PluginLogger;
import com.djrapitops.plugin.logging.error.ErrorHandler; import com.djrapitops.plugin.logging.error.ErrorHandler;
import com.djrapitops.plugin.utilities.Verify; import com.djrapitops.plugin.utilities.Verify;
@ -38,7 +37,12 @@ public abstract class DBSystem implements SubSystem {
protected Database db; protected Database db;
protected Set<Database> databases; protected Set<Database> databases;
public DBSystem(Locale locale, PluginLogger logger, Timings timings, ErrorHandler errorHandler) { public DBSystem(
Locale locale,
PluginLogger logger,
Timings timings,
ErrorHandler errorHandler
) {
this.locale = locale; this.locale = locale;
this.logger = logger; this.logger = logger;
this.timings = timings; this.timings = timings;
@ -46,13 +50,6 @@ public abstract class DBSystem implements SubSystem {
databases = new HashSet<>(); databases = new HashSet<>();
} }
@Deprecated
public static DBSystem getInstance() {
DBSystem dbSystem = PlanSystem.getInstance().getDatabaseSystem();
Verify.nullCheck(dbSystem, () -> new IllegalStateException("Database system was not initialized."));
return dbSystem;
}
public Database getActiveDatabaseByName(String dbName) { public Database getActiveDatabaseByName(String dbName) {
for (Database database : getDatabases()) { for (Database database : getDatabases()) {
String dbConfigName = database.getConfigName(); String dbConfigName = database.getConfigName();
@ -74,7 +71,7 @@ public abstract class DBSystem implements SubSystem {
db.close(); db.close();
} }
} catch (DBException e) { } catch (DBException e) {
Log.toLog(this.getClass(), e); errorHandler.log(L.WARN, this.getClass(), e);
} }
} }
@ -87,7 +84,7 @@ public abstract class DBSystem implements SubSystem {
try { try {
db.init(); db.init();
db.scheduleClean(1L); db.scheduleClean(1L);
Log.info(locale.getString(PluginLang.ENABLED_DATABASE, db.getName())); logger.info(locale.getString(PluginLang.ENABLED_DATABASE, db.getName()));
} catch (DBInitException e) { } catch (DBInitException e) {
Throwable cause = e.getCause(); Throwable cause = e.getCause();
String message = cause == null ? e.getMessage() : cause.getMessage(); String message = cause == null ? e.getMessage() : cause.getMessage();

View File

@ -2,9 +2,7 @@ package com.djrapitops.plan.system.database.databases;
import com.djrapitops.plan.api.exceptions.database.DBException; import com.djrapitops.plan.api.exceptions.database.DBException;
import com.djrapitops.plan.api.exceptions.database.DBInitException; import com.djrapitops.plan.api.exceptions.database.DBInitException;
import com.djrapitops.plan.system.database.DBSystem;
import com.djrapitops.plan.system.database.databases.operation.*; import com.djrapitops.plan.system.database.databases.operation.*;
import com.djrapitops.plugin.utilities.Verify;
/** /**
* Abstract class representing a Database. * Abstract class representing a Database.
@ -17,13 +15,6 @@ public abstract class Database {
protected boolean open = false; protected boolean open = false;
@Deprecated
public static Database getActive() {
Database database = DBSystem.getInstance().getActiveDatabase();
Verify.nullCheck(database, () -> new IllegalStateException("Database was not initialized."));
return database;
}
public abstract void init() throws DBInitException; public abstract void init() throws DBInitException;
public abstract BackupOperations backup(); public abstract BackupOperations backup();
@ -40,13 +31,6 @@ public abstract class Database {
public abstract SaveOperations save(); public abstract SaveOperations save();
/**
* Used to get the name of the database type.
* <p>
* Thread safe.
*
* @return SQLite/MySQL
*/
public abstract String getName(); public abstract String getName();
/** /**

View File

@ -7,7 +7,7 @@ import com.djrapitops.plan.system.locale.lang.PluginLang;
import com.djrapitops.plan.system.settings.Settings; import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plan.system.settings.config.PlanConfig; import com.djrapitops.plan.system.settings.config.PlanConfig;
import com.djrapitops.plugin.api.TimeAmount; import com.djrapitops.plugin.api.TimeAmount;
import com.djrapitops.plugin.api.utility.log.Log; import com.djrapitops.plugin.benchmarking.Timings;
import com.djrapitops.plugin.logging.L; import com.djrapitops.plugin.logging.L;
import com.djrapitops.plugin.logging.console.PluginLogger; import com.djrapitops.plugin.logging.console.PluginLogger;
import com.djrapitops.plugin.logging.error.ErrorHandler; import com.djrapitops.plugin.logging.error.ErrorHandler;
@ -31,9 +31,15 @@ public class MySQLDB extends SQLDB {
protected volatile DataSource dataSource; protected volatile DataSource dataSource;
@Inject @Inject
public MySQLDB(Locale locale, PlanConfig config, public MySQLDB(
RunnableFactory runnableFactory, PluginLogger pluginLogger, ErrorHandler errorHandler) { Locale locale,
super(locale, config, runnableFactory, pluginLogger, errorHandler); PlanConfig config,
RunnableFactory runnableFactory,
PluginLogger pluginLogger,
Timings timings,
ErrorHandler errorHandler
) {
super(locale, config, runnableFactory, pluginLogger, timings, errorHandler);
} }
private static synchronized void increment() { private static synchronized void increment() {
@ -62,7 +68,7 @@ public class MySQLDB extends SQLDB {
String launchOptions = config.getString(Settings.DB_LAUNCH_OPTIONS); String launchOptions = config.getString(Settings.DB_LAUNCH_OPTIONS);
if (launchOptions.isEmpty() || !launchOptions.startsWith("?") || launchOptions.endsWith("&")) { if (launchOptions.isEmpty() || !launchOptions.startsWith("?") || launchOptions.endsWith("&")) {
launchOptions = "?rewriteBatchedStatements=true&useSSL=false"; launchOptions = "?rewriteBatchedStatements=true&useSSL=false";
Log.error(locale.getString(PluginLang.DB_MYSQL_LAUNCH_OPTIONS_FAIL, launchOptions)); logger.error(locale.getString(PluginLang.DB_MYSQL_LAUNCH_OPTIONS_FAIL, launchOptions));
} }
hikariConfig.setJdbcUrl("jdbc:mysql://" + host + ":" + port + "/" + database + launchOptions); hikariConfig.setJdbcUrl("jdbc:mysql://" + host + ":" + port + "/" + database + launchOptions);
@ -131,6 +137,11 @@ public class MySQLDB extends SQLDB {
returnToPool(connection); returnToPool(connection);
} }
@Override
public boolean isUsingMySQL() {
return true;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;

View File

@ -15,6 +15,7 @@ import com.djrapitops.plan.system.locale.lang.PluginLang;
import com.djrapitops.plan.system.settings.Settings; import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plan.system.settings.config.PlanConfig; import com.djrapitops.plan.system.settings.config.PlanConfig;
import com.djrapitops.plugin.api.TimeAmount; import com.djrapitops.plugin.api.TimeAmount;
import com.djrapitops.plugin.benchmarking.Timings;
import com.djrapitops.plugin.logging.L; import com.djrapitops.plugin.logging.L;
import com.djrapitops.plugin.logging.console.PluginLogger; import com.djrapitops.plugin.logging.console.PluginLogger;
import com.djrapitops.plugin.logging.error.ErrorHandler; import com.djrapitops.plugin.logging.error.ErrorHandler;
@ -44,7 +45,8 @@ public abstract class SQLDB extends Database {
protected final PlanConfig config; protected final PlanConfig config;
protected final RunnableFactory runnableFactory; protected final RunnableFactory runnableFactory;
protected final PluginLogger logger; protected final PluginLogger logger;
protected ErrorHandler errorHandler; protected final Timings timings;
protected final ErrorHandler errorHandler;
private final UsersTable usersTable; private final UsersTable usersTable;
private final UserInfoTable userInfoTable; private final UserInfoTable userInfoTable;
@ -70,18 +72,23 @@ public abstract class SQLDB extends Database {
private final SQLSaveOps saveOps; private final SQLSaveOps saveOps;
private final SQLTransferOps transferOps; private final SQLTransferOps transferOps;
private final boolean usingMySQL;
private PluginTask dbCleanTask; private PluginTask dbCleanTask;
public SQLDB(Locale locale, PlanConfig config, RunnableFactory runnableFactory, PluginLogger logger, ErrorHandler errorHandler) { public SQLDB(
Locale locale,
PlanConfig config,
RunnableFactory runnableFactory,
PluginLogger logger,
Timings timings,
ErrorHandler errorHandler
) {
this.locale = locale; this.locale = locale;
this.config = config; this.config = config;
this.runnableFactory = runnableFactory; this.runnableFactory = runnableFactory;
this.logger = logger; this.logger = logger;
this.timings = timings;
this.errorHandler = errorHandler; this.errorHandler = errorHandler;
usingMySQL = this instanceof MySQLDB;
serverTable = new ServerTable(this); serverTable = new ServerTable(this);
securityTable = new SecurityTable(this); securityTable = new SecurityTable(this);
@ -274,25 +281,12 @@ public abstract class SQLDB extends Database {
public abstract void returnToPool(Connection connection); public abstract void returnToPool(Connection connection);
/**
* Reverts transaction when using SQLite Database.
* <p>
* MySQL has Auto Commit enabled.
*/
public void rollback(Connection connection) throws SQLException {
try {
if (!usingMySQL) {
connection.rollback();
}
} finally {
returnToPool(connection);
}
}
public boolean execute(ExecStatement statement) { public boolean execute(ExecStatement statement) {
Connection connection = null; Connection connection = null;
try { try {
connection = getConnection(); connection = getConnection();
// Inject Timings to the statement for benchmarking
statement.setTimings(timings);
try (PreparedStatement preparedStatement = connection.prepareStatement(statement.getSql())) { try (PreparedStatement preparedStatement = connection.prepareStatement(statement.getSql())) {
return statement.execute(preparedStatement); return statement.execute(preparedStatement);
} }
@ -329,6 +323,8 @@ public abstract class SQLDB extends Database {
Connection connection = null; Connection connection = null;
try { try {
connection = getConnection(); connection = getConnection();
// Inject Timings to the statement for benchmarking
statement.setTimings(timings);
try (PreparedStatement preparedStatement = connection.prepareStatement(statement.getSql())) { try (PreparedStatement preparedStatement = connection.prepareStatement(statement.getSql())) {
statement.executeBatch(preparedStatement); statement.executeBatch(preparedStatement);
} }
@ -343,6 +339,8 @@ public abstract class SQLDB extends Database {
Connection connection = null; Connection connection = null;
try { try {
connection = getConnection(); connection = getConnection();
// Inject Timings to the statement for benchmarking
statement.setTimings(timings);
try (PreparedStatement preparedStatement = connection.prepareStatement(statement.getSql())) { try (PreparedStatement preparedStatement = connection.prepareStatement(statement.getSql())) {
return statement.executeQuery(preparedStatement); return statement.executeQuery(preparedStatement);
} }
@ -410,7 +408,7 @@ public abstract class SQLDB extends Database {
} }
public boolean isUsingMySQL() { public boolean isUsingMySQL() {
return usingMySQL; return false;
} }
@Override @Override
@ -458,11 +456,11 @@ public abstract class SQLDB extends Database {
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
SQLDB sqldb = (SQLDB) o; SQLDB sqldb = (SQLDB) o;
return usingMySQL == sqldb.usingMySQL && getName().equals(sqldb.getName()); return getName().equals(sqldb.getName());
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(usingMySQL, getName()); return Objects.hash(getName());
} }
} }

View File

@ -6,7 +6,7 @@ import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.PluginLang; import com.djrapitops.plan.system.locale.lang.PluginLang;
import com.djrapitops.plan.system.settings.config.PlanConfig; import com.djrapitops.plan.system.settings.config.PlanConfig;
import com.djrapitops.plan.utilities.MiscUtils; import com.djrapitops.plan.utilities.MiscUtils;
import com.djrapitops.plugin.api.utility.log.Log; import com.djrapitops.plugin.benchmarking.Timings;
import com.djrapitops.plugin.logging.L; import com.djrapitops.plugin.logging.L;
import com.djrapitops.plugin.logging.console.PluginLogger; import com.djrapitops.plugin.logging.console.PluginLogger;
import com.djrapitops.plugin.logging.error.ErrorHandler; import com.djrapitops.plugin.logging.error.ErrorHandler;
@ -29,9 +29,16 @@ public class SQLiteDB extends SQLDB {
private Connection connection; private Connection connection;
private PluginTask connectionPingTask; private PluginTask connectionPingTask;
public SQLiteDB(File databaseFile, Locale locale, PlanConfig config, public SQLiteDB(
RunnableFactory runnableFactory, PluginLogger logger, ErrorHandler errorHandler) { File databaseFile,
super(locale, config, runnableFactory, logger, errorHandler); Locale locale,
PlanConfig config,
RunnableFactory runnableFactory,
PluginLogger logger,
Timings timings,
ErrorHandler errorHandler
) {
super(locale, config, runnableFactory, logger, timings, errorHandler);
dbName = databaseFile.getName(); dbName = databaseFile.getName();
this.databaseFile = databaseFile; this.databaseFile = databaseFile;
} }
@ -86,7 +93,7 @@ public class SQLiteDB extends SQLDB {
resultSet = statement.executeQuery("/* ping */ SELECT 1"); resultSet = statement.executeQuery("/* ping */ SELECT 1");
} }
} catch (SQLException e) { } catch (SQLException e) {
Log.debug("Something went wrong during SQLite Connection upkeep task."); logger.debug("Something went wrong during SQLite Connection upkeep task.");
try { try {
connection = getNewConnection(databaseFile); connection = getNewConnection(databaseFile);
} catch (SQLException e1) { } catch (SQLException e1) {
@ -174,17 +181,26 @@ public class SQLiteDB extends SQLDB {
private final PlanConfig config; private final PlanConfig config;
private final RunnableFactory runnableFactory; private final RunnableFactory runnableFactory;
private final PluginLogger logger; private final PluginLogger logger;
private final Timings timings;
private final ErrorHandler errorHandler; private final ErrorHandler errorHandler;
private FileSystem fileSystem; private FileSystem fileSystem;
@Inject @Inject
public Factory(Locale locale, PlanConfig config, FileSystem fileSystem, public Factory(
RunnableFactory runnableFactory, PluginLogger logger, ErrorHandler errorHandler) { Locale locale,
PlanConfig config,
FileSystem fileSystem,
RunnableFactory runnableFactory,
PluginLogger logger,
Timings timings,
ErrorHandler errorHandler
) {
this.locale = locale; this.locale = locale;
this.config = config; this.config = config;
this.fileSystem = fileSystem; this.fileSystem = fileSystem;
this.runnableFactory = runnableFactory; this.runnableFactory = runnableFactory;
this.logger = logger; this.logger = logger;
this.timings = timings;
this.errorHandler = errorHandler; this.errorHandler = errorHandler;
} }
@ -197,7 +213,7 @@ public class SQLiteDB extends SQLDB {
} }
public SQLiteDB usingFile(File databaseFile) { public SQLiteDB usingFile(File databaseFile) {
return new SQLiteDB(databaseFile, locale, config, runnableFactory, logger, errorHandler); return new SQLiteDB(databaseFile, locale, config, runnableFactory, logger, timings, errorHandler);
} }
} }

View File

@ -4,6 +4,7 @@ import com.djrapitops.plan.api.exceptions.database.DBInitException;
import com.djrapitops.plan.system.locale.Locale; import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.settings.Settings; import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plan.system.settings.config.PlanConfig; import com.djrapitops.plan.system.settings.config.PlanConfig;
import com.djrapitops.plugin.benchmarking.Timings;
import com.djrapitops.plugin.logging.console.PluginLogger; import com.djrapitops.plugin.logging.console.PluginLogger;
import com.djrapitops.plugin.logging.error.ErrorHandler; import com.djrapitops.plugin.logging.error.ErrorHandler;
import com.djrapitops.plugin.task.RunnableFactory; import com.djrapitops.plugin.task.RunnableFactory;
@ -23,9 +24,15 @@ import java.util.Optional;
public class SpongeMySQLDB extends MySQLDB { public class SpongeMySQLDB extends MySQLDB {
@Inject @Inject
public SpongeMySQLDB(Locale locale, PlanConfig config, public SpongeMySQLDB(
RunnableFactory runnableFactory, PluginLogger pluginLogger, ErrorHandler errorHandler) { Locale locale,
super(locale, config, runnableFactory, pluginLogger, errorHandler); PlanConfig config,
RunnableFactory runnableFactory,
PluginLogger pluginLogger,
Timings timings,
ErrorHandler errorHandler
) {
super(locale, config, runnableFactory, pluginLogger, timings, errorHandler);
} }
@Override @Override

View File

@ -13,11 +13,15 @@ public class SQLBackupOps extends SQLOps implements BackupOperations {
@Override @Override
public void backup(Database toDatabase) { public void backup(Database toDatabase) {
BatchOperationTable toDB = new BatchOperationTable((SQLDB) toDatabase); if (toDatabase instanceof SQLDB) {
BatchOperationTable fromDB = new BatchOperationTable(db); BatchOperationTable toDB = new BatchOperationTable((SQLDB) toDatabase);
BatchOperationTable fromDB = new BatchOperationTable(db);
toDB.removeAllData(); toDB.removeAllData();
fromDB.copyEverything(toDB); fromDB.copyEverything(toDB);
} else {
throw new IllegalArgumentException("Database was not a SQL database - backup not implemented.");
}
} }
@Override @Override

View File

@ -3,6 +3,7 @@ package com.djrapitops.plan.system.database.databases.sql.operation;
import com.djrapitops.plan.system.database.databases.operation.SearchOperations; import com.djrapitops.plan.system.database.databases.operation.SearchOperations;
import com.djrapitops.plan.system.database.databases.sql.SQLDB; import com.djrapitops.plan.system.database.databases.sql.SQLDB;
import java.util.Collections;
import java.util.List; import java.util.List;
public class SQLSearchOps extends SQLOps implements SearchOperations { public class SQLSearchOps extends SQLOps implements SearchOperations {
@ -13,6 +14,8 @@ public class SQLSearchOps extends SQLOps implements SearchOperations {
@Override @Override
public List<String> matchingPlayers(String search) { public List<String> matchingPlayers(String search) {
return usersTable.getMatchingNames(search); List<String> matchingNames = usersTable.getMatchingNames(search);
Collections.sort(matchingNames);
return matchingNames;
} }
} }

View File

@ -8,8 +8,6 @@ import com.djrapitops.plan.system.database.databases.sql.processing.ExecStatemen
import com.djrapitops.plan.system.database.databases.sql.processing.QueryStatement; import com.djrapitops.plan.system.database.databases.sql.processing.QueryStatement;
import com.djrapitops.plan.system.database.databases.sql.tables.GeoInfoTable; import com.djrapitops.plan.system.database.databases.sql.tables.GeoInfoTable;
import com.djrapitops.plan.system.database.databases.sql.tables.move.Version18TransferTable; import com.djrapitops.plan.system.database.databases.sql.tables.move.Version18TransferTable;
import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plugin.api.utility.log.Log;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
@ -83,10 +81,8 @@ public class IPAnonPatch extends Patch {
statement.setString(2, updatedInfo.getIpHash()); statement.setString(2, updatedInfo.getIpHash());
statement.setString(3, geoInfo.getIp()); statement.setString(3, geoInfo.getIp());
statement.addBatch(); statement.addBatch();
} catch (UnknownHostException | NoSuchAlgorithmException e) { } catch (UnknownHostException | NoSuchAlgorithmException ignore) {
if (Settings.DEV_MODE.isTrue()) { // This ip is already anonymised or completely unusable.
Log.toLog(this.getClass(), e);
}
} }
} }
}); });

View File

@ -0,0 +1,50 @@
package com.djrapitops.plan.system.database.databases.sql.processing;
import com.djrapitops.plan.system.DebugChannels;
import com.djrapitops.plugin.benchmarking.Timings;
/**
* Abstract class that performs an SQL statement.
* <p>
* For Benchmarking purposes.
*
* @author Rsl1122
*/
public abstract class AbstractSQLStatement {
protected final String sql;
private Timings timings;
protected AbstractSQLStatement(String sql) {
this.sql = sql;
}
protected void startBenchmark() {
if (timings != null) {
timings.start(DebugChannels.SQL + ": " + sql);
}
}
protected void startBatchBenchmark() {
if (timings != null) {
timings.start(DebugChannels.SQL + ": " + sql + " (Batch)");
}
}
protected void stopBenchmark() {
if (timings != null) {
timings.end(DebugChannels.SQL, DebugChannels.SQL + ": " + sql);
}
}
protected void stopBatchBenchmark() {
if (timings != null) {
timings.end(DebugChannels.SQL, DebugChannels.SQL + ": " + sql + " (Batch)");
}
}
public void setTimings(Timings timings) {
this.timings = timings;
}
}

View File

@ -4,10 +4,6 @@
*/ */
package com.djrapitops.plan.system.database.databases.sql.processing; package com.djrapitops.plan.system.database.databases.sql.processing;
import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plugin.api.Benchmark;
import com.djrapitops.plugin.api.utility.log.Log;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
@ -16,39 +12,31 @@ import java.sql.SQLException;
* *
* @author Rsl1122 * @author Rsl1122
*/ */
public abstract class ExecStatement { public abstract class ExecStatement extends AbstractSQLStatement {
private final String sql;
private final boolean devMode;
public ExecStatement(String sql) { public ExecStatement(String sql) {
this.sql = sql; super(sql);
devMode = Settings.DEV_MODE.isTrue();
} }
public boolean execute(PreparedStatement statement) throws SQLException { public boolean execute(PreparedStatement statement) throws SQLException {
Benchmark.start("SQL: " + sql); startBenchmark();
try { try {
prepare(statement); prepare(statement);
return statement.executeUpdate() > 0; return statement.executeUpdate() > 0;
} finally { } finally {
statement.close(); statement.close();
if (devMode) { stopBenchmark();
Log.debug(Benchmark.stopAndFormat("SQL: " + sql));
}
} }
} }
public void executeBatch(PreparedStatement statement) throws SQLException { public void executeBatch(PreparedStatement statement) throws SQLException {
Benchmark.start("SQL: " + sql + " (Batch)"); startBatchBenchmark();
try { try {
prepare(statement); prepare(statement);
statement.executeBatch(); statement.executeBatch();
} finally { } finally {
statement.close(); statement.close();
if (devMode) { stopBatchBenchmark();
Log.debug(Benchmark.stopAndFormat("SQL: " + sql + " (Batch)"));
}
} }
} }

View File

@ -4,10 +4,6 @@
*/ */
package com.djrapitops.plan.system.database.databases.sql.processing; package com.djrapitops.plan.system.database.databases.sql.processing;
import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plugin.api.Benchmark;
import com.djrapitops.plugin.api.utility.log.Log;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
@ -17,24 +13,21 @@ import java.sql.SQLException;
* *
* @author Rsl1122 * @author Rsl1122
*/ */
public abstract class QueryStatement<T> { public abstract class QueryStatement<T> extends AbstractSQLStatement {
private final String sql;
private final int fetchSize; private final int fetchSize;
private boolean devMode;
public QueryStatement(String sql) { public QueryStatement(String sql) {
this(sql, 10); this(sql, 10);
} }
public QueryStatement(String sql, int fetchSize) { public QueryStatement(String sql, int fetchSize) {
this.sql = sql; super(sql);
devMode = Settings.DEV_MODE.isTrue();
this.fetchSize = fetchSize; this.fetchSize = fetchSize;
} }
public T executeQuery(PreparedStatement statement) throws SQLException { public T executeQuery(PreparedStatement statement) throws SQLException {
Benchmark.start("SQL: " + sql); startBenchmark();
try { try {
statement.setFetchSize(fetchSize); statement.setFetchSize(fetchSize);
prepare(statement); prepare(statement);
@ -43,9 +36,7 @@ public abstract class QueryStatement<T> {
} }
} finally { } finally {
statement.close(); statement.close();
if (devMode) { stopBenchmark();
Log.debug(Benchmark.stopAndFormat("SQL: " + sql));
}
} }
} }

View File

@ -10,7 +10,6 @@ import com.djrapitops.plan.system.database.databases.sql.tables.ServerTable;
import com.djrapitops.plan.system.database.databases.sql.tables.Table; import com.djrapitops.plan.system.database.databases.sql.tables.Table;
import com.djrapitops.plan.system.database.databases.sql.tables.UsersTable; import com.djrapitops.plan.system.database.databases.sql.tables.UsersTable;
import com.djrapitops.plan.system.info.server.Server; import com.djrapitops.plan.system.info.server.Server;
import com.djrapitops.plugin.api.utility.log.Log;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -71,7 +70,6 @@ public class BatchOperationTable extends Table {
if (toDB.equals(this)) { if (toDB.equals(this)) {
return; return;
} }
Log.debug("Start Batch Copy Everything");
toDB.removeAllData(); toDB.removeAllData();
copyServers(toDB); copyServers(toDB);
@ -98,7 +96,6 @@ public class BatchOperationTable extends Table {
if (toDB.equals(this)) { if (toDB.equals(this)) {
return; return;
} }
Log.debug("Batch Copy Commands");
toDB.db.getCommandUseTable().insertCommandUsage(db.getCommandUseTable().getAllCommandUsages()); toDB.db.getCommandUseTable().insertCommandUsage(db.getCommandUseTable().getAllCommandUsages());
} }
@ -106,7 +103,6 @@ public class BatchOperationTable extends Table {
if (toDB.equals(this)) { if (toDB.equals(this)) {
return; return;
} }
Log.debug("Batch Copy IPs, Geolocations & Last used dates");
toDB.db.getGeoInfoTable().insertAllGeoInfo(db.getGeoInfoTable().getAllGeoInfo()); toDB.db.getGeoInfoTable().insertAllGeoInfo(db.getGeoInfoTable().getAllGeoInfo());
} }
@ -114,7 +110,6 @@ public class BatchOperationTable extends Table {
if (toDB.equals(this)) { if (toDB.equals(this)) {
return; return;
} }
Log.debug("Batch Copy Nicknames");
toDB.db.getNicknamesTable().insertNicknames(db.getNicknamesTable().getAllNicknames()); toDB.db.getNicknamesTable().insertNicknames(db.getNicknamesTable().getAllNicknames());
} }
@ -122,7 +117,6 @@ public class BatchOperationTable extends Table {
if (toDB.equals(this)) { if (toDB.equals(this)) {
return; return;
} }
Log.debug("Batch Copy WebUsers");
toDB.db.getSecurityTable().addUsers(db.getSecurityTable().getUsers()); toDB.db.getSecurityTable().addUsers(db.getSecurityTable().getUsers());
} }
@ -130,7 +124,6 @@ public class BatchOperationTable extends Table {
if (toDB.equals(this)) { if (toDB.equals(this)) {
return; return;
} }
Log.debug("Batch Copy Servers");
ServerTable serverTable = db.getServerTable(); ServerTable serverTable = db.getServerTable();
List<Server> servers = new ArrayList<>(serverTable.getBukkitServers().values()); List<Server> servers = new ArrayList<>(serverTable.getBukkitServers().values());
serverTable.getBungeeInfo().ifPresent(servers::add); serverTable.getBungeeInfo().ifPresent(servers::add);
@ -141,7 +134,6 @@ public class BatchOperationTable extends Table {
if (toDB.equals(this)) { if (toDB.equals(this)) {
return; return;
} }
Log.debug("Batch Copy TPS");
toDB.db.getTpsTable().insertAllTPS(db.getTpsTable().getAllTPS()); toDB.db.getTpsTable().insertAllTPS(db.getTpsTable().getAllTPS());
} }
@ -149,7 +141,6 @@ public class BatchOperationTable extends Table {
if (toDB.equals(this)) { if (toDB.equals(this)) {
return; return;
} }
Log.debug("Batch Copy UserInfo");
toDB.db.getUserInfoTable().insertUserInfo(db.getUserInfoTable().getAllUserInfo()); toDB.db.getUserInfoTable().insertUserInfo(db.getUserInfoTable().getAllUserInfo());
} }
@ -157,7 +148,6 @@ public class BatchOperationTable extends Table {
if (toDB.equals(this)) { if (toDB.equals(this)) {
return; return;
} }
Log.debug("Batch Copy Worlds");
toDB.db.getWorldTable().saveWorlds(db.getWorldTable().getAllWorlds()); toDB.db.getWorldTable().saveWorlds(db.getWorldTable().getAllWorlds());
} }
@ -165,7 +155,6 @@ public class BatchOperationTable extends Table {
if (toDB.equals(this)) { if (toDB.equals(this)) {
return; return;
} }
Log.debug("Batch Copy Users");
UsersTable fromTable = db.getUsersTable(); UsersTable fromTable = db.getUsersTable();
UsersTable toTable = toDB.db.getUsersTable(); UsersTable toTable = toDB.db.getUsersTable();
Map<UUID, UserInfo> users = fromTable.getUsers(); Map<UUID, UserInfo> users = fromTable.getUsers();
@ -177,7 +166,6 @@ public class BatchOperationTable extends Table {
if (toDB.equals(this)) { if (toDB.equals(this)) {
return; return;
} }
Log.debug("Batch Copy Sessions");
toDB.db.getSessionsTable().insertSessions(db.getSessionsTable().getAllSessions(true), true); toDB.db.getSessionsTable().insertSessions(db.getSessionsTable().getAllSessions(true), true);
} }
} }

View File

@ -4,7 +4,6 @@
*/ */
package com.djrapitops.plan.system.info; package com.djrapitops.plan.system.info;
import com.djrapitops.plan.api.exceptions.ParseException;
import com.djrapitops.plan.api.exceptions.connection.NoServersException; import com.djrapitops.plan.api.exceptions.connection.NoServersException;
import com.djrapitops.plan.api.exceptions.connection.WebException; import com.djrapitops.plan.api.exceptions.connection.WebException;
import com.djrapitops.plan.system.info.connection.ConnectionSystem; import com.djrapitops.plan.system.info.connection.ConnectionSystem;
@ -16,8 +15,7 @@ import com.djrapitops.plan.system.info.server.ServerInfo;
import com.djrapitops.plan.system.webserver.WebServer; import com.djrapitops.plan.system.webserver.WebServer;
import com.djrapitops.plan.system.webserver.cache.PageId; import com.djrapitops.plan.system.webserver.cache.PageId;
import com.djrapitops.plan.system.webserver.cache.ResponseCache; import com.djrapitops.plan.system.webserver.cache.ResponseCache;
import com.djrapitops.plan.system.webserver.response.errors.InternalErrorResponse; import com.djrapitops.plan.system.webserver.response.ResponseFactory;
import com.djrapitops.plan.system.webserver.response.pages.NetworkPageResponse;
import com.djrapitops.plugin.logging.console.PluginLogger; import com.djrapitops.plugin.logging.console.PluginLogger;
import javax.inject.Inject; import javax.inject.Inject;
@ -31,17 +29,20 @@ import javax.inject.Singleton;
@Singleton @Singleton
public class BungeeInfoSystem extends InfoSystem { public class BungeeInfoSystem extends InfoSystem {
private final ResponseFactory responseFactory;
private final ServerInfo serverInfo; private final ServerInfo serverInfo;
@Inject @Inject
public BungeeInfoSystem( public BungeeInfoSystem(
InfoRequestFactory infoRequestFactory, InfoRequestFactory infoRequestFactory,
ResponseFactory responseFactory,
ConnectionSystem connectionSystem, ConnectionSystem connectionSystem,
ServerInfo serverInfo, ServerInfo serverInfo,
WebServer webServer, WebServer webServer,
PluginLogger logger PluginLogger logger
) { ) {
super(infoRequestFactory, connectionSystem, serverInfo, webServer, logger); super(infoRequestFactory, connectionSystem, serverInfo, webServer, logger);
this.responseFactory = responseFactory;
this.serverInfo = serverInfo; this.serverInfo = serverInfo;
} }
@ -59,12 +60,6 @@ public class BungeeInfoSystem extends InfoSystem {
@Override @Override
public void updateNetworkPage() { public void updateNetworkPage() {
ResponseCache.cacheResponse(PageId.SERVER.of(serverInfo.getServerUUID()), () -> { ResponseCache.cacheResponse(PageId.SERVER.of(serverInfo.getServerUUID()), responseFactory::networkPageResponse);
try {
return new NetworkPageResponse();
} catch (ParseException e) {
return new InternalErrorResponse("Network page parsing failed.", e);
}
});
} }
} }

View File

@ -64,7 +64,7 @@ public class SaveDBSettingsRequest extends InfoRequestWithVariables implements S
if (Check.isBungeeAvailable()) { if (Check.isBungeeAvailable()) {
return new BadRequestResponse("Not supposed to be called on a Bungee server"); return new BadRequestResponse("Not supposed to be called on a Bungee server");
} }
if (Settings.BUNGEE_COPY_CONFIG.isFalse() || Settings.BUNGEE_OVERRIDE_STANDALONE_MODE.isTrue()) { if (config.isFalse(Settings.BUNGEE_COPY_CONFIG) || config.isTrue(Settings.BUNGEE_OVERRIDE_STANDALONE_MODE)) {
return new BadRequestResponse("Bungee config settings overridden on this server."); return new BadRequestResponse("Bungee config settings overridden on this server.");
} }

View File

@ -6,6 +6,7 @@ package com.djrapitops.plan.system.processing.importing.importers;
import com.djrapitops.plan.Plan; import com.djrapitops.plan.Plan;
import com.djrapitops.plan.api.exceptions.database.DBException; import com.djrapitops.plan.api.exceptions.database.DBException;
import com.djrapitops.plan.api.exceptions.database.DBOpException;
import com.djrapitops.plan.data.container.GeoInfo; import com.djrapitops.plan.data.container.GeoInfo;
import com.djrapitops.plan.data.container.Session; import com.djrapitops.plan.data.container.Session;
import com.djrapitops.plan.data.container.UserInfo; import com.djrapitops.plan.data.container.UserInfo;
@ -19,7 +20,6 @@ import com.djrapitops.plan.system.processing.importing.ServerImportData;
import com.djrapitops.plan.system.processing.importing.UserImportData; import com.djrapitops.plan.system.processing.importing.UserImportData;
import com.djrapitops.plan.system.processing.importing.UserImportRefiner; import com.djrapitops.plan.system.processing.importing.UserImportRefiner;
import com.djrapitops.plan.utilities.SHA256Hash; import com.djrapitops.plan.utilities.SHA256Hash;
import com.djrapitops.plugin.api.Benchmark;
import com.djrapitops.plugin.api.utility.log.Log; import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.utilities.Verify; import com.djrapitops.plugin.utilities.Verify;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -37,6 +37,14 @@ import java.util.stream.Collectors;
*/ */
public abstract class Importer { public abstract class Importer {
private final Database database;
private final UUID serverUUID;
protected Importer(Database database, ServerInfo serverInfo) {
this.database = database;
this.serverUUID = serverInfo.getServerUUID();
}
public abstract List<String> getNames(); public abstract List<String> getNames();
public abstract ServerImportData getServerImportData(); public abstract ServerImportData getServerImportData();
@ -44,106 +52,56 @@ public abstract class Importer {
public abstract List<UserImportData> getUserImportData(); public abstract List<UserImportData> getUserImportData();
public final void processImport() { public final void processImport() {
String benchmarkName = "Import processing";
String serverBenchmarkName = "Server Data processing";
String userDataBenchmarkName = "User Data processing";
Benchmark.start(benchmarkName);
ExecutorService service = Executors.newCachedThreadPool(); ExecutorService service = Executors.newCachedThreadPool();
submitTo(service, () -> { submitTo(service, this::processServerData);
Benchmark.start(serverBenchmarkName); submitTo(service, this::processUserData);
processServerData();
Benchmark.stop(serverBenchmarkName);
});
submitTo(service, () -> {
Benchmark.start(userDataBenchmarkName);
processUserData();
Benchmark.stop(userDataBenchmarkName);
});
service.shutdown(); service.shutdown();
try { try {
service.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); service.awaitTermination(20, TimeUnit.MINUTES);
} catch (InterruptedException e) { } catch (InterruptedException e) {
Log.toLog(this.getClass(), e); service.shutdownNow();
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
Benchmark.stop(benchmarkName);
} }
private void processServerData() { private void processServerData() {
String benchmarkName = "Processing Server Data";
String getDataBenchmarkName = "Getting Server Data";
String insertDataIntoDatabaseBenchmarkName = "Insert Server Data into Database";
Benchmark.start(benchmarkName);
Benchmark.start(getDataBenchmarkName);
ServerImportData serverImportData = getServerImportData(); ServerImportData serverImportData = getServerImportData();
Benchmark.stop(getDataBenchmarkName);
if (serverImportData == null) { if (serverImportData == null) {
Log.debug("Server Import Data null, skipping"); Log.debug("Server Import Data null, skipping");
return; return;
} }
UUID uuid = ServerInfo.getServerUUID_Old();
Database db = Database.getActive();
ExecutorService service = Executors.newCachedThreadPool(); ExecutorService service = Executors.newCachedThreadPool();
Benchmark.start(insertDataIntoDatabaseBenchmarkName); SaveOperations save = database.save();
submitTo(service, () -> save.insertTPS(ImmutableMap.of(serverUUID, serverImportData.getTpsData())));
SaveOperations save = db.save(); submitTo(service, () -> save.insertCommandUsage(ImmutableMap.of(serverUUID, serverImportData.getCommandUsages())));
submitTo(service, () -> save.insertTPS(ImmutableMap.of(uuid, serverImportData.getTpsData())));
submitTo(service, () -> save.insertCommandUsage(ImmutableMap.of(uuid, serverImportData.getCommandUsages())));
service.shutdown(); service.shutdown();
try { try {
service.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); service.awaitTermination(20, TimeUnit.MINUTES);
} catch (InterruptedException e) { } catch (InterruptedException e) {
service.shutdownNow();
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
Log.toLog(this.getClass(), e);
} }
Benchmark.stop(insertDataIntoDatabaseBenchmarkName);
Benchmark.stop(benchmarkName);
} }
private void processUserData() { private void processUserData() {
String benchmarkName = "Processing User Data";
String getDataBenchmarkName = "Getting User Data";
String insertDataIntoCollectionsBenchmarkName = "Insert User Data into Collections";
String insertDataIntoDatabaseBenchmarkName = "Insert User Data into Database";
Benchmark.start(benchmarkName);
Benchmark.start(getDataBenchmarkName);
List<UserImportData> userImportData = getUserImportData(); List<UserImportData> userImportData = getUserImportData();
Benchmark.stop(getDataBenchmarkName);
if (Verify.isEmpty(userImportData)) { if (Verify.isEmpty(userImportData)) {
Log.debug("User Import Data null or empty, skipping");
return; return;
} }
UserImportRefiner userImportRefiner = new UserImportRefiner(Plan.getInstance(), userImportData); UserImportRefiner userImportRefiner = new UserImportRefiner(Plan.getInstance(), userImportData);
userImportData = userImportRefiner.refineData(); userImportData = userImportRefiner.refineData();
UUID serverUUID = ServerInfo.getServerUUID_Old(); Set<UUID> existingUUIDs = database.fetch().getSavedUUIDs();
Database db = Database.getActive(); Set<UUID> existingUserInfoTableUUIDs = database.fetch().getSavedUUIDs(serverUUID);
Set<UUID> existingUUIDs = db.fetch().getSavedUUIDs();
Set<UUID> existingUserInfoTableUUIDs = db.fetch().getSavedUUIDs(serverUUID);
Benchmark.start(insertDataIntoCollectionsBenchmarkName);
Map<UUID, UserInfo> users = new HashMap<>(); Map<UUID, UserInfo> users = new HashMap<>();
List<UserInfo> userInfo = new ArrayList<>(); List<UserInfo> userInfo = new ArrayList<>();
@ -170,13 +128,9 @@ public abstract class Importer {
sessions.put(uuid, Collections.singletonList(toSession(data))); sessions.put(uuid, Collections.singletonList(toSession(data)));
}); });
Benchmark.stop(insertDataIntoCollectionsBenchmarkName);
ExecutorService service = Executors.newCachedThreadPool(); ExecutorService service = Executors.newCachedThreadPool();
Benchmark.start(insertDataIntoDatabaseBenchmarkName); SaveOperations save = database.save();
SaveOperations save = db.save();
save.insertUsers(users); save.insertUsers(users);
submitTo(service, () -> save.insertSessions(ImmutableMap.of(serverUUID, sessions), true)); submitTo(service, () -> save.insertSessions(ImmutableMap.of(serverUUID, sessions), true));
@ -186,16 +140,12 @@ public abstract class Importer {
submitTo(service, () -> save.insertAllGeoInfo(geoInfo)); submitTo(service, () -> save.insertAllGeoInfo(geoInfo));
service.shutdown(); service.shutdown();
try { try {
service.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); service.awaitTermination(20, TimeUnit.MINUTES);
} catch (InterruptedException e) { } catch (InterruptedException e) {
service.shutdownNow();
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
Log.toLog(this.getClass(), e);
} }
Benchmark.stop(insertDataIntoDatabaseBenchmarkName);
Benchmark.stop(benchmarkName);
} }
private void submitTo(ExecutorService service, ImportExecutorHelper helper) { private void submitTo(ExecutorService service, ImportExecutorHelper helper) {
@ -216,7 +166,7 @@ public abstract class Importer {
int mobKills = userImportData.getMobKills(); int mobKills = userImportData.getMobKills();
int deaths = userImportData.getDeaths(); int deaths = userImportData.getDeaths();
Session session = new Session(0, userImportData.getUuid(), ServerInfo.getServerUUID_Old(), 0L, 0L, mobKills, deaths, 0); Session session = new Session(0, userImportData.getUuid(), serverUUID, 0L, 0L, mobKills, deaths, 0);
session.setPlayerKills(userImportData.getKills()); session.setPlayerKills(userImportData.getKills());
session.setWorldTimes(new WorldTimes(userImportData.getWorldTimes())); session.setWorldTimes(new WorldTimes(userImportData.getWorldTimes()));
@ -242,14 +192,11 @@ public abstract class Importer {
void execute() throws DBException; void execute() throws DBException;
default void submit(ExecutorService service) { default void submit(ExecutorService service) {
service.submit(new Runnable() { service.submit(() -> {
@Override try {
public void run() { execute();
try { } catch (DBException e) {
execute(); throw new DBOpException("Import Execution failed", e);
} catch (DBException e) {
Log.toLog(this.getClass(), e);
}
} }
}); });
} }

View File

@ -4,11 +4,15 @@
*/ */
package com.djrapitops.plan.system.processing.importing.importers; package com.djrapitops.plan.system.processing.importing.importers;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.info.server.ServerInfo;
import com.djrapitops.plan.system.processing.importing.ServerImportData; import com.djrapitops.plan.system.processing.importing.ServerImportData;
import com.djrapitops.plan.system.processing.importing.UserImportData; import com.djrapitops.plan.system.processing.importing.UserImportData;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -18,8 +22,17 @@ import java.util.Set;
* @author Fuzzlemann * @author Fuzzlemann
* @since 4.0.0 * @since 4.0.0
*/ */
@Singleton
public class OfflinePlayerImporter extends Importer { public class OfflinePlayerImporter extends Importer {
@Inject
public OfflinePlayerImporter(
Database database,
ServerInfo serverInfo
) {
super(database, serverInfo);
}
@Override @Override
public List<String> getNames() { public List<String> getNames() {
return Arrays.asList("offline", "offlineplayer"); return Arrays.asList("offline", "offlineplayer");

View File

@ -16,12 +16,14 @@ public class CommandProcessor implements CriticalRunnable {
private final String command; private final String command;
private Database database;
public CommandProcessor(String command) { public CommandProcessor(String command) {
this.command = command; this.command = command;
} }
@Override @Override
public void run() { public void run() {
Database.getActive().save().commandUsed(command); database.save().commandUsed(command);
} }
} }

View File

@ -20,6 +20,8 @@ public class TPSInsertProcessor implements CriticalRunnable {
private final List<TPS> tpsList; private final List<TPS> tpsList;
private Database database;
public TPSInsertProcessor(List<TPS> tpsList) { public TPSInsertProcessor(List<TPS> tpsList) {
this.tpsList = tpsList; this.tpsList = tpsList;
} }
@ -45,6 +47,6 @@ public class TPSInsertProcessor implements CriticalRunnable {
.chunksLoaded(averageChunksLoaded) .chunksLoaded(averageChunksLoaded)
.toTPS(); .toTPS();
Database.getActive().save().insertTPSforThisServer(tps); database.save().insertTPSforThisServer(tps);
} }
} }

View File

@ -21,6 +21,8 @@ public class BanAndOpProcessor implements Runnable {
private final Supplier<Boolean> banned; private final Supplier<Boolean> banned;
private final boolean op; private final boolean op;
private Database database;
public BanAndOpProcessor(UUID uuid, Supplier<Boolean> banned, boolean op) { public BanAndOpProcessor(UUID uuid, Supplier<Boolean> banned, boolean op) {
this.uuid = uuid; this.uuid = uuid;
this.banned = banned; this.banned = banned;
@ -29,7 +31,7 @@ public class BanAndOpProcessor implements Runnable {
@Override @Override
public void run() { public void run() {
SaveOperations save = Database.getActive().save(); SaveOperations save = database.save();
save.banStatus(uuid, banned.get()); save.banStatus(uuid, banned.get());
save.opStatus(uuid, op); save.opStatus(uuid, op);
} }

View File

@ -23,6 +23,7 @@ public class BungeePlayerRegisterProcessor implements CriticalRunnable {
private final Runnable[] afterProcess; private final Runnable[] afterProcess;
private Processing processing; private Processing processing;
private Database database;
public BungeePlayerRegisterProcessor(UUID uuid, String name, long registered, Runnable... afterProcess) { public BungeePlayerRegisterProcessor(UUID uuid, String name, long registered, Runnable... afterProcess) {
this.uuid = uuid; this.uuid = uuid;
@ -33,7 +34,6 @@ public class BungeePlayerRegisterProcessor implements CriticalRunnable {
@Override @Override
public void run() { public void run() {
Database database = Database.getActive();
try { try {
if (database.check().isPlayerRegistered(uuid)) { if (database.check().isPlayerRegistered(uuid)) {
return; return;

View File

@ -26,6 +26,8 @@ public class IPUpdateProcessor implements CriticalRunnable {
private final InetAddress ip; private final InetAddress ip;
private final long time; private final long time;
private Database database;
public IPUpdateProcessor(UUID uuid, InetAddress ip, long time) { public IPUpdateProcessor(UUID uuid, InetAddress ip, long time) {
this.uuid = uuid; this.uuid = uuid;
this.ip = ip; this.ip = ip;
@ -38,7 +40,7 @@ public class IPUpdateProcessor implements CriticalRunnable {
String country = GeolocationCache.getCountry(ip.getHostAddress()); String country = GeolocationCache.getCountry(ip.getHostAddress());
try { try {
GeoInfo geoInfo = new GeoInfo(ip, country, time); GeoInfo geoInfo = new GeoInfo(ip, country, time);
Database.getActive().save().geoInfo(uuid, geoInfo); database.save().geoInfo(uuid, geoInfo);
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
Log.toLog(this.getClass(), e); Log.toLog(this.getClass(), e);
} }

View File

@ -18,12 +18,14 @@ public class KickProcessor implements CriticalRunnable {
private final UUID uuid; private final UUID uuid;
private Database database;
public KickProcessor(UUID uuid) { public KickProcessor(UUID uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
@Override @Override
public void run() { public void run() {
Database.getActive().save().playerWasKicked(uuid); database.save().playerWasKicked(uuid);
} }
} }

View File

@ -7,6 +7,7 @@ package com.djrapitops.plan.system.processing.processors.player;
import com.djrapitops.plan.data.store.objects.Nickname; import com.djrapitops.plan.data.store.objects.Nickname;
import com.djrapitops.plan.system.cache.DataCache; import com.djrapitops.plan.system.cache.DataCache;
import com.djrapitops.plan.system.database.databases.Database; import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.database.databases.operation.SaveOperations;
import com.djrapitops.plan.system.info.server.ServerInfo; import com.djrapitops.plan.system.info.server.ServerInfo;
import com.djrapitops.plan.system.processing.CriticalRunnable; import com.djrapitops.plan.system.processing.CriticalRunnable;
@ -24,6 +25,8 @@ public class NameProcessor implements CriticalRunnable {
private final String playerName; private final String playerName;
private final Nickname nickname; private final Nickname nickname;
private Database database;
public NameProcessor(UUID uuid, String playerName, String displayName) { public NameProcessor(UUID uuid, String playerName, String displayName) {
this.uuid = uuid; this.uuid = uuid;
this.playerName = playerName; this.playerName = playerName;
@ -43,9 +46,8 @@ public class NameProcessor implements CriticalRunnable {
dataCache.updateNames(uuid, playerName, nickname.getName()); dataCache.updateNames(uuid, playerName, nickname.getName());
Database database = Database.getActive(); SaveOperations save = database.save();
database.save().playerName(uuid, playerName); save.playerName(uuid, playerName);
save.playerDisplayName(uuid, nickname);
database.save().playerDisplayName(uuid, nickname);
} }
} }

View File

@ -26,6 +26,8 @@ public class PingInsertProcessor implements CriticalRunnable {
private final UUID uuid; private final UUID uuid;
private final List<DateObj<Integer>> pingList; private final List<DateObj<Integer>> pingList;
private Database database;
public PingInsertProcessor(UUID uuid, List<DateObj<Integer>> pingList) { public PingInsertProcessor(UUID uuid, List<DateObj<Integer>> pingList) {
this.uuid = uuid; this.uuid = uuid;
this.pingList = pingList; this.pingList = pingList;
@ -61,6 +63,6 @@ public class PingInsertProcessor implements CriticalRunnable {
maxValue, maxValue,
avgValue); avgValue);
Database.getActive().save().ping(uuid, ping); database.save().ping(uuid, ping);
} }
} }

View File

@ -5,6 +5,8 @@
package com.djrapitops.plan.system.processing.processors.player; package com.djrapitops.plan.system.processing.processors.player;
import com.djrapitops.plan.system.database.databases.Database; import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.database.databases.operation.CheckOperations;
import com.djrapitops.plan.system.database.databases.operation.SaveOperations;
import com.djrapitops.plan.system.processing.Processing; import com.djrapitops.plan.system.processing.Processing;
import com.djrapitops.plugin.task.AbsRunnable; import com.djrapitops.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.Verify; import com.djrapitops.plugin.utilities.Verify;
@ -25,6 +27,7 @@ public class RegisterProcessor extends AbsRunnable {
private final Runnable[] afterProcess; private final Runnable[] afterProcess;
private Processing processing; private Processing processing;
private Database database;
public RegisterProcessor(UUID uuid, Supplier<Long> registered, String name, Runnable... afterProcess) { public RegisterProcessor(UUID uuid, Supplier<Long> registered, String name, Runnable... afterProcess) {
this.uuid = uuid; this.uuid = uuid;
@ -35,14 +38,16 @@ public class RegisterProcessor extends AbsRunnable {
@Override @Override
public void run() { public void run() {
Database db = Database.getActive();
Verify.nullCheck(uuid, () -> new IllegalStateException("UUID was null")); Verify.nullCheck(uuid, () -> new IllegalStateException("UUID was null"));
CheckOperations check = database.check();
SaveOperations save = database.save();
try { try {
if (!db.check().isPlayerRegistered(uuid)) { if (!check.isPlayerRegistered(uuid)) {
db.save().registerNewUser(uuid, registered.get(), name); save.registerNewUser(uuid, registered.get(), name);
} }
if (!db.check().isPlayerRegisteredOnThisServer(uuid)) { if (!check.isPlayerRegisteredOnThisServer(uuid)) {
db.save().registerNewUserOnThisServer(uuid, registered.get()); save.registerNewUserOnThisServer(uuid, registered.get());
} }
} finally { } finally {
for (Runnable runnable : afterProcess) { for (Runnable runnable : afterProcess) {

View File

@ -2,11 +2,9 @@ package com.djrapitops.plan.system.settings;
import com.djrapitops.plan.system.settings.config.ConfigSystem; import com.djrapitops.plan.system.settings.config.ConfigSystem;
import com.djrapitops.plan.system.settings.config.Setting; import com.djrapitops.plan.system.settings.config.Setting;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.config.Config; import com.djrapitops.plugin.config.Config;
import com.djrapitops.plugin.utilities.Verify; import com.djrapitops.plugin.utilities.Verify;
import java.io.IOException;
import java.util.List; import java.util.List;
/** /**
@ -114,15 +112,6 @@ public enum Settings implements Setting {
this.configPath = path; this.configPath = path;
} }
@Deprecated
public static void save() {
try {
ConfigSystem.getConfig_Old().save();
} catch (IOException e) {
Log.toLog(Settings.class, e);
}
}
/** /**
* If the settings is a boolean, this method should be used. * If the settings is a boolean, this method should be used.
* *
@ -136,11 +125,6 @@ public enum Settings implements Setting {
return getConfig().getBoolean(configPath); return getConfig().getBoolean(configPath);
} }
@Deprecated
public boolean isFalse() {
return !isTrue();
}
/** /**
* If the settings is a String, this method should be used. * If the settings is a String, this method should be used.
* *

View File

@ -18,7 +18,7 @@ import com.djrapitops.plugin.task.RunnableFactory;
*/ */
public abstract class TaskSystem implements SubSystem { public abstract class TaskSystem implements SubSystem {
protected TPSCountTimer tpsCountTimer; protected final TPSCountTimer tpsCountTimer;
protected final RunnableFactory runnableFactory; protected final RunnableFactory runnableFactory;
public TaskSystem(RunnableFactory runnableFactory, TPSCountTimer tpsCountTimer) { public TaskSystem(RunnableFactory runnableFactory, TPSCountTimer tpsCountTimer) {

View File

@ -4,14 +4,19 @@
*/ */
package com.djrapitops.plan.system.webserver; package com.djrapitops.plan.system.webserver;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.locale.Locale; import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.settings.Settings; import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plan.system.settings.config.PlanConfig;
import com.djrapitops.plan.system.webserver.auth.Authentication; import com.djrapitops.plan.system.webserver.auth.Authentication;
import com.djrapitops.plan.system.webserver.auth.BasicAuthentication; import com.djrapitops.plan.system.webserver.auth.BasicAuthentication;
import com.djrapitops.plan.system.webserver.response.PromptAuthorizationResponse; import com.djrapitops.plan.system.webserver.response.PromptAuthorizationResponse;
import com.djrapitops.plan.system.webserver.response.Response; import com.djrapitops.plan.system.webserver.response.Response;
import com.djrapitops.plugin.api.Benchmark; import com.djrapitops.plugin.benchmarking.Benchmark;
import com.djrapitops.plugin.api.utility.log.Log; import com.djrapitops.plugin.benchmarking.Timings;
import com.djrapitops.plugin.logging.L;
import com.djrapitops.plugin.logging.console.PluginLogger;
import com.djrapitops.plugin.logging.error.ErrorHandler;
import com.djrapitops.plugin.utilities.Verify; import com.djrapitops.plugin.utilities.Verify;
import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpExchange;
@ -30,12 +35,30 @@ import java.util.List;
public class RequestHandler implements HttpHandler { public class RequestHandler implements HttpHandler {
private final Locale locale; private final Locale locale;
private final PlanConfig config;
private final Database database;
private final ResponseHandler responseHandler; private final ResponseHandler responseHandler;
private final Timings timings;
private final PluginLogger logger;
private final ErrorHandler errorHandler;
@Inject @Inject
RequestHandler(Locale locale, ResponseHandler responseHandler) { RequestHandler(
Locale locale,
PlanConfig config,
Database database,
ResponseHandler responseHandler,
Timings timings,
PluginLogger logger,
ErrorHandler errorHandler
) {
this.locale = locale; this.locale = locale;
this.config = config;
this.database = database;
this.responseHandler = responseHandler; this.responseHandler = responseHandler;
this.timings = timings;
this.logger = logger;
this.errorHandler = errorHandler;
} }
@Override @Override
@ -46,8 +69,10 @@ public class RequestHandler implements HttpHandler {
request.setAuth(getAuthorization(requestHeaders)); request.setAuth(getAuthorization(requestHeaders));
String requestString = request.toString(); String requestString = request.toString();
Benchmark.start("", requestString); timings.start(requestString);
int responseCode = -1; int responseCode = -1;
boolean inDevMode = config.isTrue(Settings.DEV_MODE);
try { try {
Response response = responseHandler.getResponse(request); Response response = responseHandler.getResponse(request);
responseCode = response.getCode(); responseCode = response.getCode();
@ -58,14 +83,14 @@ public class RequestHandler implements HttpHandler {
response.setResponseHeaders(responseHeaders); response.setResponseHeaders(responseHeaders);
response.send(exchange, locale); response.send(exchange, locale);
} catch (Exception e) { } catch (Exception e) {
if (Settings.DEV_MODE.isTrue()) { if (inDevMode) {
Log.warn("THIS ERROR IS ONLY LOGGED IN DEV MODE:"); logger.warn("THIS ERROR IS ONLY LOGGED IN DEV MODE:");
Log.toLog(this.getClass(), e); errorHandler.log(L.WARN, this.getClass(), e);
} }
} finally { } finally {
exchange.close(); exchange.close();
if (Settings.DEV_MODE.isTrue()) { if (inDevMode) {
Log.debug(requestString + " Response code: " + responseCode + " took " + Benchmark.stop("", requestString) + " ms"); logger.debug(requestString + " Response code: " + responseCode + timings.end(requestString).map(Benchmark::toString).orElse("-"));
} }
} }
} }
@ -78,7 +103,7 @@ public class RequestHandler implements HttpHandler {
String authLine = authorization.get(0); String authLine = authorization.get(0);
if (authLine.contains("Basic ")) { if (authLine.contains("Basic ")) {
return new BasicAuthentication(authLine.split(" ")[1]); return new BasicAuthentication(authLine.split(" ")[1], database);
} }
return null; return null;
} }

View File

@ -22,10 +22,12 @@ import com.djrapitops.plan.utilities.PassEncryptUtil;
*/ */
public class BasicAuthentication implements Authentication { public class BasicAuthentication implements Authentication {
private String authenticationString; private final String authenticationString;
private final Database database;
public BasicAuthentication(String authenticationString) { public BasicAuthentication(String authenticationString, Database database) {
this.authenticationString = authenticationString; this.authenticationString = authenticationString;
this.database = database;
} }
@Override @Override
@ -41,8 +43,6 @@ public class BasicAuthentication implements Authentication {
String passwordRaw = userInfo[1]; String passwordRaw = userInfo[1];
try { try {
Database database = Database.getActive();
if (!database.check().doesWebUserExists(user)) { if (!database.check().doesWebUserExists(user)) {
throw new WebUserAuthException(FailReason.USER_DOES_NOT_EXIST, user); throw new WebUserAuthException(FailReason.USER_DOES_NOT_EXIST, user);
} }

View File

@ -1,10 +1,12 @@
package com.djrapitops.plan.system.webserver.response; package com.djrapitops.plan.system.webserver.response;
import com.djrapitops.plan.api.exceptions.ParseException;
import com.djrapitops.plan.system.database.databases.Database; import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.locale.Locale; import com.djrapitops.plan.system.locale.Locale;
import com.djrapitops.plan.system.locale.lang.ErrorPageLang; import com.djrapitops.plan.system.locale.lang.ErrorPageLang;
import com.djrapitops.plan.system.settings.theme.Theme; import com.djrapitops.plan.system.settings.theme.Theme;
import com.djrapitops.plan.system.webserver.response.errors.ErrorResponse; import com.djrapitops.plan.system.webserver.response.errors.ErrorResponse;
import com.djrapitops.plan.system.webserver.response.errors.InternalErrorResponse;
import com.djrapitops.plan.system.webserver.response.errors.NotFoundResponse; import com.djrapitops.plan.system.webserver.response.errors.NotFoundResponse;
import com.djrapitops.plan.system.webserver.response.pages.*; import com.djrapitops.plan.system.webserver.response.pages.*;
import com.djrapitops.plan.utilities.html.pages.PageFactory; import com.djrapitops.plan.utilities.html.pages.PageFactory;
@ -44,7 +46,19 @@ public class ResponseFactory {
} }
public Response playersPageResponse() { public Response playersPageResponse() {
return new PlayersPageResponse(pageFactory.playersPage()); try {
return new PlayersPageResponse(pageFactory.playersPage());
} catch (ParseException e) {
return new InternalErrorResponse("Failed to parse players page", e);
}
}
public Response networkPageResponse() {
try {
return new NetworkPageResponse(pageFactory.networkPage());
} catch (ParseException e) {
return new InternalErrorResponse("Failed to parse network page", e);
}
} }
public RawDataResponse rawPlayerPageResponse(UUID uuid) { public RawDataResponse rawPlayerPageResponse(UUID uuid) {

View File

@ -1,8 +1,6 @@
package com.djrapitops.plan.system.webserver.response.pages; package com.djrapitops.plan.system.webserver.response.pages;
import com.djrapitops.plan.api.exceptions.ParseException; import com.djrapitops.plan.api.exceptions.ParseException;
import com.djrapitops.plan.data.store.containers.NetworkContainer;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.webserver.response.Response; import com.djrapitops.plan.system.webserver.response.Response;
import com.djrapitops.plan.utilities.html.pages.NetworkPage; import com.djrapitops.plan.utilities.html.pages.NetworkPage;
@ -13,9 +11,8 @@ import com.djrapitops.plan.utilities.html.pages.NetworkPage;
*/ */
public class NetworkPageResponse extends Response { public class NetworkPageResponse extends Response {
public NetworkPageResponse() throws ParseException { public NetworkPageResponse(NetworkPage networkPage) throws ParseException {
super.setHeader("HTTP/1.1 200 OK"); setHeader("HTTP/1.1 200 OK");
NetworkContainer networkContainer = Database.getActive().fetch().getNetworkContainer(); // Not cached, big. setContent(networkPage.toHtml());
setContent(new NetworkPage(networkContainer).toHtml());
} }
} }

View File

@ -2,9 +2,7 @@ package com.djrapitops.plan.system.webserver.response.pages;
import com.djrapitops.plan.api.exceptions.ParseException; import com.djrapitops.plan.api.exceptions.ParseException;
import com.djrapitops.plan.system.webserver.response.Response; import com.djrapitops.plan.system.webserver.response.Response;
import com.djrapitops.plan.system.webserver.response.errors.InternalErrorResponse;
import com.djrapitops.plan.utilities.html.pages.PlayersPage; import com.djrapitops.plan.utilities.html.pages.PlayersPage;
import com.djrapitops.plugin.api.utility.log.Log;
/** /**
* @author Rsl1122 * @author Rsl1122
@ -12,13 +10,8 @@ import com.djrapitops.plugin.api.utility.log.Log;
*/ */
public class PlayersPageResponse extends Response { public class PlayersPageResponse extends Response {
public PlayersPageResponse(PlayersPage playersPage) { public PlayersPageResponse(PlayersPage playersPage) throws ParseException {
super.setHeader("HTTP/1.1 200 OK"); setHeader("HTTP/1.1 200 OK");
try { setContent(playersPage.toHtml());
super.setContent(playersPage.toHtml());
} catch (ParseException e) {
Log.toLog(this.getClass(), e);
setContent(new InternalErrorResponse("/players", e).getContent());
}
} }
} }

View File

@ -1,7 +1,6 @@
package com.djrapitops.plan.utilities; package com.djrapitops.plan.utilities;
import com.djrapitops.plan.PlanPlugin; import com.djrapitops.plan.PlanPlugin;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.settings.Permissions; import com.djrapitops.plan.system.settings.Permissions;
import com.djrapitops.plan.system.settings.Settings; import com.djrapitops.plan.system.settings.Settings;
import com.djrapitops.plugin.api.TimeAmount; import com.djrapitops.plugin.api.TimeAmount;
@ -11,8 +10,6 @@ import com.djrapitops.plugin.command.ISender;
import java.io.Closeable; import java.io.Closeable;
import java.io.IOException; import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.TimeZone; import java.util.TimeZone;
/** /**
@ -30,6 +27,7 @@ public class MiscUtils {
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
@Deprecated
public static int getTimeZoneOffsetHours() { public static int getTimeZoneOffsetHours() {
if (Settings.USE_SERVER_TIME.isTrue()) { if (Settings.USE_SERVER_TIME.isTrue()) {
return -TimeZone.getDefault().getOffset(System.currentTimeMillis()) / (int) TimeAmount.HOUR.ms(); return -TimeZone.getDefault().getOffset(System.currentTimeMillis()) / (int) TimeAmount.HOUR.ms();
@ -75,20 +73,6 @@ public class MiscUtils {
return playerName; return playerName;
} }
/**
* Get matching player names from the offline players.
*
* @param search Part of a name to search for.
* @return Alphabetically sorted list of matching player names.
*/
@Deprecated
public static List<String> getMatchingPlayerNames(String search) {
Database db = Database.getActive();
List<String> matches = db.search().matchingPlayers(search);
Collections.sort(matches);
return matches;
}
public static void close(Closeable... close) { public static void close(Closeable... close) {
for (Closeable c : close) { for (Closeable c : close) {
if (c != null) { if (c != null) {

View File

@ -63,6 +63,7 @@ public class HtmlStructure {
} }
// TODO Rework into NetworkPage generation // TODO Rework into NetworkPage generation
@Deprecated
public static String createServerContainer() { public static String createServerContainer() {
ServerProperties properties = ServerInfo.getServerProperties_Old(); ServerProperties properties = ServerInfo.getServerProperties_Old();
int maxPlayers = properties.getMaxPlayers(); int maxPlayers = properties.getMaxPlayers();
@ -75,7 +76,7 @@ public class HtmlStructure {
String serverType = properties.getVersion(); String serverType = properties.getVersion();
String address = "../server/" + serverName; String address = "../server/" + serverName;
Database db = Database.getActive(); Database db = null; // TODO
UUID serverUUID = server.getUuid(); UUID serverUUID = server.getUuid();
String id = ThreadLocalRandom.current().nextInt(100) + serverUUID.toString().replace("-", ""); String id = ThreadLocalRandom.current().nextInt(100) + serverUUID.toString().replace("-", "");

View File

@ -8,7 +8,7 @@ import com.djrapitops.plan.api.exceptions.ParseException;
import com.djrapitops.plan.data.store.containers.NetworkContainer; import com.djrapitops.plan.data.store.containers.NetworkContainer;
import com.djrapitops.plan.data.store.keys.NetworkKeys; import com.djrapitops.plan.data.store.keys.NetworkKeys;
import com.djrapitops.plan.data.store.mutators.formatting.PlaceholderReplacer; import com.djrapitops.plan.data.store.mutators.formatting.PlaceholderReplacer;
import com.djrapitops.plan.system.info.server.ServerInfo; import com.djrapitops.plan.system.info.server.properties.ServerProperties;
import com.djrapitops.plan.system.webserver.cache.PageId; import com.djrapitops.plan.system.webserver.cache.PageId;
import com.djrapitops.plan.system.webserver.cache.ResponseCache; import com.djrapitops.plan.system.webserver.cache.ResponseCache;
import com.djrapitops.plan.system.webserver.response.pages.parts.NetworkPageContent; import com.djrapitops.plan.system.webserver.response.pages.parts.NetworkPageContent;
@ -25,14 +25,20 @@ public class NetworkPage implements Page {
private final NetworkContainer networkContainer; private final NetworkContainer networkContainer;
public NetworkPage(NetworkContainer networkContainer) { private final ServerProperties serverProperties;
public NetworkPage(
NetworkContainer networkContainer,
ServerProperties serverProperties
) {
this.networkContainer = networkContainer; this.networkContainer = networkContainer;
this.serverProperties = serverProperties;
} }
@Override @Override
public String toHtml() throws ParseException { public String toHtml() throws ParseException {
try { try {
networkContainer.putSupplier(NetworkKeys.PLAYERS_ONLINE, ServerInfo.getServerProperties_Old()::getOnlinePlayers); networkContainer.putSupplier(NetworkKeys.PLAYERS_ONLINE, serverProperties::getOnlinePlayers);
PlaceholderReplacer placeholderReplacer = new PlaceholderReplacer(); PlaceholderReplacer placeholderReplacer = new PlaceholderReplacer();
placeholderReplacer.addAllPlaceholdersFrom(networkContainer, placeholderReplacer.addAllPlaceholdersFrom(networkContainer,

View File

@ -1,6 +1,7 @@
package com.djrapitops.plan.utilities.html.pages; package com.djrapitops.plan.utilities.html.pages;
import com.djrapitops.plan.data.store.containers.AnalysisContainer; import com.djrapitops.plan.data.store.containers.AnalysisContainer;
import com.djrapitops.plan.data.store.containers.NetworkContainer;
import com.djrapitops.plan.data.store.containers.PlayerContainer; import com.djrapitops.plan.data.store.containers.PlayerContainer;
import com.djrapitops.plan.system.database.databases.Database; import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.info.connection.ConnectionSystem; import com.djrapitops.plan.system.info.connection.ConnectionSystem;
@ -74,4 +75,9 @@ public class PageFactory {
Map<UUID, String> serverNames = database.get().fetch().getServerNames(); Map<UUID, String> serverNames = database.get().fetch().getServerNames();
return new InspectPage(player, serverNames, config.get(), serverInfo.get(), timings.get()); return new InspectPage(player, serverNames, config.get(), serverInfo.get(), timings.get());
} }
public NetworkPage networkPage() {
NetworkContainer networkContainer = database.get().fetch().getNetworkContainer(); // Not cached, big.
return new NetworkPage(networkContainer, serverInfo.get().getServerProperties());
}
} }

View File

@ -1,7 +1,6 @@
package com.djrapitops.plan.utilities.metrics; package com.djrapitops.plan.utilities.metrics;
import com.djrapitops.plan.Plan; import com.djrapitops.plan.Plan;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plugin.api.Check; import com.djrapitops.plugin.api.Check;
import com.djrapitops.plugin.api.utility.log.Log; import com.djrapitops.plugin.api.utility.log.Log;
import org.bstats.bukkit.Metrics; import org.bstats.bukkit.Metrics;
@ -28,7 +27,7 @@ public class BStatsBukkit {
if ("CraftBukkit".equals(serverType) && Check.isSpigotAvailable()) { if ("CraftBukkit".equals(serverType) && Check.isSpigotAvailable()) {
serverType = "Spigot"; serverType = "Spigot";
} }
String databaseType = Database.getActive().getName(); String databaseType = plugin.getSystem().getDatabaseSystem().getActiveDatabase().getName();
addStringSettingPie("server_type", serverType); addStringSettingPie("server_type", serverType);
addStringSettingPie("database_type", databaseType); addStringSettingPie("database_type", databaseType);

View File

@ -33,21 +33,6 @@ public class UUIDUtility {
this.errorHandler = errorHandler; this.errorHandler = errorHandler;
} }
/**
* Get UUID of a player.
*
* @param playerName Player's name
* @return UUID of the player.
*/
@Deprecated
public static UUID getUUIDOf_Old(String playerName) {
try {
return Database.getActive().fetch().getUuidOf(playerName);
} catch (Exception e) {
return null;
}
}
/** /**
* Get UUID of a player. * Get UUID of a player.
* *

View File

@ -1,6 +1,7 @@
package com.djrapitops.plan.system.cache; package com.djrapitops.plan.system.cache;
import com.djrapitops.plan.data.container.Session; import com.djrapitops.plan.data.container.Session;
import com.djrapitops.plan.system.database.databases.Database;
import org.junit.Before; import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.ClassRule; import org.junit.ClassRule;
@ -23,6 +24,8 @@ public class SessionCacheTest {
private Session session; private Session session;
private final UUID uuid = TestConstants.PLAYER_ONE_UUID; private final UUID uuid = TestConstants.PLAYER_ONE_UUID;
private Database database; // TODO
@BeforeClass @BeforeClass
public static void setUpClass() throws Exception { public static void setUpClass() throws Exception {
SystemMockUtil.setUp(temporaryFolder.getRoot()) SystemMockUtil.setUp(temporaryFolder.getRoot())
@ -31,14 +34,14 @@ public class SessionCacheTest {
@Before @Before
public void setUp() { public void setUp() {
sessionCache = new SessionCache(); sessionCache = new SessionCache(database);
session = new Session(uuid, 12345L, "World1", "SURVIVAL"); session = new Session(uuid, 12345L, "World1", "SURVIVAL");
sessionCache.cacheSession(uuid, session); sessionCache.cacheSession(uuid, session);
} }
@Test @Test
public void testAtomity() { public void testAtomity() {
SessionCache reloaded = new SessionCache(); SessionCache reloaded = new SessionCache(database);
Optional<Session> cachedSession = SessionCache.getCachedSession(uuid); Optional<Session> cachedSession = SessionCache.getCachedSession(uuid);
assertTrue(cachedSession.isPresent()); assertTrue(cachedSession.isPresent());
assertEquals(session, cachedSession.get()); assertEquals(session, cachedSession.get());

View File

@ -93,7 +93,6 @@ public class SQLiteTest {
@Before @Before
public void setUp() { public void setUp() {
assertEquals(db, Database.getActive());
System.out.println("\n-- Clearing Test Database --"); System.out.println("\n-- Clearing Test Database --");
db.remove().everything(); db.remove().everything();
ServerTable serverTable = db.getServerTable(); ServerTable serverTable = db.getServerTable();

View File

@ -7,17 +7,12 @@ package com.djrapitops.plan.utilities;
import com.djrapitops.plan.Plan; import com.djrapitops.plan.Plan;
import com.djrapitops.plan.data.store.objects.Nickname; import com.djrapitops.plan.data.store.objects.Nickname;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plan.system.database.databases.sql.SQLDB; import com.djrapitops.plan.system.database.databases.sql.SQLDB;
import com.djrapitops.plan.system.database.databases.sql.tables.UsersTable; import com.djrapitops.plan.system.database.databases.sql.tables.UsersTable;
import com.djrapitops.plan.system.info.server.Server;
import com.djrapitops.plugin.StaticHolder; import com.djrapitops.plugin.StaticHolder;
import com.djrapitops.plugin.command.ISender; import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.bukkit.BukkitCMDSender; import com.djrapitops.plugin.command.bukkit.BukkitCMDSender;
import org.junit.Before; import org.junit.*;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder; import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
@ -50,12 +45,13 @@ public class MiscUtilsTest {
.enableDatabaseSystem() .enableDatabaseSystem()
.enableServerInfoSystem(); .enableServerInfoSystem();
Database.getActive().save().serverInfoForThisServer(new Server(-1, TestConstants.SERVER_UUID, "ServerName", "", 20)); // Database.getActive().save().serverInfoForThisServer(new Server(-1, TestConstants.SERVER_UUID, "ServerName", "", 20));
} }
@Before @Before
public void setUp() { public void setUp() {
db = (SQLDB) Database.getActive(); db = null; // TODO;
Assume.assumeNotNull(db);
} }
@Test @Test
@ -123,6 +119,7 @@ public class MiscUtilsTest {
assertEquals(expResult, result); assertEquals(expResult, result);
} }
// TODO Move to database test
@Test @Test
public void testGetMatchingNames() { public void testGetMatchingNames() {
String exp1 = "TestName"; String exp1 = "TestName";
@ -135,7 +132,7 @@ public class MiscUtilsTest {
String search = "testname"; String search = "testname";
List<String> result = MiscUtils.getMatchingPlayerNames(search); List<String> result = db.search().matchingPlayers(search);
assertNotNull(result); assertNotNull(result);
assertEquals(2, result.size()); assertEquals(2, result.size());
@ -143,6 +140,7 @@ public class MiscUtilsTest {
assertEquals(exp2, result.get(1)); assertEquals(exp2, result.get(1));
} }
// TODO Move to database test
@Test @Test
public void testGetMatchingNickNames() { public void testGetMatchingNickNames() {
UUID uuid = UUID.randomUUID(); UUID uuid = UUID.randomUUID();
@ -156,7 +154,7 @@ public class MiscUtilsTest {
String search = "2"; String search = "2";
List<String> result = MiscUtils.getMatchingPlayerNames(search); List<String> result = db.search().matchingPlayers(search);
assertNotNull(result); assertNotNull(result);
assertEquals(1, result.size()); assertEquals(1, result.size());