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.locale.Locale;
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.utilities.metrics.BStatsBukkit;
import com.djrapitops.plugin.BukkitPlugin;
@ -83,11 +81,13 @@ interface PlanComponent {
class BukkitPlanModule {
@Provides
PlanPlugin providePlanPlugin(Plan plan) {
return plan;
@Singleton
PlanPlugin providePlanPlugin(Plan plugin) {
return plugin;
}
@Provides
@Singleton
@Named("mainCommand")
CommandNode provideMainCommand(PlanCommand command) {
return command;
@ -124,7 +124,8 @@ public class Plan extends BukkitPlugin implements PlanPlugin {
locale = system.getLocaleSystem().getLocale();
system.enable();
ImporterManager.registerImporter(new OfflinePlayerImporter());
// TODO Refactor into ImportSystem
// ImporterManager.registerImporter(new OfflinePlayerImporter());
new BStatsBukkit(this).registerMetrics();

View File

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

View File

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

View File

@ -25,15 +25,23 @@ public class InfoCommand extends CommandNode {
private final PlanPlugin plugin;
private final Locale locale;
private final Database database;
private final ConnectionSystem connectionSystem;
private final VersionCheckSystem versionCheckSystem;
@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);
this.plugin = plugin;
this.locale = locale;
this.database = database;
this.connectionSystem = connectionSystem;
this.versionCheckSystem = versionCheckSystem;
@ -52,7 +60,7 @@ public class InfoCommand extends CommandNode {
"",
locale.getString(CommandLang.INFO_VERSION, plugin.getVersion()),
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),
"",
">"

View File

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

View File

@ -1,6 +1,5 @@
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.Type;
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.time.WorldTimes;
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.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.ThemeVal;
import com.djrapitops.plan.utilities.MiscUtils;
@ -50,6 +49,12 @@ public class AnalysisContainer extends DataContainer {
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");
public AnalysisContainer(ServerContainer serverContainer) {
@ -90,11 +95,11 @@ public class AnalysisContainer extends DataContainer {
putRawData(AnalysisKeys.ANALYSIS_TIME_MONTH_AGO, now - TimeAmount.MONTH.ms());
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);
putRawData(AnalysisKeys.FIRST_DAY, 1);
putRawData(AnalysisKeys.TPS_MEDIUM, Settings.THEME_GRAPH_TPS_THRESHOLD_MED.getNumber());
putRawData(AnalysisKeys.TPS_HIGH, Settings.THEME_GRAPH_TPS_THRESHOLD_HIGH.getNumber());
putRawData(AnalysisKeys.TPS_MEDIUM, config.getNumber(Settings.THEME_GRAPH_TPS_THRESHOLD_MED));
putRawData(AnalysisKeys.TPS_HIGH, config.getNumber(Settings.THEME_GRAPH_TPS_THRESHOLD_HIGH));
addServerProperties();
addThemeColors();
@ -105,24 +110,23 @@ public class AnalysisContainer extends DataContainer {
getUnsafe(serverNames).getOrDefault(serverContainer.getUnsafe(ServerKeys.SERVER_UUID), "Plan")
);
ServerProperties serverProperties = ServerInfo.getServerProperties_Old();
putRawData(AnalysisKeys.PLAYERS_MAX, serverProperties.getMaxPlayers());
putRawData(AnalysisKeys.PLAYERS_ONLINE, serverProperties.getOnlinePlayers());
}
private void addThemeColors() {
putRawData(AnalysisKeys.ACTIVITY_PIE_COLORS, Theme.getValue_Old(ThemeVal.GRAPH_ACTIVITY_PIE));
putRawData(AnalysisKeys.GM_PIE_COLORS, Theme.getValue_Old(ThemeVal.GRAPH_GM_PIE));
putRawData(AnalysisKeys.PLAYERS_GRAPH_COLOR, Theme.getValue_Old(ThemeVal.GRAPH_PLAYERS_ONLINE));
putRawData(AnalysisKeys.TPS_LOW_COLOR, Theme.getValue_Old(ThemeVal.GRAPH_TPS_LOW));
putRawData(AnalysisKeys.TPS_MEDIUM_COLOR, Theme.getValue_Old(ThemeVal.GRAPH_TPS_MED));
putRawData(AnalysisKeys.TPS_HIGH_COLOR, Theme.getValue_Old(ThemeVal.GRAPH_TPS_HIGH));
putRawData(AnalysisKeys.WORLD_MAP_LOW_COLOR, Theme.getValue_Old(ThemeVal.WORLD_MAP_LOW));
putRawData(AnalysisKeys.WORLD_MAP_HIGH_COLOR, Theme.getValue_Old(ThemeVal.WORLD_MAP_HIGH));
putRawData(AnalysisKeys.WORLD_PIE_COLORS, Theme.getValue_Old(ThemeVal.GRAPH_WORLD_PIE));
putRawData(AnalysisKeys.AVG_PING_COLOR, Theme.getValue_Old(ThemeVal.GRAPH_AVG_PING));
putRawData(AnalysisKeys.MAX_PING_COLOR, Theme.getValue_Old(ThemeVal.GRAPH_MAX_PING));
putRawData(AnalysisKeys.MIN_PING_COLOR, Theme.getValue_Old(ThemeVal.GRAPH_MIN_PING));
putRawData(AnalysisKeys.ACTIVITY_PIE_COLORS, theme.getValue(ThemeVal.GRAPH_ACTIVITY_PIE));
putRawData(AnalysisKeys.GM_PIE_COLORS, theme.getValue(ThemeVal.GRAPH_GM_PIE));
putRawData(AnalysisKeys.PLAYERS_GRAPH_COLOR, theme.getValue(ThemeVal.GRAPH_PLAYERS_ONLINE));
putRawData(AnalysisKeys.TPS_LOW_COLOR, theme.getValue(ThemeVal.GRAPH_TPS_LOW));
putRawData(AnalysisKeys.TPS_MEDIUM_COLOR, theme.getValue(ThemeVal.GRAPH_TPS_MED));
putRawData(AnalysisKeys.TPS_HIGH_COLOR, theme.getValue(ThemeVal.GRAPH_TPS_HIGH));
putRawData(AnalysisKeys.WORLD_MAP_LOW_COLOR, theme.getValue(ThemeVal.WORLD_MAP_LOW));
putRawData(AnalysisKeys.WORLD_MAP_HIGH_COLOR, theme.getValue(ThemeVal.WORLD_MAP_HIGH));
putRawData(AnalysisKeys.WORLD_PIE_COLORS, theme.getValue(ThemeVal.GRAPH_WORLD_PIE));
putRawData(AnalysisKeys.AVG_PING_COLOR, theme.getValue(ThemeVal.GRAPH_AVG_PING));
putRawData(AnalysisKeys.MAX_PING_COLOR, theme.getValue(ThemeVal.GRAPH_MAX_PING));
putRawData(AnalysisKeys.MIN_PING_COLOR, theme.getValue(ThemeVal.GRAPH_MIN_PING));
}
private void addPlayerSuppliers() {
@ -260,7 +264,7 @@ public class AnalysisContainer extends DataContainer {
private void addSessionSuppliers() {
Key<SessionAccordion> sessionAccordion = new Key<>(SessionAccordion.class, "SESSION_ACCORDION");
putSupplier(serverNames, () -> Database.getActive().fetch().getServerNames());
putSupplier(serverNames, () -> database.fetch().getServerNames());
putSupplier(sessionAccordion, () -> SessionAccordion.forServer(
getUnsafe(AnalysisKeys.SESSIONS_MUTATOR).all(),
getSupplier(serverNames),

View File

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

View File

@ -6,6 +6,10 @@ package com.djrapitops.plan.system;
* @author Rsl1122
*/
public class DebugChannels {
public static final String INFO_REQUESTS = "InfoRequests";
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
public DataCache(Database database) {
super(database);
playerNames = new HashMap<>();
displayNames = new HashMap<>();
uuids = new HashMap<>();

View File

@ -1,10 +1,8 @@
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.store.keys.SessionKeys;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.utilities.Verify;
import java.util.HashMap;
@ -22,6 +20,12 @@ public class SessionCache {
private static final Map<UUID, Session> activeSessions = new HashMap<>();
private final Database database;
public SessionCache(Database database) {
this.database = database;
}
@Deprecated
public static SessionCache getInstance() {
SessionCache dataCache = CacheSystem.getInstance().getDataCache();
@ -60,6 +64,13 @@ public class SessionCache {
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) {
Session session = activeSessions.get(uuid);
if (session == null) {
@ -70,9 +81,8 @@ public class SessionCache {
}
try {
session.endSession(time);
Database.getActive().save().session(uuid, session);
} catch (DBOpException e) {
Log.toLog(this.getClass(), e);
// Might throw a DBOpException
database.save().session(uuid, session);
} finally {
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.database.DBException;
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.database.databases.Database;
import com.djrapitops.plan.system.locale.Locale;
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.logging.L;
import com.djrapitops.plugin.logging.console.PluginLogger;
import com.djrapitops.plugin.logging.error.ErrorHandler;
import com.djrapitops.plugin.utilities.Verify;
@ -38,7 +37,12 @@ public abstract class DBSystem implements SubSystem {
protected Database db;
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.logger = logger;
this.timings = timings;
@ -46,13 +50,6 @@ public abstract class DBSystem implements SubSystem {
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) {
for (Database database : getDatabases()) {
String dbConfigName = database.getConfigName();
@ -74,7 +71,7 @@ public abstract class DBSystem implements SubSystem {
db.close();
}
} 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 {
db.init();
db.scheduleClean(1L);
Log.info(locale.getString(PluginLang.ENABLED_DATABASE, db.getName()));
logger.info(locale.getString(PluginLang.ENABLED_DATABASE, db.getName()));
} catch (DBInitException e) {
Throwable cause = e.getCause();
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.DBInitException;
import com.djrapitops.plan.system.database.DBSystem;
import com.djrapitops.plan.system.database.databases.operation.*;
import com.djrapitops.plugin.utilities.Verify;
/**
* Abstract class representing a Database.
@ -17,13 +15,6 @@ public abstract class Database {
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 BackupOperations backup();
@ -40,13 +31,6 @@ public abstract class Database {
public abstract SaveOperations save();
/**
* Used to get the name of the database type.
* <p>
* Thread safe.
*
* @return SQLite/MySQL
*/
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.config.PlanConfig;
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.console.PluginLogger;
import com.djrapitops.plugin.logging.error.ErrorHandler;
@ -31,9 +31,15 @@ public class MySQLDB extends SQLDB {
protected volatile DataSource dataSource;
@Inject
public MySQLDB(Locale locale, PlanConfig config,
RunnableFactory runnableFactory, PluginLogger pluginLogger, ErrorHandler errorHandler) {
super(locale, config, runnableFactory, pluginLogger, errorHandler);
public MySQLDB(
Locale locale,
PlanConfig config,
RunnableFactory runnableFactory,
PluginLogger pluginLogger,
Timings timings,
ErrorHandler errorHandler
) {
super(locale, config, runnableFactory, pluginLogger, timings, errorHandler);
}
private static synchronized void increment() {
@ -62,7 +68,7 @@ public class MySQLDB extends SQLDB {
String launchOptions = config.getString(Settings.DB_LAUNCH_OPTIONS);
if (launchOptions.isEmpty() || !launchOptions.startsWith("?") || launchOptions.endsWith("&")) {
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);
@ -131,6 +137,11 @@ public class MySQLDB extends SQLDB {
returnToPool(connection);
}
@Override
public boolean isUsingMySQL() {
return true;
}
@Override
public boolean equals(Object o) {
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.config.PlanConfig;
import com.djrapitops.plugin.api.TimeAmount;
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;
@ -44,7 +45,8 @@ public abstract class SQLDB extends Database {
protected final PlanConfig config;
protected final RunnableFactory runnableFactory;
protected final PluginLogger logger;
protected ErrorHandler errorHandler;
protected final Timings timings;
protected final ErrorHandler errorHandler;
private final UsersTable usersTable;
private final UserInfoTable userInfoTable;
@ -70,18 +72,23 @@ public abstract class SQLDB extends Database {
private final SQLSaveOps saveOps;
private final SQLTransferOps transferOps;
private final boolean usingMySQL;
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.config = config;
this.runnableFactory = runnableFactory;
this.logger = logger;
this.timings = timings;
this.errorHandler = errorHandler;
usingMySQL = this instanceof MySQLDB;
serverTable = new ServerTable(this);
securityTable = new SecurityTable(this);
@ -274,25 +281,12 @@ public abstract class SQLDB extends Database {
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) {
Connection connection = null;
try {
connection = getConnection();
// Inject Timings to the statement for benchmarking
statement.setTimings(timings);
try (PreparedStatement preparedStatement = connection.prepareStatement(statement.getSql())) {
return statement.execute(preparedStatement);
}
@ -329,6 +323,8 @@ public abstract class SQLDB extends Database {
Connection connection = null;
try {
connection = getConnection();
// Inject Timings to the statement for benchmarking
statement.setTimings(timings);
try (PreparedStatement preparedStatement = connection.prepareStatement(statement.getSql())) {
statement.executeBatch(preparedStatement);
}
@ -343,6 +339,8 @@ public abstract class SQLDB extends Database {
Connection connection = null;
try {
connection = getConnection();
// Inject Timings to the statement for benchmarking
statement.setTimings(timings);
try (PreparedStatement preparedStatement = connection.prepareStatement(statement.getSql())) {
return statement.executeQuery(preparedStatement);
}
@ -410,7 +408,7 @@ public abstract class SQLDB extends Database {
}
public boolean isUsingMySQL() {
return usingMySQL;
return false;
}
@Override
@ -458,11 +456,11 @@ public abstract class SQLDB extends Database {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SQLDB sqldb = (SQLDB) o;
return usingMySQL == sqldb.usingMySQL && getName().equals(sqldb.getName());
return getName().equals(sqldb.getName());
}
@Override
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.settings.config.PlanConfig;
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.console.PluginLogger;
import com.djrapitops.plugin.logging.error.ErrorHandler;
@ -29,9 +29,16 @@ public class SQLiteDB extends SQLDB {
private Connection connection;
private PluginTask connectionPingTask;
public SQLiteDB(File databaseFile, Locale locale, PlanConfig config,
RunnableFactory runnableFactory, PluginLogger logger, ErrorHandler errorHandler) {
super(locale, config, runnableFactory, logger, errorHandler);
public SQLiteDB(
File databaseFile,
Locale locale,
PlanConfig config,
RunnableFactory runnableFactory,
PluginLogger logger,
Timings timings,
ErrorHandler errorHandler
) {
super(locale, config, runnableFactory, logger, timings, errorHandler);
dbName = databaseFile.getName();
this.databaseFile = databaseFile;
}
@ -86,7 +93,7 @@ public class SQLiteDB extends SQLDB {
resultSet = statement.executeQuery("/* ping */ SELECT 1");
}
} catch (SQLException e) {
Log.debug("Something went wrong during SQLite Connection upkeep task.");
logger.debug("Something went wrong during SQLite Connection upkeep task.");
try {
connection = getNewConnection(databaseFile);
} catch (SQLException e1) {
@ -174,17 +181,26 @@ public class SQLiteDB extends SQLDB {
private final PlanConfig config;
private final RunnableFactory runnableFactory;
private final PluginLogger logger;
private final Timings timings;
private final ErrorHandler errorHandler;
private FileSystem fileSystem;
@Inject
public Factory(Locale locale, PlanConfig config, FileSystem fileSystem,
RunnableFactory runnableFactory, PluginLogger logger, ErrorHandler errorHandler) {
public Factory(
Locale locale,
PlanConfig config,
FileSystem fileSystem,
RunnableFactory runnableFactory,
PluginLogger logger,
Timings timings,
ErrorHandler errorHandler
) {
this.locale = locale;
this.config = config;
this.fileSystem = fileSystem;
this.runnableFactory = runnableFactory;
this.logger = logger;
this.timings = timings;
this.errorHandler = errorHandler;
}
@ -197,7 +213,7 @@ public class SQLiteDB extends SQLDB {
}
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.settings.Settings;
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.error.ErrorHandler;
import com.djrapitops.plugin.task.RunnableFactory;
@ -23,9 +24,15 @@ import java.util.Optional;
public class SpongeMySQLDB extends MySQLDB {
@Inject
public SpongeMySQLDB(Locale locale, PlanConfig config,
RunnableFactory runnableFactory, PluginLogger pluginLogger, ErrorHandler errorHandler) {
super(locale, config, runnableFactory, pluginLogger, errorHandler);
public SpongeMySQLDB(
Locale locale,
PlanConfig config,
RunnableFactory runnableFactory,
PluginLogger pluginLogger,
Timings timings,
ErrorHandler errorHandler
) {
super(locale, config, runnableFactory, pluginLogger, timings, errorHandler);
}
@Override

View File

@ -13,11 +13,15 @@ public class SQLBackupOps extends SQLOps implements BackupOperations {
@Override
public void backup(Database toDatabase) {
BatchOperationTable toDB = new BatchOperationTable((SQLDB) toDatabase);
BatchOperationTable fromDB = new BatchOperationTable(db);
if (toDatabase instanceof SQLDB) {
BatchOperationTable toDB = new BatchOperationTable((SQLDB) toDatabase);
BatchOperationTable fromDB = new BatchOperationTable(db);
toDB.removeAllData();
fromDB.copyEverything(toDB);
toDB.removeAllData();
fromDB.copyEverything(toDB);
} else {
throw new IllegalArgumentException("Database was not a SQL database - backup not implemented.");
}
}
@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.sql.SQLDB;
import java.util.Collections;
import java.util.List;
public class SQLSearchOps extends SQLOps implements SearchOperations {
@ -13,6 +14,8 @@ public class SQLSearchOps extends SQLOps implements SearchOperations {
@Override
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.tables.GeoInfoTable;
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.UnknownHostException;
@ -83,10 +81,8 @@ public class IPAnonPatch extends Patch {
statement.setString(2, updatedInfo.getIpHash());
statement.setString(3, geoInfo.getIp());
statement.addBatch();
} catch (UnknownHostException | NoSuchAlgorithmException e) {
if (Settings.DEV_MODE.isTrue()) {
Log.toLog(this.getClass(), e);
}
} catch (UnknownHostException | NoSuchAlgorithmException ignore) {
// This ip is already anonymised or completely unusable.
}
}
});

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;
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.SQLException;
@ -16,39 +12,31 @@ import java.sql.SQLException;
*
* @author Rsl1122
*/
public abstract class ExecStatement {
private final String sql;
private final boolean devMode;
public abstract class ExecStatement extends AbstractSQLStatement {
public ExecStatement(String sql) {
this.sql = sql;
devMode = Settings.DEV_MODE.isTrue();
super(sql);
}
public boolean execute(PreparedStatement statement) throws SQLException {
Benchmark.start("SQL: " + sql);
startBenchmark();
try {
prepare(statement);
return statement.executeUpdate() > 0;
} finally {
statement.close();
if (devMode) {
Log.debug(Benchmark.stopAndFormat("SQL: " + sql));
}
stopBenchmark();
}
}
public void executeBatch(PreparedStatement statement) throws SQLException {
Benchmark.start("SQL: " + sql + " (Batch)");
startBatchBenchmark();
try {
prepare(statement);
statement.executeBatch();
} finally {
statement.close();
if (devMode) {
Log.debug(Benchmark.stopAndFormat("SQL: " + sql + " (Batch)"));
}
stopBatchBenchmark();
}
}

View File

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

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

View File

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

View File

@ -64,7 +64,7 @@ public class SaveDBSettingsRequest extends InfoRequestWithVariables implements S
if (Check.isBungeeAvailable()) {
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.");
}

View File

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

View File

@ -4,11 +4,15 @@
*/
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.UserImportData;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@ -18,8 +22,17 @@ import java.util.Set;
* @author Fuzzlemann
* @since 4.0.0
*/
@Singleton
public class OfflinePlayerImporter extends Importer {
@Inject
public OfflinePlayerImporter(
Database database,
ServerInfo serverInfo
) {
super(database, serverInfo);
}
@Override
public List<String> getNames() {
return Arrays.asList("offline", "offlineplayer");

View File

@ -16,12 +16,14 @@ public class CommandProcessor implements CriticalRunnable {
private final String command;
private Database database;
public CommandProcessor(String command) {
this.command = command;
}
@Override
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 Database database;
public TPSInsertProcessor(List<TPS> tpsList) {
this.tpsList = tpsList;
}
@ -45,6 +47,6 @@ public class TPSInsertProcessor implements CriticalRunnable {
.chunksLoaded(averageChunksLoaded)
.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 boolean op;
private Database database;
public BanAndOpProcessor(UUID uuid, Supplier<Boolean> banned, boolean op) {
this.uuid = uuid;
this.banned = banned;
@ -29,7 +31,7 @@ public class BanAndOpProcessor implements Runnable {
@Override
public void run() {
SaveOperations save = Database.getActive().save();
SaveOperations save = database.save();
save.banStatus(uuid, banned.get());
save.opStatus(uuid, op);
}

View File

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

View File

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

View File

@ -18,12 +18,14 @@ public class KickProcessor implements CriticalRunnable {
private final UUID uuid;
private Database database;
public KickProcessor(UUID uuid) {
this.uuid = uuid;
}
@Override
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.system.cache.DataCache;
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.processing.CriticalRunnable;
@ -24,6 +25,8 @@ public class NameProcessor implements CriticalRunnable {
private final String playerName;
private final Nickname nickname;
private Database database;
public NameProcessor(UUID uuid, String playerName, String displayName) {
this.uuid = uuid;
this.playerName = playerName;
@ -43,9 +46,8 @@ public class NameProcessor implements CriticalRunnable {
dataCache.updateNames(uuid, playerName, nickname.getName());
Database database = Database.getActive();
database.save().playerName(uuid, playerName);
database.save().playerDisplayName(uuid, nickname);
SaveOperations save = database.save();
save.playerName(uuid, playerName);
save.playerDisplayName(uuid, nickname);
}
}

View File

@ -26,6 +26,8 @@ public class PingInsertProcessor implements CriticalRunnable {
private final UUID uuid;
private final List<DateObj<Integer>> pingList;
private Database database;
public PingInsertProcessor(UUID uuid, List<DateObj<Integer>> pingList) {
this.uuid = uuid;
this.pingList = pingList;
@ -61,6 +63,6 @@ public class PingInsertProcessor implements CriticalRunnable {
maxValue,
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;
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.plugin.task.AbsRunnable;
import com.djrapitops.plugin.utilities.Verify;
@ -25,6 +27,7 @@ public class RegisterProcessor extends AbsRunnable {
private final Runnable[] afterProcess;
private Processing processing;
private Database database;
public RegisterProcessor(UUID uuid, Supplier<Long> registered, String name, Runnable... afterProcess) {
this.uuid = uuid;
@ -35,14 +38,16 @@ public class RegisterProcessor extends AbsRunnable {
@Override
public void run() {
Database db = Database.getActive();
Verify.nullCheck(uuid, () -> new IllegalStateException("UUID was null"));
CheckOperations check = database.check();
SaveOperations save = database.save();
try {
if (!db.check().isPlayerRegistered(uuid)) {
db.save().registerNewUser(uuid, registered.get(), name);
if (!check.isPlayerRegistered(uuid)) {
save.registerNewUser(uuid, registered.get(), name);
}
if (!db.check().isPlayerRegisteredOnThisServer(uuid)) {
db.save().registerNewUserOnThisServer(uuid, registered.get());
if (!check.isPlayerRegisteredOnThisServer(uuid)) {
save.registerNewUserOnThisServer(uuid, registered.get());
}
} finally {
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.Setting;
import com.djrapitops.plugin.api.utility.log.Log;
import com.djrapitops.plugin.config.Config;
import com.djrapitops.plugin.utilities.Verify;
import java.io.IOException;
import java.util.List;
/**
@ -114,15 +112,6 @@ public enum Settings implements Setting {
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.
*
@ -136,11 +125,6 @@ public enum Settings implements Setting {
return getConfig().getBoolean(configPath);
}
@Deprecated
public boolean isFalse() {
return !isTrue();
}
/**
* 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 {
protected TPSCountTimer tpsCountTimer;
protected final TPSCountTimer tpsCountTimer;
protected final RunnableFactory runnableFactory;
public TaskSystem(RunnableFactory runnableFactory, TPSCountTimer tpsCountTimer) {

View File

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

View File

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

View File

@ -1,10 +1,12 @@
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.locale.Locale;
import com.djrapitops.plan.system.locale.lang.ErrorPageLang;
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.InternalErrorResponse;
import com.djrapitops.plan.system.webserver.response.errors.NotFoundResponse;
import com.djrapitops.plan.system.webserver.response.pages.*;
import com.djrapitops.plan.utilities.html.pages.PageFactory;
@ -44,7 +46,19 @@ public class ResponseFactory {
}
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) {

View File

@ -1,8 +1,6 @@
package com.djrapitops.plan.system.webserver.response.pages;
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.utilities.html.pages.NetworkPage;
@ -13,9 +11,8 @@ import com.djrapitops.plan.utilities.html.pages.NetworkPage;
*/
public class NetworkPageResponse extends Response {
public NetworkPageResponse() throws ParseException {
super.setHeader("HTTP/1.1 200 OK");
NetworkContainer networkContainer = Database.getActive().fetch().getNetworkContainer(); // Not cached, big.
setContent(new NetworkPage(networkContainer).toHtml());
public NetworkPageResponse(NetworkPage networkPage) throws ParseException {
setHeader("HTTP/1.1 200 OK");
setContent(networkPage.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.system.webserver.response.Response;
import com.djrapitops.plan.system.webserver.response.errors.InternalErrorResponse;
import com.djrapitops.plan.utilities.html.pages.PlayersPage;
import com.djrapitops.plugin.api.utility.log.Log;
/**
* @author Rsl1122
@ -12,13 +10,8 @@ import com.djrapitops.plugin.api.utility.log.Log;
*/
public class PlayersPageResponse extends Response {
public PlayersPageResponse(PlayersPage playersPage) {
super.setHeader("HTTP/1.1 200 OK");
try {
super.setContent(playersPage.toHtml());
} catch (ParseException e) {
Log.toLog(this.getClass(), e);
setContent(new InternalErrorResponse("/players", e).getContent());
}
public PlayersPageResponse(PlayersPage playersPage) throws ParseException {
setHeader("HTTP/1.1 200 OK");
setContent(playersPage.toHtml());
}
}

View File

@ -1,7 +1,6 @@
package com.djrapitops.plan.utilities;
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.Settings;
import com.djrapitops.plugin.api.TimeAmount;
@ -11,8 +10,6 @@ import com.djrapitops.plugin.command.ISender;
import java.io.Closeable;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.TimeZone;
/**
@ -30,6 +27,7 @@ public class MiscUtils {
throw new IllegalStateException("Utility class");
}
@Deprecated
public static int getTimeZoneOffsetHours() {
if (Settings.USE_SERVER_TIME.isTrue()) {
return -TimeZone.getDefault().getOffset(System.currentTimeMillis()) / (int) TimeAmount.HOUR.ms();
@ -75,20 +73,6 @@ public class MiscUtils {
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) {
for (Closeable c : close) {
if (c != null) {

View File

@ -63,6 +63,7 @@ public class HtmlStructure {
}
// TODO Rework into NetworkPage generation
@Deprecated
public static String createServerContainer() {
ServerProperties properties = ServerInfo.getServerProperties_Old();
int maxPlayers = properties.getMaxPlayers();
@ -75,7 +76,7 @@ public class HtmlStructure {
String serverType = properties.getVersion();
String address = "../server/" + serverName;
Database db = Database.getActive();
Database db = null; // TODO
UUID serverUUID = server.getUuid();
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.keys.NetworkKeys;
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.ResponseCache;
import com.djrapitops.plan.system.webserver.response.pages.parts.NetworkPageContent;
@ -25,14 +25,20 @@ public class NetworkPage implements Page {
private final NetworkContainer networkContainer;
public NetworkPage(NetworkContainer networkContainer) {
private final ServerProperties serverProperties;
public NetworkPage(
NetworkContainer networkContainer,
ServerProperties serverProperties
) {
this.networkContainer = networkContainer;
this.serverProperties = serverProperties;
}
@Override
public String toHtml() throws ParseException {
try {
networkContainer.putSupplier(NetworkKeys.PLAYERS_ONLINE, ServerInfo.getServerProperties_Old()::getOnlinePlayers);
networkContainer.putSupplier(NetworkKeys.PLAYERS_ONLINE, serverProperties::getOnlinePlayers);
PlaceholderReplacer placeholderReplacer = new PlaceholderReplacer();
placeholderReplacer.addAllPlaceholdersFrom(networkContainer,

View File

@ -1,6 +1,7 @@
package com.djrapitops.plan.utilities.html.pages;
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.system.database.databases.Database;
import com.djrapitops.plan.system.info.connection.ConnectionSystem;
@ -74,4 +75,9 @@ public class PageFactory {
Map<UUID, String> serverNames = database.get().fetch().getServerNames();
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;
import com.djrapitops.plan.Plan;
import com.djrapitops.plan.system.database.databases.Database;
import com.djrapitops.plugin.api.Check;
import com.djrapitops.plugin.api.utility.log.Log;
import org.bstats.bukkit.Metrics;
@ -28,7 +27,7 @@ public class BStatsBukkit {
if ("CraftBukkit".equals(serverType) && Check.isSpigotAvailable()) {
serverType = "Spigot";
}
String databaseType = Database.getActive().getName();
String databaseType = plugin.getSystem().getDatabaseSystem().getActiveDatabase().getName();
addStringSettingPie("server_type", serverType);
addStringSettingPie("database_type", databaseType);

View File

@ -33,21 +33,6 @@ public class UUIDUtility {
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.
*

View File

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

View File

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

View File

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