From 351b24fd14ffee74087ea87aec5ae6222aa9db73 Mon Sep 17 00:00:00 2001 From: ljacqu Date: Thu, 24 Mar 2016 20:58:18 +0100 Subject: [PATCH] Change AntiBot from static to instance - Convert static methods in AntiBot - Create BukkitService for operations requiring calls to static methods on the Bukkit class --- src/main/java/fr/xephi/authme/AntiBot.java | 54 +++++++++++-------- src/main/java/fr/xephi/authme/AuthMe.java | 40 +++++++------- .../xephi/authme/command/CommandService.java | 10 +++- .../authme/SwitchAntiBotCommand.java | 7 +-- .../authme/listener/AuthMePlayerListener.java | 31 +++++++---- .../fr/xephi/authme/util/BukkitService.java | 52 ++++++++++++++++++ .../java/fr/xephi/authme/AntiBotTest.java | 35 ------------ .../authme/command/CommandServiceTest.java | 39 ++++++++------ 8 files changed, 161 insertions(+), 107 deletions(-) create mode 100644 src/main/java/fr/xephi/authme/util/BukkitService.java delete mode 100644 src/test/java/fr/xephi/authme/AntiBotTest.java diff --git a/src/main/java/fr/xephi/authme/AntiBot.java b/src/main/java/fr/xephi/authme/AntiBot.java index f93c26051..00a53daf3 100644 --- a/src/main/java/fr/xephi/authme/AntiBot.java +++ b/src/main/java/fr/xephi/authme/AntiBot.java @@ -2,9 +2,10 @@ package fr.xephi.authme; import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.Messages; +import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PlayerStatePermission; import fr.xephi.authme.settings.Settings; -import fr.xephi.authme.util.Wrapper; +import fr.xephi.authme.util.BukkitService; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -16,17 +17,25 @@ import java.util.List; */ public class AntiBot { - private static final Wrapper wrapper = Wrapper.getInstance(); - private static final AuthMe plugin = wrapper.getAuthMe(); - private static final Messages messages = wrapper.getMessages(); - private static final List antibotPlayers = new ArrayList<>(); - private static AntiBotStatus antiBotStatus = AntiBotStatus.DISABLED; + private final Messages messages; + private final PermissionsManager permissionsManager; + private final BukkitService bukkitService; + private final List antibotPlayers = new ArrayList<>(); + private AntiBotStatus antiBotStatus = AntiBotStatus.DISABLED; - public static void setupAntiBotService() { + public AntiBot(Messages messages, PermissionsManager permissionsManager, BukkitService bukkitService) { + this.messages = messages; + this.permissionsManager = permissionsManager; + this.bukkitService = bukkitService; + + setupAntiBotService(); + } + + private void setupAntiBotService() { if (!Settings.enableAntiBot) { return; } - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + bukkitService.scheduleSyncDelayedTask(new Runnable() { @Override public void run() { antiBotStatus = AntiBotStatus.LISTENING; @@ -34,46 +43,45 @@ public class AntiBot { }, 2400); } - public static void overrideAntiBotStatus(boolean activated) { - if (antiBotStatus == AntiBotStatus.DISABLED) { - return; - } - if (activated) { - antiBotStatus = AntiBotStatus.ACTIVE; - } else { - antiBotStatus = AntiBotStatus.LISTENING; + public void overrideAntiBotStatus(boolean activated) { + if (antiBotStatus != AntiBotStatus.DISABLED) { + if (activated) { + antiBotStatus = AntiBotStatus.ACTIVE; + } else { + antiBotStatus = AntiBotStatus.LISTENING; + } } } - public static AntiBotStatus getAntiBotStatus() { + public AntiBotStatus getAntiBotStatus() { return antiBotStatus; } - public static void activateAntiBot() { + public void activateAntiBot() { antiBotStatus = AntiBotStatus.ACTIVE; for (String s : messages.retrieve(MessageKey.ANTIBOT_AUTO_ENABLED_MESSAGE)) { Bukkit.broadcastMessage(s); } - wrapper.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + bukkitService.scheduleSyncDelayedTask(new Runnable() { @Override public void run() { if (antiBotStatus == AntiBotStatus.ACTIVE) { antiBotStatus = AntiBotStatus.LISTENING; antibotPlayers.clear(); for (String s : messages.retrieve(MessageKey.ANTIBOT_AUTO_DISABLED_MESSAGE)) { - Bukkit.broadcastMessage(s.replace("%m", "" + Settings.antiBotDuration)); + bukkitService.broadcastMessage(s.replace("%m", Integer.toString(Settings.antiBotDuration))); } } } }, Settings.antiBotDuration * 1200); } - public static void checkAntiBot(final Player player) { + public void checkAntiBot(final Player player) { if (antiBotStatus == AntiBotStatus.ACTIVE || antiBotStatus == AntiBotStatus.DISABLED) { return; } - if (plugin.getPermissionsManager().hasPermission(player, PlayerStatePermission.BYPASS_ANTIBOT)) { + if (permissionsManager.hasPermission(player, PlayerStatePermission.BYPASS_ANTIBOT)) { return; } @@ -82,7 +90,7 @@ public class AntiBot { activateAntiBot(); return; } - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + bukkitService.scheduleSyncDelayedTask(new Runnable() { @Override public void run() { antibotPlayers.remove(player.getName().toLowerCase()); diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index 58d791d5e..27eafb40c 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -55,6 +55,7 @@ import fr.xephi.authme.settings.properties.RestrictionSettings; 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.CollectionUtils; import fr.xephi.authme.util.FileUtils; import fr.xephi.authme.util.GeoLiteAPI; @@ -136,6 +137,7 @@ public class AuthMe extends JavaPlugin { private IpAddressManager ipAddressManager; private PluginHooks pluginHooks; private SpawnLoader spawnLoader; + private AntiBot antiBot; /** * Get the plugin's instance. @@ -254,10 +256,14 @@ public class AuthMe extends JavaPlugin { // Initialize spawn loader spawnLoader = new SpawnLoader(getDataFolder(), newSettings, pluginHooks); + // AntiBot delay + BukkitService bukkitService = new BukkitService(this); + antiBot = new AntiBot(messages, permsMan, bukkitService); + // Set up the permissions manager and command handler permsMan = initializePermissionsManager(); commandHandler = initializeCommandHandler(permsMan, messages, passwordSecurity, newSettings, ipAddressManager, - pluginHooks, spawnLoader); + pluginHooks, spawnLoader, antiBot); // Set up Metrics MetricsStarter.setupMetrics(plugin, newSettings); @@ -265,9 +271,6 @@ public class AuthMe extends JavaPlugin { // Set console filter setupConsoleFilter(); - // AntiBot delay - AntiBot.setupAntiBotService(); - // Download and load GeoIp.dat file if absent GeoLiteAPI.isDataAvailable(); @@ -304,7 +307,7 @@ public class AuthMe extends JavaPlugin { reloadSupportHook(); // Register event listeners - registerEventListeners(messages, pluginHooks, spawnLoader); + registerEventListeners(messages, database, management, pluginHooks, spawnLoader, antiBot); // Purge on start if enabled autoPurge(); @@ -370,12 +373,13 @@ public class AuthMe extends JavaPlugin { /** * Register all event listeners. */ - private void registerEventListeners(Messages messages, PluginHooks pluginHooks, SpawnLoader spawnLoader) { + private void registerEventListeners(Messages messages, DataSource dataSource, Management management, + PluginHooks pluginHooks, SpawnLoader spawnLoader, AntiBot antiBot) { // Get the plugin manager instance PluginManager pluginManager = server.getPluginManager(); // Register event listeners - pluginManager.registerEvents(new AuthMePlayerListener(this), this); + pluginManager.registerEvents(new AuthMePlayerListener(this, messages, dataSource, antiBot, management), this); pluginManager.registerEvents(new AuthMeBlockListener(), this); pluginManager.registerEvents(new AuthMeEntityListener(), this); pluginManager.registerEvents(new AuthMeServerListener(this, messages, pluginHooks, spawnLoader), this); @@ -427,12 +431,12 @@ public class AuthMe extends JavaPlugin { private CommandHandler initializeCommandHandler(PermissionsManager permissionsManager, Messages messages, PasswordSecurity passwordSecurity, NewSetting settings, IpAddressManager ipAddressManager, PluginHooks pluginHooks, - SpawnLoader spawnLoader) { + SpawnLoader spawnLoader, AntiBot antiBot) { HelpProvider helpProvider = new HelpProvider(permissionsManager, settings.getProperty(HELP_HEADER)); Set baseCommands = CommandInitializer.buildCommands(); CommandMapper mapper = new CommandMapper(baseCommands, permissionsManager); CommandService commandService = new CommandService(this, mapper, helpProvider, messages, passwordSecurity, - permissionsManager, settings, ipAddressManager, pluginHooks, spawnLoader); + permissionsManager, settings, ipAddressManager, pluginHooks, spawnLoader, antiBot); return new CommandHandler(commandService); } @@ -616,15 +620,6 @@ public class AuthMe extends JavaPlugin { return manager; } - /** - * Get the permissions manager instance. - * - * @return Permissions Manager instance. - */ - public PermissionsManager getPermissionsManager() { - return this.permsMan; - } - // Set the console filter to remove the passwords private void setLog4JFilter() { Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() { @@ -814,6 +809,15 @@ public class AuthMe extends JavaPlugin { return commandHandler.processCommand(sender, commandLabel, args); } + /** + * Get the permissions manager instance. + * + * @return Permissions Manager instance. + */ + public PermissionsManager getPermissionsManager() { + return this.permsMan; + } + /** * Return the management instance. * diff --git a/src/main/java/fr/xephi/authme/command/CommandService.java b/src/main/java/fr/xephi/authme/command/CommandService.java index 9c3c55a53..a4791e688 100644 --- a/src/main/java/fr/xephi/authme/command/CommandService.java +++ b/src/main/java/fr/xephi/authme/command/CommandService.java @@ -1,5 +1,6 @@ package fr.xephi.authme.command; +import fr.xephi.authme.AntiBot; import fr.xephi.authme.AuthMe; import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.command.help.HelpProvider; @@ -34,6 +35,7 @@ public class CommandService { private final IpAddressManager ipAddressManager; private final PluginHooks pluginHooks; private final SpawnLoader spawnLoader; + private final AntiBot antiBot; /** * Constructor. @@ -51,7 +53,8 @@ public class CommandService { */ public CommandService(AuthMe authMe, CommandMapper commandMapper, HelpProvider helpProvider, Messages messages, PasswordSecurity passwordSecurity, PermissionsManager permissionsManager, NewSetting settings, - IpAddressManager ipAddressManager, PluginHooks pluginHooks, SpawnLoader spawnLoader) { + IpAddressManager ipAddressManager, PluginHooks pluginHooks, SpawnLoader spawnLoader, + AntiBot antiBot) { this.authMe = authMe; this.messages = messages; this.helpProvider = helpProvider; @@ -62,6 +65,7 @@ public class CommandService { this.ipAddressManager = ipAddressManager; this.pluginHooks = pluginHooks; this.spawnLoader = spawnLoader; + this.antiBot = antiBot; } /** @@ -211,4 +215,8 @@ public class CommandService { return spawnLoader; } + public AntiBot getAntiBot() { + return antiBot; + } + } diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/SwitchAntiBotCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/SwitchAntiBotCommand.java index e11645a94..3c36c1690 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/SwitchAntiBotCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/SwitchAntiBotCommand.java @@ -18,8 +18,9 @@ public class SwitchAntiBotCommand implements ExecutableCommand { @Override public void executeCommand(final CommandSender sender, List arguments, CommandService commandService) { + AntiBot antiBot = commandService.getAntiBot(); if (arguments.isEmpty()) { - sender.sendMessage("[AuthMe] AntiBot status: " + AntiBot.getAntiBotStatus().name()); + sender.sendMessage("[AuthMe] AntiBot status: " + antiBot.getAntiBotStatus().name()); return; } @@ -27,10 +28,10 @@ public class SwitchAntiBotCommand implements ExecutableCommand { // Enable or disable the mod if ("ON".equalsIgnoreCase(newState)) { - AntiBot.overrideAntiBotStatus(true); + antiBot.overrideAntiBotStatus(true); sender.sendMessage("[AuthMe] AntiBot Manual Override: enabled!"); } else if ("OFF".equalsIgnoreCase(newState)) { - AntiBot.overrideAntiBotStatus(false); + antiBot.overrideAntiBotStatus(false); sender.sendMessage("[AuthMe] AntiBot Manual Override: disabled!"); } else { sender.sendMessage(ChatColor.DARK_RED + "Invalid AntiBot mode!"); diff --git a/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java b/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java index 7643de73c..b5e0a9b30 100644 --- a/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java +++ b/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java @@ -9,10 +9,12 @@ import fr.xephi.authme.cache.auth.PlayerAuth; import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.cache.limbo.LimboPlayer; +import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.Messages; import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PlayerStatePermission; +import fr.xephi.authme.process.Management; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.util.GeoLiteAPI; import fr.xephi.authme.util.Utils; @@ -58,10 +60,17 @@ public class AuthMePlayerListener implements Listener { public static final ConcurrentHashMap causeByAuthMe = new ConcurrentHashMap<>(); private final AuthMe plugin; private final Messages m; + private final DataSource dataSource; + private final AntiBot antiBot; + private final Management management; - public AuthMePlayerListener(AuthMe plugin) { - this.m = plugin.getMessages(); + public AuthMePlayerListener(AuthMe plugin, Messages messages, DataSource dataSource, AntiBot antiBot, + Management management) { this.plugin = plugin; + this.m = messages; + this.dataSource = dataSource; + this.antiBot = antiBot; + this.management = management; } private void handleChat(AsyncPlayerChatEvent event) { @@ -87,7 +96,7 @@ public class AuthMePlayerListener implements Listener { plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { - if (plugin.getDataSource().isAuthAvailable(player.getName().toLowerCase())) { + if (dataSource.isAuthAvailable(player.getName().toLowerCase())) { m.send(player, MessageKey.LOGIN_MESSAGE); } else { if (Settings.emailRegistration) { @@ -229,14 +238,14 @@ public class AuthMePlayerListener implements Listener { Bukkit.getScheduler().runTask(plugin, new Runnable() { @Override public void run() { - plugin.getManagement().performJoin(player); + management.performJoin(player); } }); } @EventHandler(priority = EventPriority.HIGHEST) public void onPreLogin(AsyncPlayerPreLoginEvent event) { - PlayerAuth auth = plugin.getDataSource().getAuth(event.getName()); + PlayerAuth auth = dataSource.getAuth(event.getName()); if (Settings.preventOtherCase && auth != null && auth.getRealName() != null) { String realName = auth.getRealName(); if (!realName.isEmpty() && !realName.equals("Player") && !realName.equals(event.getName())) { @@ -245,7 +254,7 @@ public class AuthMePlayerListener implements Listener { return; } if (realName.isEmpty() || realName.equals("Player")) { - plugin.getDataSource().updateRealName(event.getName().toLowerCase(), event.getName()); + dataSource.updateRealName(event.getName().toLowerCase(), event.getName()); } } @@ -319,7 +328,7 @@ public class AuthMePlayerListener implements Listener { } final String name = player.getName().toLowerCase(); - boolean isAuthAvailable = plugin.getDataSource().isAuthAvailable(name); + boolean isAuthAvailable = dataSource.isAuthAvailable(name); if (Settings.isKickNonRegisteredEnabled && !isAuthAvailable) { if (Settings.antiBotInAction) { @@ -345,7 +354,7 @@ public class AuthMePlayerListener implements Listener { return; } - AntiBot.checkAntiBot(player); + antiBot.checkAntiBot(player); if (Settings.bungee) { ByteArrayDataOutput out = ByteStreams.newDataOutput(); @@ -366,7 +375,7 @@ public class AuthMePlayerListener implements Listener { event.setQuitMessage(null); } - plugin.getManagement().performQuit(player, false); + management.performQuit(player, false); } @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) @@ -492,13 +501,13 @@ public class AuthMePlayerListener implements Listener { Player player = event.getPlayer(); String name = player.getName().toLowerCase(); Location spawn = plugin.getSpawnLocation(player); - if (Settings.isSaveQuitLocationEnabled && plugin.getDataSource().isAuthAvailable(name)) { + if (Settings.isSaveQuitLocationEnabled && dataSource.isAuthAvailable(name)) { PlayerAuth auth = PlayerAuth.builder() .name(name) .realName(player.getName()) .location(spawn) .build(); - plugin.getDataSource().updateQuitLoc(auth); + dataSource.updateQuitLoc(auth); } if (spawn != null && spawn.getWorld() != null) { event.setRespawnLocation(spawn); diff --git a/src/main/java/fr/xephi/authme/util/BukkitService.java b/src/main/java/fr/xephi/authme/util/BukkitService.java new file mode 100644 index 000000000..41622413a --- /dev/null +++ b/src/main/java/fr/xephi/authme/util/BukkitService.java @@ -0,0 +1,52 @@ +package fr.xephi.authme.util; + +import fr.xephi.authme.AuthMe; +import org.bukkit.Bukkit; + +/** + * Service for operations requiring server entities, such as for scheduling. + */ +public class BukkitService { + + private final AuthMe authMe; + + public BukkitService(AuthMe authMe) { + this.authMe = authMe; + } + + /** + * Schedules a once off task to occur as soon as possible. + *

+ * This task will be executed by the main server thread. + * + * @param task Task to be executed + * @return Task id number (-1 if scheduling failed) + */ + public int scheduleSyncDelayedTask(Runnable task) { + return Bukkit.getScheduler().scheduleSyncDelayedTask(authMe, task); + } + + /** + * Schedules a once off task to occur after a delay. + *

+ * This task will be executed by the main server thread. + * + * @param task Task to be executed + * @param delay Delay in server ticks before executing task + * @return Task id number (-1 if scheduling failed) + */ + public int scheduleSyncDelayedTask(Runnable task, long delay) { + return Bukkit.getScheduler().scheduleSyncDelayedTask(authMe, task, delay); + } + + /** + * Broadcast a message to all players. + * + * @param message the message + * @return the number of players + */ + public int broadcastMessage(String message) { + return Bukkit.broadcastMessage(message); + } + +} diff --git a/src/test/java/fr/xephi/authme/AntiBotTest.java b/src/test/java/fr/xephi/authme/AntiBotTest.java deleted file mode 100644 index 25e250fda..000000000 --- a/src/test/java/fr/xephi/authme/AntiBotTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package fr.xephi.authme; - -import fr.xephi.authme.settings.Settings; -import fr.xephi.authme.util.WrapperMock; -import org.junit.Before; -import org.junit.Test; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - -/** - * Test for {@link AntiBot}. - */ -public class AntiBotTest { - - private WrapperMock wrapper; - - @Before - public void setUpMocks() { - wrapper = WrapperMock.createInstance(); - } - - @Test - public void shouldNotEnableAntiBot() { - // given - Settings.enableAntiBot = false; - - // when - AntiBot.setupAntiBotService(); - - // then - verify(wrapper.getScheduler(), never()).scheduleSyncDelayedTask(any(AuthMe.class), any(Runnable.class)); - } -} diff --git a/src/test/java/fr/xephi/authme/command/CommandServiceTest.java b/src/test/java/fr/xephi/authme/command/CommandServiceTest.java index 242e9eac1..d34ee6331 100644 --- a/src/test/java/fr/xephi/authme/command/CommandServiceTest.java +++ b/src/test/java/fr/xephi/authme/command/CommandServiceTest.java @@ -1,5 +1,6 @@ package fr.xephi.authme.command; +import fr.xephi.authme.AntiBot; import fr.xephi.authme.AuthMe; import fr.xephi.authme.cache.IpAddressManager; import fr.xephi.authme.command.help.HelpProvider; @@ -18,7 +19,10 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; import java.util.Arrays; import java.util.List; @@ -33,34 +37,37 @@ import static org.mockito.Mockito.verify; /** * Test for {@link CommandService}. */ +@RunWith(MockitoJUnitRunner.class) public class CommandServiceTest { - private AuthMe authMe; - private CommandMapper commandMapper; - private HelpProvider helpProvider; - private Messages messages; - private PasswordSecurity passwordSecurity; private CommandService commandService; + @Mock + private AuthMe authMe; + @Mock + private CommandMapper commandMapper; + @Mock + private HelpProvider helpProvider; + @Mock + private Messages messages; + @Mock + private PasswordSecurity passwordSecurity; + @Mock private PermissionsManager permissionsManager; + @Mock private NewSetting settings; + @Mock private IpAddressManager ipAddressManager; + @Mock private PluginHooks pluginHooks; + @Mock private SpawnLoader spawnLoader; + @Mock + private AntiBot antiBot; @Before public void setUpService() { - authMe = mock(AuthMe.class); - commandMapper = mock(CommandMapper.class); - helpProvider = mock(HelpProvider.class); - messages = mock(Messages.class); - passwordSecurity = mock(PasswordSecurity.class); - permissionsManager = mock(PermissionsManager.class); - settings = mock(NewSetting.class); - ipAddressManager = mock(IpAddressManager.class); - pluginHooks = mock(PluginHooks.class); - spawnLoader = mock(SpawnLoader.class); commandService = new CommandService(authMe, commandMapper, helpProvider, messages, passwordSecurity, - permissionsManager, settings, ipAddressManager, pluginHooks, spawnLoader); + permissionsManager, settings, ipAddressManager, pluginHooks, spawnLoader, antiBot); } @Test