Main class cleanup, take 1

This commit is contained in:
Gabriele C 2016-08-09 01:05:22 +02:00
parent eb7487ca84
commit bf71f98fae
3 changed files with 40 additions and 77 deletions

View File

@ -18,7 +18,7 @@ import fr.xephi.authme.datasource.MySQL;
import fr.xephi.authme.datasource.SQLite; import fr.xephi.authme.datasource.SQLite;
import fr.xephi.authme.hooks.PluginHooks; import fr.xephi.authme.hooks.PluginHooks;
import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.initialization.DataFolder;
import fr.xephi.authme.initialization.MetricsStarter; import fr.xephi.authme.initialization.MetricsManager;
import fr.xephi.authme.listener.BlockListener; import fr.xephi.authme.listener.BlockListener;
import fr.xephi.authme.listener.EntityListener; import fr.xephi.authme.listener.EntityListener;
import fr.xephi.authme.listener.PlayerListener; import fr.xephi.authme.listener.PlayerListener;
@ -85,8 +85,11 @@ import static fr.xephi.authme.util.BukkitService.TICKS_PER_MINUTE;
*/ */
public class AuthMe extends JavaPlugin { public class AuthMe extends JavaPlugin {
// Name of the plugin. // Costants
private static final String PLUGIN_NAME = "AuthMeReloaded"; private static final String PLUGIN_NAME = "AuthMeReloaded";
private static final String LOG_FILENAME = "authme.log";
private static final int SQLITE_MAX_SIZE = 4000;
private final int CLEANUP_INTERVAL = 5 * TICKS_PER_MINUTE;
// Default version and build number values; // Default version and build number values;
private static String pluginVersion = "N/D"; private static String pluginVersion = "N/D";
@ -95,10 +98,6 @@ public class AuthMe extends JavaPlugin {
/* /*
* Private instances * Private instances
*/ */
// Plugin instance
private static AuthMe plugin;
private Management management; private Management management;
private CommandHandler commandHandler; private CommandHandler commandHandler;
private PermissionsManager permsMan; private PermissionsManager permsMan;
@ -128,16 +127,6 @@ public class AuthMe extends JavaPlugin {
super(loader, server, description, dataFolder, file); super(loader, server, description, dataFolder, file);
} }
/**
* Get the plugin's instance.
*
* @return AuthMe
*/
@Deprecated
public static AuthMe getInstance() {
return plugin;
}
/** /**
* Get the plugin's name. * Get the plugin's name.
* *
@ -165,47 +154,37 @@ public class AuthMe extends JavaPlugin {
return pluginBuildNumber; return pluginBuildNumber;
} }
// Get version and build number of the plugin
private void loadPluginInfo() {
String versionRaw = this.getDescription().getVersion();
int index = versionRaw.lastIndexOf("-");
if (index != -1) {
pluginVersion = versionRaw.substring(0, index);
pluginBuildNumber = versionRaw.substring(index + 1);
if (pluginBuildNumber.startsWith("b")) {
pluginBuildNumber = pluginBuildNumber.substring(1);
}
}
}
/** /**
* Method called when the server enables the plugin. * Method called when the server enables the plugin.
*/ */
@Override @Override
public void onEnable() { public void onEnable() {
// Set the plugin instance and load plugin info from the plugin description. // Set the plugin instance and load plugin info from the plugin description.
plugin = this;
loadPluginInfo(); loadPluginInfo();
// Set the Logger instance and log file path // Set the Logger instance and log file path
ConsoleLogger.setLogger(getLogger()); ConsoleLogger.setLogger(getLogger());
ConsoleLogger.setLogFile(new File(getDataFolder(), "authme.log")); ConsoleLogger.setLogFile(new File(getDataFolder(), LOG_FILENAME));
// Load settings and custom configurations, if it fails, stop the server due to security reasons. // Load settings and custom configurations, if it fails, stop the server due to security reasons.
settings = createSettings(); settings = createSettings();
if (settings == null) { if (settings == null) {
getLogger().warning("Could not load configuration. Aborting."); ConsoleLogger.warning("Could not load the configuration file!"
getServer().shutdown(); + "The server is going to shutdown NOW!");
setEnabled(false); setEnabled(false);
getServer().shutdown();
return; return;
} }
// Apply settings to the logger // Apply settings to the logger
ConsoleLogger.setLoggingOptions(settings); ConsoleLogger.setLoggingOptions(settings);
// Set console filter
setupConsoleFilter();
// Connect to the database and setup tables // Connect to the database and setup tables
try { try {
setupDatabase(settings); setupDatabase();
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.logException("Fatal error occurred during database connection! " ConsoleLogger.logException("Fatal error occurred during database connection! "
+ "Authme initialization aborted!", e); + "Authme initialization aborted!", e);
@ -232,46 +211,53 @@ public class AuthMe extends JavaPlugin {
instantiateServices(injector); instantiateServices(injector);
// Set up Metrics // Set up Metrics
MetricsStarter.setupMetrics(this, settings); MetricsManager.sendMetrics(this, settings);
// Set console filter
setupConsoleFilter();
// Do a backup on start // Do a backup on start
// TODO: maybe create a backup manager? // TODO: maybe create a backup manager?
new PerformBackup(this, settings).doBackup(PerformBackup.BackupCause.START); new PerformBackup(this, settings).doBackup(PerformBackup.BackupCause.START);
// Reload support hook
reloadSupportHook();
// Register event listeners // Register event listeners
registerEventListeners(injector); registerEventListeners(injector);
// Start Email recall task if needed // Start Email recall task if needed
scheduleRecallEmailTask(); scheduleRecallEmailTask();
// Show settings warnings // Show settings warnings
showSettingsWarnings(); showSettingsWarnings();
// If server is using PermissionsBukkit, print a warning that some features may not be supported
if (PermissionsSystemType.PERMISSIONS_BUKKIT.equals(permsMan.getPermissionSystem())) {
ConsoleLogger.warning("Warning! This server uses PermissionsBukkit for permissions. Some permissions features may not be supported!");
}
// Sponsor messages // Sponsor messages
ConsoleLogger.info("Development builds are available on our jenkins, thanks to f14stelt."); ConsoleLogger.info("Development builds are available on our jenkins, thanks to f14stelt.");
ConsoleLogger.info("Do you want a good game server? Look at our sponsor GameHosting.it leader in Italy as Game Server Provider!"); ConsoleLogger.info("Do you want a good game server? Look at our sponsor GameHosting.it leader in Italy as Game Server Provider!");
// Successful message // Successful message
ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " correctly enabled!"); ConsoleLogger.info("AuthMe " + getPluginVersion() + " build n°" + getPluginBuildNumber() + " correctly enabled!");
// If server is using PermissionsBukkit, print a warning that some features may not be supported
if (PermissionsSystemType.PERMISSIONS_BUKKIT.equals(permsMan.getPermissionSystem())) {
ConsoleLogger.warning("Warning! This server uses PermissionsBukkit for permissions. Some permissions features may not be supported!");
}
// Purge on start if enabled // Purge on start if enabled
PurgeService purgeService = injector.getSingleton(PurgeService.class); PurgeService purgeService = injector.getSingleton(PurgeService.class);
purgeService.runAutoPurge(); purgeService.runAutoPurge();
// Schedule clean up task // Schedule clean up task
final int cleanupInterval = 5 * TICKS_PER_MINUTE;
CleanupTask cleanupTask = injector.getSingleton(CleanupTask.class); CleanupTask cleanupTask = injector.getSingleton(CleanupTask.class);
cleanupTask.runTaskTimerAsynchronously(this, cleanupInterval, cleanupInterval); cleanupTask.runTaskTimerAsynchronously(this, CLEANUP_INTERVAL, CLEANUP_INTERVAL);
}
// Get version and build number of the plugin
private void loadPluginInfo() {
String versionRaw = this.getDescription().getVersion();
int index = versionRaw.lastIndexOf("-");
if (index != -1) {
pluginVersion = versionRaw.substring(0, index);
pluginBuildNumber = versionRaw.substring(index + 1);
if (pluginBuildNumber.startsWith("b")) {
pluginBuildNumber = pluginBuildNumber.substring(1);
}
}
} }
protected void instantiateServices(Injector injector) { protected void instantiateServices(Injector injector) {
@ -337,23 +323,6 @@ public class AuthMe extends JavaPlugin {
} }
} }
private void reloadSupportHook() {
if (database != null) {
int playersOnline = bukkitService.getOnlinePlayers().size();
if (playersOnline < 1) {
database.purgeLogged();
} else if (settings.getProperty(SecuritySettings.USE_RELOAD_COMMAND_SUPPORT)) {
for (PlayerAuth auth : database.getLoggedPlayers()) {
if (auth != null) {
auth.setLastLogin(new Date().getTime());
database.updateSession(auth);
playerCache.addPlayer(auth);
}
}
}
}
}
/** /**
* Loads the plugin's settings. * Loads the plugin's settings.
* *
@ -475,14 +444,12 @@ public class AuthMe extends JavaPlugin {
/** /**
* Sets up the data source. * Sets up the data source.
* *
* @param settings The settings instance
*
* @throws ClassNotFoundException if no driver could be found for the datasource * @throws ClassNotFoundException if no driver could be found for the datasource
* @throws SQLException when initialization of a SQL datasource failed * @throws SQLException when initialization of a SQL datasource failed
* @throws IOException if flat file cannot be read * @throws IOException if flat file cannot be read
* @see AuthMe#database * @see AuthMe#database
*/ */
public void setupDatabase(Settings settings) throws ClassNotFoundException, SQLException, IOException { public void setupDatabase() throws ClassNotFoundException, SQLException, IOException {
if (this.database != null) { if (this.database != null) {
this.database.close(); this.database.close();
} }

View File

@ -10,12 +10,12 @@ import org.mcstats.Metrics.Graph;
import java.io.IOException; import java.io.IOException;
public class MetricsStarter { public class MetricsManager {
private MetricsStarter() { private MetricsManager() {
} }
public static void setupMetrics(AuthMe plugin, Settings settings) { public static void sendMetrics(AuthMe plugin, Settings settings) {
try { try {
final Metrics metrics = new Metrics(plugin); final Metrics metrics = new Metrics(plugin);
@ -41,7 +41,7 @@ public class MetricsStarter {
metrics.start(); metrics.start();
} catch (IOException e) { } catch (IOException e) {
// Failed to submit the metrics data // Failed to submit the metrics data
ConsoleLogger.logException("Can't start Metrics! The plugin will work anyway...", e); ConsoleLogger.logException("Can't send Metrics data! The plugin will work anyway...", e);
} }
} }
} }

View File

@ -94,10 +94,6 @@ public class AuthMeInitializationTest {
// given // given
Settings settings = new Settings(settingsFile, dataFolder, getAllPropertyFields(), alwaysFulfilled()); Settings settings = new Settings(settingsFile, dataFolder, getAllPropertyFields(), alwaysFulfilled());
// TODO ljacqu 20160619: At some point setting the "plugin" field should no longer be necessary
// We only require it right now because of usages of AuthMe#getInstance()
ReflectionTestUtils.setField(AuthMe.class, null, "plugin", authMe);
Injector injector = new InjectorBuilder().addDefaultHandlers("fr.xephi.authme").create(); Injector injector = new InjectorBuilder().addDefaultHandlers("fr.xephi.authme").create();
injector.provide(DataFolder.class, dataFolder); injector.provide(DataFolder.class, dataFolder);
injector.register(Server.class, server); injector.register(Server.class, server);