Move more complex initializations from main class to Initializer helper (tentative)

This commit is contained in:
ljacqu 2016-08-12 22:04:56 +02:00
parent 5d2da7bd82
commit 02ca2d18b9
6 changed files with 262 additions and 217 deletions

View File

@ -10,14 +10,10 @@ import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.backup.PlayerDataStorage; import fr.xephi.authme.cache.backup.PlayerDataStorage;
import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.command.CommandHandler; import fr.xephi.authme.command.CommandHandler;
import fr.xephi.authme.datasource.CacheDataSource;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.datasource.DataSourceType;
import fr.xephi.authme.datasource.FlatFile;
import fr.xephi.authme.datasource.MySQL;
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.Initializer;
import fr.xephi.authme.initialization.MetricsManager; 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;
@ -26,35 +22,23 @@ import fr.xephi.authme.listener.PlayerListener16;
import fr.xephi.authme.listener.PlayerListener18; import fr.xephi.authme.listener.PlayerListener18;
import fr.xephi.authme.listener.PlayerListener19; import fr.xephi.authme.listener.PlayerListener19;
import fr.xephi.authme.listener.ServerListener; import fr.xephi.authme.listener.ServerListener;
import fr.xephi.authme.output.ConsoleFilter;
import fr.xephi.authme.output.Log4JFilter;
import fr.xephi.authme.output.MessageKey;
import fr.xephi.authme.output.Messages; import fr.xephi.authme.output.Messages;
import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.permission.PermissionsSystemType; import fr.xephi.authme.permission.PermissionsSystemType;
import fr.xephi.authme.process.Management; import fr.xephi.authme.process.Management;
import fr.xephi.authme.security.crypts.SHA256; import fr.xephi.authme.security.crypts.SHA256;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.SettingsMigrationService;
import fr.xephi.authme.settings.SpawnLoader; import fr.xephi.authme.settings.SpawnLoader;
import fr.xephi.authme.settings.properties.DatabaseSettings;
import fr.xephi.authme.settings.properties.EmailSettings;
import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.PluginSettings;
import fr.xephi.authme.settings.properties.RestrictionSettings; import fr.xephi.authme.settings.properties.RestrictionSettings;
import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.settings.properties.SecuritySettings;
import fr.xephi.authme.settings.properties.SettingsFieldRetriever;
import fr.xephi.authme.settings.propertymap.PropertyMap;
import fr.xephi.authme.task.CleanupTask; import fr.xephi.authme.task.CleanupTask;
import fr.xephi.authme.task.purge.PurgeService; import fr.xephi.authme.task.purge.PurgeService;
import fr.xephi.authme.util.BukkitService; import fr.xephi.authme.util.BukkitService;
import fr.xephi.authme.util.FileUtils;
import fr.xephi.authme.util.GeoLiteAPI; import fr.xephi.authme.util.GeoLiteAPI;
import fr.xephi.authme.util.MigrationService; import fr.xephi.authme.util.MigrationService;
import fr.xephi.authme.util.StringUtils;
import fr.xephi.authme.util.Utils; import fr.xephi.authme.util.Utils;
import fr.xephi.authme.util.ValidationService; import fr.xephi.authme.util.ValidationService;
import org.apache.logging.log4j.LogManager;
import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.Command; import org.bukkit.command.Command;
@ -68,17 +52,15 @@ import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitWorker; import org.bukkit.scheduler.BukkitWorker;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Date;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger;
import static fr.xephi.authme.settings.properties.EmailSettings.RECALL_PLAYERS;
import static fr.xephi.authme.util.BukkitService.TICKS_PER_MINUTE; import static fr.xephi.authme.util.BukkitService.TICKS_PER_MINUTE;
import static fr.xephi.authme.util.Utils.isClassLoaded;
/** /**
* The AuthMe main class. * The AuthMe main class.
@ -88,8 +70,6 @@ public class AuthMe extends JavaPlugin {
// Constants // Constants
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 String LOG_FILENAME = "authme.log";
private static final String FLATFILE_FILENAME = "auths.db";
private static final int SQLITE_MAX_SIZE = 4000;
private static final int CLEANUP_INTERVAL = 5 * TICKS_PER_MINUTE; private static final int CLEANUP_INTERVAL = 5 * TICKS_PER_MINUTE;
// Default version and build number values; // Default version and build number values;
@ -160,69 +140,12 @@ public class AuthMe extends JavaPlugin {
*/ */
@Override @Override
public void onEnable() { public void onEnable() {
// Set the plugin instance and load plugin info from the plugin description.
loadPluginInfo();
// Set the Logger instance and log file path
ConsoleLogger.setLogger(getLogger());
ConsoleLogger.setLogFile(new File(getDataFolder(), LOG_FILENAME));
// Load settings and custom configurations, if it fails, stop the server due to security reasons.
settings = createSettings();
if (settings == null) {
ConsoleLogger.warning("Could not load the configuration file!"
+ "The server is going to shutdown NOW!");
setEnabled(false);
getServer().shutdown();
return;
}
// Apply settings to the logger
ConsoleLogger.setLoggingOptions(settings);
// Set console filter
setupConsoleFilter();
// Connect to the database and setup tables
try { try {
setupDatabase(); initializeServices();
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.logException("Fatal error occurred during database connection! " ConsoleLogger.logException("Aborting initialization of AuthMe:", e);
+ "Authme initialization aborted!", e);
stopOrUnload(); stopOrUnload();
return;
} }
// Convert deprecated PLAINTEXT hash entries
MigrationService.changePlainTextToSha256(settings, database, new SHA256());
// Injector initialization
injector = new InjectorBuilder().addDefaultHandlers("fr.xephi.authme").create();
// Register elements of the Bukkit / JavaPlugin environment
injector.register(AuthMe.class, this);
injector.register(Server.class, getServer());
injector.register(PluginManager.class, getServer().getPluginManager());
injector.register(BukkitScheduler.class, getServer().getScheduler());
injector.provide(DataFolder.class, getDataFolder());
// Register elements we instantiate manually
injector.register(Settings.class, settings);
injector.register(DataSource.class, database);
instantiateServices(injector);
// Reload support hook
reloadSupportHook();
// Do a backup on start
// TODO: maybe create a backup manager?
new PerformBackup(this, settings).doBackup(PerformBackup.BackupCause.START);
// Register event listeners
registerEventListeners(injector);
// Start Email recall task if needed
scheduleRecallEmailTask();
// Show settings warnings // Show settings warnings
showSettingsWarnings(); showSettingsWarnings();
@ -232,6 +155,9 @@ public class AuthMe extends JavaPlugin {
ConsoleLogger.warning("Warning! This server uses PermissionsBukkit for permissions. Some permissions features may not be supported!"); ConsoleLogger.warning("Warning! This server uses PermissionsBukkit for permissions. Some permissions features may not be supported!");
} }
// Do a backup on start
new PerformBackup(this, settings).doBackup(PerformBackup.BackupCause.START);
// Set up Metrics // Set up Metrics
MetricsManager.sendMetrics(this, settings); MetricsManager.sendMetrics(this, settings);
@ -251,6 +177,55 @@ public class AuthMe extends JavaPlugin {
cleanupTask.runTaskTimerAsynchronously(this, CLEANUP_INTERVAL, CLEANUP_INTERVAL); cleanupTask.runTaskTimerAsynchronously(this, CLEANUP_INTERVAL, CLEANUP_INTERVAL);
} }
private void initializeServices() throws Exception {
// Set the plugin instance and load plugin info from the plugin description.
loadPluginInfo();
// Set the Logger instance and log file path
ConsoleLogger.setLogger(getLogger());
ConsoleLogger.setLogFile(new File(getDataFolder(), LOG_FILENAME));
bukkitService = new BukkitService(this);
Initializer initializer = new Initializer(this, bukkitService);
// Load settings and set up the console and console filter
settings = initializer.createSettings();
ConsoleLogger.setLoggingOptions(settings);
initializer.setupConsoleFilter(settings, getLogger());
// Connect to the database and set up tables
database = initializer.setupDatabase(settings);
// Convert deprecated PLAINTEXT hash entries
MigrationService.changePlainTextToSha256(settings, database, new SHA256());
// Injector initialization
injector = new InjectorBuilder().addDefaultHandlers("fr.xephi.authme").create();
// Register elements of the Bukkit / JavaPlugin environment
injector.register(AuthMe.class, this);
injector.register(Server.class, getServer());
injector.register(PluginManager.class, getServer().getPluginManager());
injector.register(BukkitScheduler.class, getServer().getScheduler());
injector.provide(DataFolder.class, getDataFolder());
// Register elements we instantiate manually
injector.register(Settings.class, settings);
injector.register(DataSource.class, database);
injector.register(BukkitService.class, bukkitService);
instantiateServices(injector);
// Reload support hook
reloadSupportHook();
// Register event listeners
registerEventListeners(injector);
// Start Email recall task if needed
initializer.scheduleRecallEmailTask(settings, database, messages);
}
// Get version and build number of the plugin // Get version and build number of the plugin
private void loadPluginInfo() { private void loadPluginInfo() {
String versionRaw = this.getDescription().getVersion(); String versionRaw = this.getDescription().getVersion();
@ -313,119 +288,18 @@ public class AuthMe extends JavaPlugin {
pluginManager.registerEvents(injector.getSingleton(ServerListener.class), this); pluginManager.registerEvents(injector.getSingleton(ServerListener.class), this);
// Try to register 1.6 player listeners // Try to register 1.6 player listeners
try { if (isClassLoaded("org.bukkit.event.player.PlayerEditBookEvent")) {
Class.forName("org.bukkit.event.player.PlayerEditBookEvent");
pluginManager.registerEvents(injector.getSingleton(PlayerListener16.class), this); pluginManager.registerEvents(injector.getSingleton(PlayerListener16.class), this);
} catch (ClassNotFoundException ignore) {
} }
// Try to register 1.8 player listeners // Try to register 1.8 player listeners
try { if (isClassLoaded("org.bukkit.event.player.PlayerInteractAtEntityEvent")) {
Class.forName("org.bukkit.event.player.PlayerInteractAtEntityEvent");
pluginManager.registerEvents(injector.getSingleton(PlayerListener18.class), this); pluginManager.registerEvents(injector.getSingleton(PlayerListener18.class), this);
} catch (ClassNotFoundException ignore) {
} }
// Try to register 1.9 player listeners // Try to register 1.9 player listeners
try { if (isClassLoaded("org.bukkit.event.player.PlayerSwapHandItemsEvent")) {
Class.forName("org.bukkit.event.player.PlayerSwapHandItemsEvent");
pluginManager.registerEvents(injector.getSingleton(PlayerListener19.class), this); pluginManager.registerEvents(injector.getSingleton(PlayerListener19.class), this);
} catch (ClassNotFoundException ignore) {
}
}
/**
* Loads the plugin's settings.
*
* @return The settings instance, or null if it could not be constructed
*/
private Settings createSettings() {
File configFile = new File(getDataFolder(), "config.yml");
PropertyMap properties = SettingsFieldRetriever.getAllPropertyFields();
SettingsMigrationService migrationService = new SettingsMigrationService();
return FileUtils.copyFileFromResource(configFile, "config.yml")
? new Settings(configFile, getDataFolder(), properties, migrationService)
: null;
}
/**
* Set up the console filter.
*/
private void setupConsoleFilter() {
if (!settings.getProperty(SecuritySettings.REMOVE_PASSWORD_FROM_CONSOLE)) {
return;
}
// Try to set the log4j filter
try {
Class.forName("org.apache.logging.log4j.core.filter.AbstractFilter");
setLog4JFilter();
} catch (ClassNotFoundException | NoClassDefFoundError e) {
// log4j is not available
ConsoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support will be disabled");
ConsoleFilter filter = new ConsoleFilter();
getLogger().setFilter(filter);
Bukkit.getLogger().setFilter(filter);
Logger.getLogger("Minecraft").setFilter(filter);
}
}
// Set the console filter to remove the passwords
private void setLog4JFilter() {
org.apache.logging.log4j.core.Logger logger;
logger = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger();
logger.addFilter(new Log4JFilter());
}
/**
* Sets up the data source.
*
* @throws ClassNotFoundException if no driver could be found for the datasource
* @throws SQLException when initialization of a SQL datasource failed
* @throws IOException if flat file cannot be read
* @see AuthMe#database
*/
private void setupDatabase() throws ClassNotFoundException, SQLException, IOException {
if (database != null) {
database.close();
database = null;
}
DataSourceType dataSourceType = settings.getProperty(DatabaseSettings.BACKEND);
DataSource dataSource;
switch (dataSourceType) {
case FILE:
File source = new File(getDataFolder(), FLATFILE_FILENAME);
dataSource = new FlatFile(source);
break;
case MYSQL:
dataSource = new MySQL(settings);
break;
case SQLITE:
dataSource = new SQLite(settings);
break;
default:
throw new UnsupportedOperationException("Unknown data source type '" + dataSourceType + "'");
}
DataSource convertedSource = MigrationService.convertFlatfileToSqlite(settings, dataSource);
dataSource = convertedSource == null ? dataSource : convertedSource;
if (settings.getProperty(DatabaseSettings.USE_CACHING)) {
dataSource = new CacheDataSource(dataSource);
}
database = dataSource;
if (DataSourceType.SQLITE == dataSourceType) {
getServer().getScheduler().runTaskAsynchronously(this, new Runnable() {
@Override
public void run() {
int accounts = database.getAccountsRegistered();
if (accounts >= SQLITE_MAX_SIZE) {
ConsoleLogger.warning("YOU'RE USING THE SQLITE DATABASE WITH "
+ accounts + "+ ACCOUNTS; FOR BETTER PERFORMANCE, PLEASE UPGRADE TO MYSQL!!");
}
}
});
} }
} }
@ -440,26 +314,6 @@ public class AuthMe extends JavaPlugin {
} }
} }
private void scheduleRecallEmailTask() {
if (!settings.getProperty(RECALL_PLAYERS)) {
return;
}
Bukkit.getScheduler().runTaskTimerAsynchronously(this, new Runnable() {
@Override
public void run() {
for (PlayerAuth auth : database.getLoggedPlayers()) {
String email = auth.getEmail();
if (StringUtils.isEmpty(email) || "your@email.com".equalsIgnoreCase(email)) {
Player player = bukkitService.getPlayerExact(auth.getRealName());
if (player != null) {
messages.send(player, MessageKey.ADD_EMAIL_MESSAGE);
}
}
}
}
}, 1, TICKS_PER_MINUTE * settings.getProperty(EmailSettings.DELAY_RECALL));
}
// TODO: check this, do we really need it? -sgdc3 // TODO: check this, do we really need it? -sgdc3
private void reloadSupportHook() { private void reloadSupportHook() {
if (database != null) { if (database != null) {
@ -469,8 +323,8 @@ public class AuthMe extends JavaPlugin {
} else if (settings.getProperty(SecuritySettings.USE_RELOAD_COMMAND_SUPPORT)) { } else if (settings.getProperty(SecuritySettings.USE_RELOAD_COMMAND_SUPPORT)) {
for (PlayerAuth auth : database.getLoggedPlayers()) { for (PlayerAuth auth : database.getLoggedPlayers()) {
if (auth != null) { if (auth != null) {
//auth.setLastLogin(new Date().getTime()); auth.setLastLogin(new Date().getTime());
//database.updateSession(auth); database.updateSession(auth);
playerCache.addPlayer(auth); playerCache.addPlayer(auth);
} }
} }

View File

@ -0,0 +1,167 @@
package fr.xephi.authme.initialization;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.datasource.CacheDataSource;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.datasource.DataSourceType;
import fr.xephi.authme.datasource.FlatFile;
import fr.xephi.authme.datasource.MySQL;
import fr.xephi.authme.datasource.SQLite;
import fr.xephi.authme.output.ConsoleFilter;
import fr.xephi.authme.output.Log4JFilter;
import fr.xephi.authme.output.MessageKey;
import fr.xephi.authme.output.Messages;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.SettingsMigrationService;
import fr.xephi.authme.settings.properties.DatabaseSettings;
import fr.xephi.authme.settings.properties.EmailSettings;
import fr.xephi.authme.settings.properties.SecuritySettings;
import fr.xephi.authme.settings.properties.SettingsFieldRetriever;
import fr.xephi.authme.settings.propertymap.PropertyMap;
import fr.xephi.authme.util.BukkitService;
import fr.xephi.authme.util.FileUtils;
import fr.xephi.authme.util.MigrationService;
import fr.xephi.authme.util.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Logger;
import static fr.xephi.authme.settings.properties.EmailSettings.RECALL_PLAYERS;
import static fr.xephi.authme.util.BukkitService.TICKS_PER_MINUTE;
/**
* Initializes the plugin's data source.
*/
public class Initializer {
private static final String FLATFILE_FILENAME = "auths.db";
private static final int SQLITE_MAX_SIZE = 4000;
private AuthMe authMe;
private BukkitService bukkitService;
public Initializer(AuthMe authMe, BukkitService bukkitService) {
this.authMe = authMe;
this.bukkitService = bukkitService;
}
/**
* Loads the plugin's settings.
*
* @return The settings instance, or null if it could not be constructed
*/
public Settings createSettings() throws Exception {
File configFile = new File(authMe.getDataFolder(), "config.yml");
PropertyMap properties = SettingsFieldRetriever.getAllPropertyFields();
SettingsMigrationService migrationService = new SettingsMigrationService();
if (FileUtils.copyFileFromResource(configFile, "config.yml")) {
return new Settings(configFile, authMe.getDataFolder(), properties, migrationService);
}
throw new Exception("Could not copy config.yml from JAR to plugin folder");
}
/**
* Sets up the data source.
*
* @throws ClassNotFoundException if no driver could be found for the datasource
* @throws SQLException when initialization of a SQL datasource failed
* @throws IOException if flat file cannot be read
*/
public DataSource setupDatabase(Settings settings) throws ClassNotFoundException, SQLException, IOException {
DataSourceType dataSourceType = settings.getProperty(DatabaseSettings.BACKEND);
DataSource dataSource;
switch (dataSourceType) {
case FILE:
File source = new File(authMe.getDataFolder(), FLATFILE_FILENAME);
dataSource = new FlatFile(source);
break;
case MYSQL:
dataSource = new MySQL(settings);
break;
case SQLITE:
dataSource = new SQLite(settings);
break;
default:
throw new UnsupportedOperationException("Unknown data source type '" + dataSourceType + "'");
}
DataSource convertedSource = MigrationService.convertFlatfileToSqlite(settings, dataSource);
dataSource = convertedSource == null ? dataSource : convertedSource;
if (settings.getProperty(DatabaseSettings.USE_CACHING)) {
dataSource = new CacheDataSource(dataSource);
}
if (DataSourceType.SQLITE.equals(dataSourceType)) {
checkDataSourceSize(dataSource);
}
return dataSource;
}
private void checkDataSourceSize(final DataSource dataSource) {
bukkitService.runTaskAsynchronously(new Runnable() {
@Override
public void run() {
int accounts = dataSource.getAccountsRegistered();
if (accounts >= SQLITE_MAX_SIZE) {
ConsoleLogger.warning("YOU'RE USING THE SQLITE DATABASE WITH "
+ accounts + "+ ACCOUNTS; FOR BETTER PERFORMANCE, PLEASE UPGRADE TO MYSQL!!");
}
}
});
}
/**
* Sets up the console filter if enabled.
*/
public void setupConsoleFilter(Settings settings, Logger logger) {
if (!settings.getProperty(SecuritySettings.REMOVE_PASSWORD_FROM_CONSOLE)) {
return;
}
// Try to set the log4j filter
try {
Class.forName("org.apache.logging.log4j.core.filter.AbstractFilter");
setLog4JFilter();
} catch (ClassNotFoundException | NoClassDefFoundError e) {
// log4j is not available
ConsoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support will be disabled");
ConsoleFilter filter = new ConsoleFilter();
logger.setFilter(filter);
Bukkit.getLogger().setFilter(filter);
Logger.getLogger("Minecraft").setFilter(filter);
}
}
// Set the console filter to remove the passwords
private static void setLog4JFilter() {
org.apache.logging.log4j.core.Logger logger;
logger = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger();
logger.addFilter(new Log4JFilter());
}
public void scheduleRecallEmailTask(Settings settings, final DataSource dataSource, final Messages messages) {
if (!settings.getProperty(RECALL_PLAYERS)) {
return;
}
bukkitService.runTaskTimerAsynchronously(new Runnable() {
@Override
public void run() {
for (PlayerAuth auth : dataSource.getLoggedPlayers()) {
String email = auth.getEmail();
if (StringUtils.isEmpty(email) || "your@email.com".equalsIgnoreCase(email)) {
Player player = bukkitService.getPlayerExact(auth.getRealName());
if (player != null) {
messages.send(player, MessageKey.ADD_EMAIL_MESSAGE);
}
}
}
}
}, 1, TICKS_PER_MINUTE * settings.getProperty(EmailSettings.DELAY_RECALL));
}
}

View File

@ -14,7 +14,6 @@ import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
import javax.inject.Inject;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Arrays; import java.util.Arrays;
@ -37,8 +36,7 @@ public class BukkitService {
private final boolean getOnlinePlayersIsCollection; private final boolean getOnlinePlayersIsCollection;
private Method getOnlinePlayers; private Method getOnlinePlayers;
@Inject public BukkitService(AuthMe authMe) {
BukkitService(AuthMe authMe) {
this.authMe = authMe; this.authMe = authMe;
getOnlinePlayersIsCollection = initializeOnlinePlayersIsCollectionField(); getOnlinePlayersIsCollection = initializeOnlinePlayersIsCollectionField();
} }
@ -113,17 +111,18 @@ public class BukkitService {
* <b>Asynchronous tasks should never access any API in Bukkit. Great care * <b>Asynchronous tasks should never access any API in Bukkit. Great care
* should be taken to assure the thread-safety of asynchronous tasks.</b> * should be taken to assure the thread-safety of asynchronous tasks.</b>
* <p> * <p>
* Returns a task that will run asynchronously after the specified number * Returns a task that will repeatedly run asynchronously until cancelled,
* of server ticks. * starting after the specified number of server ticks.
* *
* @param task the task to be run * @param task the task to be run
* @param delay the ticks to wait before running the task * @param delay the ticks to wait before running the task for the first
* time
* @param period the ticks to wait between runs
* @return a BukkitTask that contains the id number * @return a BukkitTask that contains the id number
* @throws IllegalArgumentException if plugin is null
* @throws IllegalArgumentException if task is null * @throws IllegalArgumentException if task is null
*/ */
public BukkitTask runTaskLaterAsynchronously(Runnable task, long delay) { public BukkitTask runTaskTimerAsynchronously(Runnable task, long delay, long period) {
return Bukkit.getScheduler().runTaskLaterAsynchronously(authMe, task, delay); return Bukkit.getScheduler().runTaskTimerAsynchronously(authMe, task, delay, period);
} }
/** /**

View File

@ -57,4 +57,20 @@ public final class Utils {
public static String getPlayerIp(Player p) { public static String getPlayerIp(Player p) {
return p.getAddress().getAddress().getHostAddress(); return p.getAddress().getAddress().getHostAddress();
} }
/**
* Returns whether the class exists in the current class loader.
*
* @param className the class name to check
*
* @return true if the class is loaded, false otherwise
*/
public static boolean isClassLoaded(String className) {
try {
Class.forName(className);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
} }

View File

@ -14,6 +14,7 @@ import fr.xephi.authme.process.login.ProcessSyncPlayerLogin;
import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.purge.PurgeService; import fr.xephi.authme.task.purge.PurgeService;
import fr.xephi.authme.util.BukkitService;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginDescriptionFile;
@ -102,6 +103,7 @@ public class AuthMeInitializationTest {
injector.register(AuthMe.class, authMe); injector.register(AuthMe.class, authMe);
injector.register(Settings.class, settings); injector.register(Settings.class, settings);
injector.register(DataSource.class, mock(DataSource.class)); injector.register(DataSource.class, mock(DataSource.class));
injector.register(BukkitService.class, mock(BukkitService.class));
// when // when
authMe.instantiateServices(injector); authMe.instantiateServices(injector);

View File

@ -96,4 +96,11 @@ public class UtilsTest {
// given / when / then // given / when / then
TestHelper.validateHasOnlyPrivateEmptyConstructor(Utils.class); TestHelper.validateHasOnlyPrivateEmptyConstructor(Utils.class);
} }
@Test
public void shouldCheckIfClassIsLoaded() {
// given / when / then
assertThat(Utils.isClassLoaded("org.bukkit.event.player.PlayerFishEvent"), equalTo(true));
assertThat(Utils.isClassLoaded("com.someclass.doesnot.exist"), equalTo(false));
}
} }