From 5e5836f1676a910407c927f32b72b254ae9d308d Mon Sep 17 00:00:00 2001 From: ljacqu Date: Sun, 8 May 2016 11:15:56 +0200 Subject: [PATCH] #432 Injector improvements - Separate FieldInjection from default fallback for no-Inject public no-args constructor classes - Make CommandInitializer a normal, instantiable service - Add various injections instead of fetching through command service --- src/main/java/fr/xephi/authme/AuthMe.java | 3 - .../xephi/authme/command/CommandHandler.java | 7 +- .../authme/command/CommandInitializer.java | 27 ++++-- .../xephi/authme/command/CommandMapper.java | 5 +- .../xephi/authme/command/CommandService.java | 60 ++----------- .../executable/authme/ConverterCommand.java | 19 +++-- .../executable/authme/FirstSpawnCommand.java | 9 +- .../executable/authme/ForceLoginCommand.java | 13 ++- .../authme/PurgeBannedPlayersCommand.java | 12 ++- .../executable/authme/PurgeCommand.java | 12 ++- .../executable/authme/ReloadCommand.java | 5 +- .../authme/SetFirstSpawnCommand.java | 7 +- .../executable/authme/SetSpawnCommand.java | 7 +- .../executable/authme/SpawnCommand.java | 9 +- .../authme/UnregisterAdminCommand.java | 8 +- .../executable/captcha/CaptchaCommand.java | 9 +- .../executable/email/AddEmailCommand.java | 7 +- .../executable/email/ChangeEmailCommand.java | 7 +- .../executable/email/RecoverEmailCommand.java | 4 +- .../executable/login/LoginCommand.java | 7 +- .../executable/logout/LogoutCommand.java | 7 +- .../executable/register/RegisterCommand.java | 11 ++- .../unregister/UnregisterCommand.java | 7 +- .../AuthMeServiceInitializer.java | 3 +- .../authme/initialization/BaseCommands.java | 14 ---- .../authme/initialization/FieldInjection.java | 4 +- .../initialization/InstantiationFallback.java | 84 +++++++++++++++++++ .../listener/AuthMePlayerListener19.java | 11 ++- .../authme/listener/AuthMeServerListener.java | 7 +- .../authme/command/CommandHandlerTest.java | 25 +++--- .../command/CommandInitializerTest.java | 6 +- .../authme/command/CommandMapperTest.java | 4 +- .../authme/command/CommandServiceTest.java | 48 ----------- .../authme/FirstSpawnCommandTest.java | 23 +++-- .../authme/ForceLoginCommandTest.java | 35 ++++---- .../executable/authme/ReloadCommandTest.java | 24 +++--- .../authme/SetFirstSpawnCommandTest.java | 27 +++--- .../authme/SetSpawnCommandTest.java | 27 +++--- .../executable/authme/SpawnCommandTest.java | 23 +++-- .../executable/email/AddEmailCommandTest.java | 18 ++-- .../email/ChangeEmailCommandTest.java | 26 +++--- .../executable/login/LoginCommandTest.java | 16 ++-- .../executable/logout/LogoutCommandTest.java | 21 +++-- .../register/RegisterCommandTest.java | 29 ++----- .../AuthMeServiceInitializerTest.java | 13 +++ .../ConstructorInjectionTest.java | 5 +- .../initialization/FieldInjectionTest.java | 15 ++++ .../InstantiationFallbackTest.java | 68 +++++++++++++++ .../samples/InstantiationFallbackClasses.java | 45 ++++++++++ .../tools/commands/CommandPageCreater.java | 3 +- 50 files changed, 554 insertions(+), 332 deletions(-) delete mode 100644 src/main/java/fr/xephi/authme/initialization/BaseCommands.java create mode 100644 src/main/java/fr/xephi/authme/initialization/InstantiationFallback.java create mode 100644 src/test/java/fr/xephi/authme/initialization/InstantiationFallbackTest.java create mode 100644 src/test/java/fr/xephi/authme/initialization/samples/InstantiationFallbackClasses.java diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java index 647484cd2..cc0fcaa55 100644 --- a/src/main/java/fr/xephi/authme/AuthMe.java +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -8,7 +8,6 @@ import fr.xephi.authme.cache.backup.JsonCache; import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.cache.limbo.LimboPlayer; import fr.xephi.authme.command.CommandHandler; -import fr.xephi.authme.command.CommandInitializer; import fr.xephi.authme.datasource.CacheDataSource; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSourceType; @@ -18,7 +17,6 @@ import fr.xephi.authme.datasource.SQLite; import fr.xephi.authme.hooks.BungeeCordMessage; import fr.xephi.authme.hooks.PluginHooks; import fr.xephi.authme.initialization.AuthMeServiceInitializer; -import fr.xephi.authme.initialization.BaseCommands; import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.initialization.MetricsStarter; import fr.xephi.authme.listener.AuthMeBlockListener; @@ -261,7 +259,6 @@ public class AuthMe extends JavaPlugin { // Some statically injected things initializer.register(PlayerCache.class, PlayerCache.getInstance()); initializer.register(LimboCache.class, LimboCache.getInstance()); - initializer.provide(BaseCommands.class, CommandInitializer.buildCommands(initializer)); permsMan = initializer.get(PermissionsManager.class); bukkitService = initializer.get(BukkitService.class); diff --git a/src/main/java/fr/xephi/authme/command/CommandHandler.java b/src/main/java/fr/xephi/authme/command/CommandHandler.java index 5f7b32af5..2fdd722d5 100644 --- a/src/main/java/fr/xephi/authme/command/CommandHandler.java +++ b/src/main/java/fr/xephi/authme/command/CommandHandler.java @@ -2,6 +2,7 @@ package fr.xephi.authme.command; import fr.xephi.authme.AuthMe; import fr.xephi.authme.command.help.HelpProvider; +import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.util.StringUtils; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; @@ -23,6 +24,7 @@ public class CommandHandler { private static final double SUGGEST_COMMAND_THRESHOLD = 0.75; private final CommandService commandService; + private final PermissionsManager permissionsManager; /** * Create a command handler. @@ -30,8 +32,9 @@ public class CommandHandler { * @param commandService The CommandService instance */ @Inject - public CommandHandler(CommandService commandService) { + public CommandHandler(CommandService commandService, PermissionsManager permissionsManager) { this.commandService = commandService; + this.permissionsManager = permissionsManager; } /** @@ -126,7 +129,7 @@ public class CommandHandler { private void sendImproperArgumentsMessage(CommandSender sender, FoundCommandResult result) { CommandDescription command = result.getCommandDescription(); - if (!commandService.getPermissionsManager().hasPermission(sender, command)) { + if (!permissionsManager.hasPermission(sender, command)) { sendPermissionDeniedError(sender); return; } diff --git a/src/main/java/fr/xephi/authme/command/CommandInitializer.java b/src/main/java/fr/xephi/authme/command/CommandInitializer.java index 14d72f4a4..ca4cec3b7 100644 --- a/src/main/java/fr/xephi/authme/command/CommandInitializer.java +++ b/src/main/java/fr/xephi/authme/command/CommandInitializer.java @@ -37,6 +37,7 @@ import fr.xephi.authme.initialization.AuthMeServiceInitializer; import fr.xephi.authme.permission.AdminPermission; import fr.xephi.authme.permission.PlayerPermission; +import javax.inject.Inject; import java.util.Arrays; import java.util.Collection; import java.util.List; @@ -48,13 +49,23 @@ import static fr.xephi.authme.permission.DefaultPermission.OP_ONLY; /** * Initializes all available AuthMe commands. */ -public final class CommandInitializer { +public class CommandInitializer { - private CommandInitializer() { - // Helper class + private AuthMeServiceInitializer initializer; + + private Set commands; + + @Inject + public CommandInitializer(AuthMeServiceInitializer initializer) { + this.initializer = initializer; + buildCommands(); } - public static Set buildCommands(AuthMeServiceInitializer initializer) { + public Set getCommands() { + return commands; + } + + private void buildCommands() { // Register the base AuthMe Reloaded command final CommandDescription AUTHME_BASE = CommandDescription.builder() .labels("authme") @@ -402,18 +413,16 @@ public final class CommandInitializer { EMAIL_BASE, CAPTCHA_BASE); - setHelpOnAllBases(baseCommands, initializer); - return baseCommands; + setHelpOnAllBases(baseCommands); + commands = baseCommands; } /** * Set the help command on all base commands, e.g. to register /authme help or /register help. * * @param commands The list of base commands to register a help child command on - * @param initializer The service initializer */ - private static void setHelpOnAllBases(Collection commands, - AuthMeServiceInitializer initializer) { + private void setHelpOnAllBases(Collection commands) { final HelpCommand helpCommandExecutable = initializer.newInstance(HelpCommand.class); final List helpCommandLabels = Arrays.asList("help", "hlp", "h", "sos", "?"); diff --git a/src/main/java/fr/xephi/authme/command/CommandMapper.java b/src/main/java/fr/xephi/authme/command/CommandMapper.java index 18473b281..2bb597a01 100644 --- a/src/main/java/fr/xephi/authme/command/CommandMapper.java +++ b/src/main/java/fr/xephi/authme/command/CommandMapper.java @@ -1,7 +1,6 @@ package fr.xephi.authme.command; import fr.xephi.authme.command.executable.HelpCommand; -import fr.xephi.authme.initialization.BaseCommands; import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.util.CollectionUtils; import fr.xephi.authme.util.StringUtils; @@ -31,8 +30,8 @@ public class CommandMapper { private final PermissionsManager permissionsManager; @Inject - public CommandMapper(@BaseCommands Set baseCommands, PermissionsManager permissionsManager) { - this.baseCommands = baseCommands; + public CommandMapper(CommandInitializer commandInitializer, PermissionsManager permissionsManager) { + this.baseCommands = commandInitializer.getCommands(); this.permissionsManager = permissionsManager; } diff --git a/src/main/java/fr/xephi/authme/command/CommandService.java b/src/main/java/fr/xephi/authme/command/CommandService.java index f88196cce..1e51303d7 100644 --- a/src/main/java/fr/xephi/authme/command/CommandService.java +++ b/src/main/java/fr/xephi/authme/command/CommandService.java @@ -1,20 +1,16 @@ package fr.xephi.authme.command; -import fr.xephi.authme.AuthMe; import fr.xephi.authme.command.help.HelpProvider; -import fr.xephi.authme.hooks.PluginHooks; import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.Messages; -import fr.xephi.authme.permission.PermissionsManager; -import fr.xephi.authme.process.Management; -import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.settings.NewSetting; -import fr.xephi.authme.settings.SpawnLoader; import fr.xephi.authme.settings.domain.Property; import fr.xephi.authme.util.BukkitService; import fr.xephi.authme.util.ValidationService; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scheduler.BukkitTask; import javax.inject.Inject; import java.util.Collection; @@ -27,7 +23,7 @@ import java.util.List; public class CommandService { @Inject - private AuthMe authMe; + private BukkitScheduler scheduler; @Inject private Messages messages; @Inject @@ -36,16 +32,8 @@ public class CommandService { private CommandMapper commandMapper; @SuppressWarnings("unused") @Inject - private PasswordSecurity passwordSecurity; - @Inject - private PermissionsManager permissionsManager; - @Inject private NewSetting settings; @Inject - private PluginHooks pluginHooks; - @Inject - private SpawnLoader spawnLoader; - @Inject private ValidationService validationService; @Inject private BukkitService bukkitService; @@ -86,19 +74,12 @@ public class CommandService { * Run the given task asynchronously with the Bukkit scheduler. * * @param task The task to run + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalArgumentException if task is null */ - public void runTaskAsynchronously(Runnable task) { - authMe.getServer().getScheduler().runTaskAsynchronously(authMe, task); - } - - /** - * Return the AuthMe instance for further manipulation. Use only if other methods from - * the command service cannot be used. - * - * @return The AuthMe instance - */ - public AuthMe getAuthMe() { - return authMe; + public BukkitTask runTaskAsynchronously(Runnable task) { + return bukkitService.runTaskAsynchronously(task); } /** @@ -115,24 +96,6 @@ public class CommandService { } } - /** - * Return the management instance of the plugin. - * - * @return The Management instance linked to the AuthMe instance - */ - public Management getManagement() { - return authMe.getManagement(); - } - - /** - * Return the permissions manager. - * - * @return the permissions manager - */ - public PermissionsManager getPermissionsManager() { - return permissionsManager; - } - /** * Retrieve a message by its message key. * @@ -163,13 +126,6 @@ public class CommandService { return settings; } - public PluginHooks getPluginHooks() { - return pluginHooks; - } - - public SpawnLoader getSpawnLoader() { - return spawnLoader; - } /** * Verifies whether a password is valid according to the plugin settings. diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/ConverterCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/ConverterCommand.java index e34144805..f4a136404 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/ConverterCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/ConverterCommand.java @@ -13,15 +13,16 @@ import fr.xephi.authme.converter.xAuthConverter; import fr.xephi.authme.output.MessageKey; import org.bukkit.command.CommandSender; +import javax.inject.Inject; import java.util.List; public class ConverterCommand implements ExecutableCommand { + @Inject + private AuthMe authMe; + @Override public void executeCommand(CommandSender sender, List arguments, CommandService commandService) { - // AuthMe plugin instance - final AuthMe plugin = AuthMe.getInstance(); - // Get the conversion job String job = arguments.get(0); @@ -36,22 +37,22 @@ public class ConverterCommand implements ExecutableCommand { Converter converter = null; switch (jobType) { case XAUTH: - converter = new xAuthConverter(plugin, sender); + converter = new xAuthConverter(authMe, sender); break; case CRAZYLOGIN: - converter = new CrazyLoginConverter(plugin, sender); + converter = new CrazyLoginConverter(authMe, sender); break; case RAKAMAK: - converter = new RakamakConverter(plugin, sender); + converter = new RakamakConverter(authMe, sender); break; case ROYALAUTH: - converter = new RoyalAuthConverter(plugin); + converter = new RoyalAuthConverter(authMe); break; case VAUTH: - converter = new vAuthConverter(plugin, sender); + converter = new vAuthConverter(authMe, sender); break; case SQLITETOSQL: - converter = new SqliteToSql(plugin, sender, commandService.getSettings()); + converter = new SqliteToSql(authMe, sender, commandService.getSettings()); break; default: break; diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/FirstSpawnCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/FirstSpawnCommand.java index 50b3b1697..9cb3ca9ba 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/FirstSpawnCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/FirstSpawnCommand.java @@ -2,8 +2,10 @@ package fr.xephi.authme.command.executable.authme; import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.PlayerCommand; +import fr.xephi.authme.settings.SpawnLoader; import org.bukkit.entity.Player; +import javax.inject.Inject; import java.util.List; /** @@ -11,10 +13,13 @@ import java.util.List; */ public class FirstSpawnCommand extends PlayerCommand { + @Inject + private SpawnLoader spawnLoader; + @Override public void runCommand(Player player, List arguments, CommandService commandService) { - if (commandService.getSpawnLoader().getFirstSpawn() != null) { - player.teleport(commandService.getSpawnLoader().getFirstSpawn()); + if (spawnLoader.getFirstSpawn() != null) { + player.teleport(spawnLoader.getFirstSpawn()); } else { player.sendMessage("[AuthMe] First spawn has failed, please try to define the first spawn"); } diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/ForceLoginCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/ForceLoginCommand.java index c974e7ea5..3535cf6ff 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/ForceLoginCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/ForceLoginCommand.java @@ -2,9 +2,12 @@ package fr.xephi.authme.command.executable.authme; import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.ExecutableCommand; +import fr.xephi.authme.permission.PermissionsManager; +import fr.xephi.authme.process.Management; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import javax.inject.Inject; import java.util.List; import static fr.xephi.authme.permission.PlayerPermission.CAN_LOGIN_BE_FORCED; @@ -14,6 +17,12 @@ import static fr.xephi.authme.permission.PlayerPermission.CAN_LOGIN_BE_FORCED; */ public class ForceLoginCommand implements ExecutableCommand { + @Inject + private PermissionsManager permissionsManager; + + @Inject + private Management management; + @Override public void executeCommand(CommandSender sender, List arguments, CommandService commandService) { // Get the player query @@ -22,10 +31,10 @@ public class ForceLoginCommand implements ExecutableCommand { Player player = commandService.getPlayer(playerName); if (player == null || !player.isOnline()) { sender.sendMessage("Player needs to be online!"); - } else if (!commandService.getPermissionsManager().hasPermission(player, CAN_LOGIN_BE_FORCED)) { + } else if (!permissionsManager.hasPermission(player, CAN_LOGIN_BE_FORCED)) { sender.sendMessage("You cannot force login the player " + playerName + "!"); } else { - commandService.getManagement().performLogin(player, "dontneed", true); + management.performLogin(player, "dontneed", true); sender.sendMessage("Force login for " + playerName + " performed!"); } } diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/PurgeBannedPlayersCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/PurgeBannedPlayersCommand.java index 995350279..1cedecd80 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/PurgeBannedPlayersCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/PurgeBannedPlayersCommand.java @@ -4,6 +4,7 @@ import fr.xephi.authme.AuthMe; import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.hooks.PluginHooks; import fr.xephi.authme.settings.properties.PurgeSettings; import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; @@ -21,11 +22,14 @@ public class PurgeBannedPlayersCommand implements ExecutableCommand { @Inject private DataSource dataSource; + @Inject + private PluginHooks pluginHooks; + + @Inject + private AuthMe plugin; + @Override public void executeCommand(CommandSender sender, List arguments, CommandService commandService) { - // AuthMe plugin instance - final AuthMe plugin = commandService.getAuthMe(); - // Get the list of banned players List bannedPlayers = new ArrayList<>(); for (OfflinePlayer offlinePlayer : commandService.getBukkitService().getBannedPlayers()) { @@ -35,7 +39,7 @@ public class PurgeBannedPlayersCommand implements ExecutableCommand { // Purge the banned players dataSource.purgeBanned(bannedPlayers); if (commandService.getProperty(PurgeSettings.REMOVE_ESSENTIALS_FILES) - && commandService.getPluginHooks().isEssentialsAvailable()) + && pluginHooks.isEssentialsAvailable()) plugin.dataManager.purgeEssentials(bannedPlayers); if (commandService.getProperty(PurgeSettings.REMOVE_PLAYER_DAT)) plugin.dataManager.purgeDat(bannedPlayers); diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/PurgeCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/PurgeCommand.java index 51ca6df11..afc04c5d5 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/PurgeCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/PurgeCommand.java @@ -4,6 +4,7 @@ import fr.xephi.authme.AuthMe; import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.hooks.PluginHooks; import fr.xephi.authme.settings.properties.PurgeSettings; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; @@ -23,6 +24,12 @@ public class PurgeCommand implements ExecutableCommand { @Inject private DataSource dataSource; + @Inject + private PluginHooks pluginHooks; + + @Inject + private AuthMe plugin; + @Override public void executeCommand(CommandSender sender, List arguments, CommandService commandService) { // Get the days parameter @@ -56,9 +63,8 @@ public class PurgeCommand implements ExecutableCommand { sender.sendMessage(ChatColor.GOLD + "Deleted " + purged.size() + " user accounts"); // Purge other data - AuthMe plugin = commandService.getAuthMe(); - if (commandService.getProperty(PurgeSettings.REMOVE_ESSENTIALS_FILES) && - commandService.getPluginHooks().isEssentialsAvailable()) + if (commandService.getProperty(PurgeSettings.REMOVE_ESSENTIALS_FILES) + && pluginHooks.isEssentialsAvailable()) plugin.dataManager.purgeEssentials(purged); if (commandService.getProperty(PurgeSettings.REMOVE_PLAYER_DAT)) plugin.dataManager.purgeDat(purged); diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/ReloadCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/ReloadCommand.java index 91df58322..3c3bc9218 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/ReloadCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/ReloadCommand.java @@ -7,6 +7,7 @@ import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.output.MessageKey; import org.bukkit.command.CommandSender; +import javax.inject.Inject; import java.util.List; /** @@ -14,9 +15,11 @@ import java.util.List; */ public class ReloadCommand implements ExecutableCommand { + @Inject + private AuthMe plugin; + @Override public void executeCommand(CommandSender sender, List arguments, CommandService commandService) { - AuthMe plugin = commandService.getAuthMe(); try { plugin.reload(); commandService.send(sender, MessageKey.CONFIG_RELOAD_SUCCESS); diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/SetFirstSpawnCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/SetFirstSpawnCommand.java index a3cc7d454..5d4b6995f 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/SetFirstSpawnCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/SetFirstSpawnCommand.java @@ -2,15 +2,20 @@ package fr.xephi.authme.command.executable.authme; import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.PlayerCommand; +import fr.xephi.authme.settings.SpawnLoader; import org.bukkit.entity.Player; +import javax.inject.Inject; import java.util.List; public class SetFirstSpawnCommand extends PlayerCommand { + @Inject + private SpawnLoader spawnLoader; + @Override public void runCommand(Player player, List arguments, CommandService commandService) { - if (commandService.getSpawnLoader().setFirstSpawn(player.getLocation())) { + if (spawnLoader.setFirstSpawn(player.getLocation())) { player.sendMessage("[AuthMe] Correctly defined new first spawn point"); } else { player.sendMessage("[AuthMe] SetFirstSpawn has failed, please retry"); diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/SetSpawnCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/SetSpawnCommand.java index 3201ea4ca..18cdf13bd 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/SetSpawnCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/SetSpawnCommand.java @@ -2,15 +2,20 @@ package fr.xephi.authme.command.executable.authme; import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.PlayerCommand; +import fr.xephi.authme.settings.SpawnLoader; import org.bukkit.entity.Player; +import javax.inject.Inject; import java.util.List; public class SetSpawnCommand extends PlayerCommand { + @Inject + private SpawnLoader spawnLoader; + @Override public void runCommand(Player player, List arguments, CommandService commandService) { - if (commandService.getSpawnLoader().setSpawn(player.getLocation())) { + if (spawnLoader.setSpawn(player.getLocation())) { player.sendMessage("[AuthMe] Correctly defined new spawn point"); } else { player.sendMessage("[AuthMe] SetSpawn has failed, please retry"); diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/SpawnCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/SpawnCommand.java index 04f8e563d..8c142d251 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/SpawnCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/SpawnCommand.java @@ -2,16 +2,21 @@ package fr.xephi.authme.command.executable.authme; import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.PlayerCommand; +import fr.xephi.authme.settings.SpawnLoader; import org.bukkit.entity.Player; +import javax.inject.Inject; import java.util.List; public class SpawnCommand extends PlayerCommand { + @Inject + private SpawnLoader spawnLoader; + @Override public void runCommand(Player player, List arguments, CommandService commandService) { - if (commandService.getSpawnLoader().getSpawn() != null) { - player.teleport(commandService.getSpawnLoader().getSpawn()); + if (spawnLoader.getSpawn() != null) { + player.teleport(spawnLoader.getSpawn()); } else { player.sendMessage("[AuthMe] Spawn has failed, please try to define the spawn"); } diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/UnregisterAdminCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/UnregisterAdminCommand.java index c69f9affe..e8f38c73e 100644 --- a/src/main/java/fr/xephi/authme/command/executable/authme/UnregisterAdminCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/authme/UnregisterAdminCommand.java @@ -36,6 +36,9 @@ public class UnregisterAdminCommand implements ExecutableCommand { @Inject private PlayerCache playerCache; + @Inject + private AuthMe authMe; + @Override public void executeCommand(final CommandSender sender, List arguments, CommandService commandService) { // Get the player name @@ -79,7 +82,6 @@ public class UnregisterAdminCommand implements ExecutableCommand { * @param service the command service */ private void applyUnregisteredEffectsAndTasks(Player target, CommandService service) { - final AuthMe plugin = service.getAuthMe(); final BukkitService bukkitService = service.getBukkitService(); final String playerNameLowerCase = target.getName().toLowerCase(); @@ -88,11 +90,11 @@ public class UnregisterAdminCommand implements ExecutableCommand { int timeOut = service.getProperty(RestrictionSettings.TIMEOUT) * TICKS_PER_SECOND; int interval = service.getProperty(RegistrationSettings.MESSAGE_INTERVAL); if (timeOut != 0) { - BukkitTask id = bukkitService.runTaskLater(new TimeoutTask(plugin, playerNameLowerCase, target), timeOut); + BukkitTask id = bukkitService.runTaskLater(new TimeoutTask(authMe, playerNameLowerCase, target), timeOut); LimboCache.getInstance().getLimboPlayer(playerNameLowerCase).setTimeoutTask(id); } LimboCache.getInstance().getLimboPlayer(playerNameLowerCase).setMessageTask( - bukkitService.runTask(new MessageTask(service.getBukkitService(), plugin.getMessages(), + bukkitService.runTask(new MessageTask(service.getBukkitService(), authMe.getMessages(), playerNameLowerCase, MessageKey.REGISTER_MESSAGE, interval))); if (service.getProperty(RegistrationSettings.APPLY_BLIND_EFFECT)) { diff --git a/src/main/java/fr/xephi/authme/command/executable/captcha/CaptchaCommand.java b/src/main/java/fr/xephi/authme/command/executable/captcha/CaptchaCommand.java index aba0a950a..ebb44f807 100644 --- a/src/main/java/fr/xephi/authme/command/executable/captcha/CaptchaCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/captcha/CaptchaCommand.java @@ -9,16 +9,21 @@ import fr.xephi.authme.security.RandomString; import fr.xephi.authme.settings.properties.SecuritySettings; import org.bukkit.entity.Player; +import javax.inject.Inject; import java.util.List; public class CaptchaCommand extends PlayerCommand { + @Inject + private AuthMe plugin; + + @Inject + private PlayerCache playerCache; + @Override public void runCommand(Player player, List arguments, CommandService commandService) { final String playerNameLowerCase = player.getName().toLowerCase(); final String captcha = arguments.get(0); - final AuthMe plugin = commandService.getAuthMe(); - PlayerCache playerCache = PlayerCache.getInstance(); // Command logic if (playerCache.isAuthenticated(playerNameLowerCase)) { diff --git a/src/main/java/fr/xephi/authme/command/executable/email/AddEmailCommand.java b/src/main/java/fr/xephi/authme/command/executable/email/AddEmailCommand.java index cd92ebf4c..6d9b384d4 100644 --- a/src/main/java/fr/xephi/authme/command/executable/email/AddEmailCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/email/AddEmailCommand.java @@ -3,8 +3,10 @@ package fr.xephi.authme.command.executable.email; import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.process.Management; import org.bukkit.entity.Player; +import javax.inject.Inject; import java.util.List; /** @@ -12,6 +14,9 @@ import java.util.List; */ public class AddEmailCommand extends PlayerCommand { + @Inject + private Management management; + @Override public void runCommand(Player player, List arguments, CommandService commandService) { String email = arguments.get(0); @@ -19,7 +24,7 @@ public class AddEmailCommand extends PlayerCommand { if (email.equals(emailConfirmation)) { // Closer inspection of the mail address handled by the async task - commandService.getManagement().performAddEmail(player, email); + management.performAddEmail(player, email); } else { commandService.send(player, MessageKey.CONFIRM_EMAIL_MESSAGE); } diff --git a/src/main/java/fr/xephi/authme/command/executable/email/ChangeEmailCommand.java b/src/main/java/fr/xephi/authme/command/executable/email/ChangeEmailCommand.java index 6d7281ac2..333f795ef 100644 --- a/src/main/java/fr/xephi/authme/command/executable/email/ChangeEmailCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/email/ChangeEmailCommand.java @@ -2,8 +2,10 @@ package fr.xephi.authme.command.executable.email; import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.PlayerCommand; +import fr.xephi.authme.process.Management; import org.bukkit.entity.Player; +import javax.inject.Inject; import java.util.List; /** @@ -11,11 +13,14 @@ import java.util.List; */ public class ChangeEmailCommand extends PlayerCommand { + @Inject + private Management management; + @Override public void runCommand(Player player, List arguments, CommandService commandService) { String playerMailOld = arguments.get(0); String playerMailNew = arguments.get(1); - commandService.getManagement().performChangeEmail(player, playerMailOld, playerMailNew); + management.performChangeEmail(player, playerMailOld, playerMailNew); } } diff --git a/src/main/java/fr/xephi/authme/command/executable/email/RecoverEmailCommand.java b/src/main/java/fr/xephi/authme/command/executable/email/RecoverEmailCommand.java index 56fb5e5c6..aba08584c 100644 --- a/src/main/java/fr/xephi/authme/command/executable/email/RecoverEmailCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/email/RecoverEmailCommand.java @@ -29,11 +29,13 @@ public class RecoverEmailCommand extends PlayerCommand { @Inject private PlayerCache playerCache; + @Inject + private AuthMe plugin; + @Override public void runCommand(Player player, List arguments, CommandService commandService) { final String playerMail = arguments.get(0); final String playerName = player.getName(); - final AuthMe plugin = commandService.getAuthMe(); if (plugin.mail == null) { ConsoleLogger.showError("Mail API is not set"); diff --git a/src/main/java/fr/xephi/authme/command/executable/login/LoginCommand.java b/src/main/java/fr/xephi/authme/command/executable/login/LoginCommand.java index 5689ec63b..d10ef91ac 100644 --- a/src/main/java/fr/xephi/authme/command/executable/login/LoginCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/login/LoginCommand.java @@ -2,8 +2,10 @@ package fr.xephi.authme.command.executable.login; import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.PlayerCommand; +import fr.xephi.authme.process.Management; import org.bukkit.entity.Player; +import javax.inject.Inject; import java.util.List; /** @@ -11,9 +13,12 @@ import java.util.List; */ public class LoginCommand extends PlayerCommand { + @Inject + private Management management; + @Override public void runCommand(Player player, List arguments, CommandService commandService) { final String password = arguments.get(0); - commandService.getManagement().performLogin(player, password, false); + management.performLogin(player, password, false); } } diff --git a/src/main/java/fr/xephi/authme/command/executable/logout/LogoutCommand.java b/src/main/java/fr/xephi/authme/command/executable/logout/LogoutCommand.java index 598d17380..2236f125d 100644 --- a/src/main/java/fr/xephi/authme/command/executable/logout/LogoutCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/logout/LogoutCommand.java @@ -2,8 +2,10 @@ package fr.xephi.authme.command.executable.logout; import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.PlayerCommand; +import fr.xephi.authme.process.Management; import org.bukkit.entity.Player; +import javax.inject.Inject; import java.util.List; /** @@ -11,8 +13,11 @@ import java.util.List; */ public class LogoutCommand extends PlayerCommand { + @Inject + private Management management; + @Override public void runCommand(Player player, List arguments, CommandService commandService) { - commandService.getManagement().performLogout(player); + management.performLogout(player); } } diff --git a/src/main/java/fr/xephi/authme/command/executable/register/RegisterCommand.java b/src/main/java/fr/xephi/authme/command/executable/register/RegisterCommand.java index 37e2100af..54f054e5d 100644 --- a/src/main/java/fr/xephi/authme/command/executable/register/RegisterCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/register/RegisterCommand.java @@ -4,12 +4,14 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.process.Management; import fr.xephi.authme.security.HashAlgorithm; import fr.xephi.authme.security.RandomString; import fr.xephi.authme.settings.properties.EmailSettings; import fr.xephi.authme.settings.properties.SecuritySettings; import org.bukkit.entity.Player; +import javax.inject.Inject; import java.util.List; import static fr.xephi.authme.settings.properties.EmailSettings.RECOVERY_PASSWORD_LENGTH; @@ -19,11 +21,14 @@ import static fr.xephi.authme.settings.properties.RestrictionSettings.ENABLE_PAS public class RegisterCommand extends PlayerCommand { + @Inject + private Management management; + @Override public void runCommand(Player player, List arguments, CommandService commandService) { if (commandService.getProperty(SecuritySettings.PASSWORD_HASH) == HashAlgorithm.TWO_FACTOR) { //for two factor auth we don't need to check the usage - commandService.getManagement().performRegister(player, "", "", true); + management.performRegister(player, "", "", true); return; } @@ -50,7 +55,7 @@ public class RegisterCommand extends PlayerCommand { if (commandService.getProperty(ENABLE_PASSWORD_CONFIRMATION) && !arguments.get(0).equals(arguments.get(1))) { commandService.send(player, MessageKey.PASSWORD_MATCH_ERROR); } else { - commandService.getManagement().performRegister(player, arguments.get(0), "", true); + management.performRegister(player, arguments.get(0), "", true); } } @@ -70,7 +75,7 @@ public class RegisterCommand extends PlayerCommand { commandService.send(player, MessageKey.USAGE_REGISTER); } else { String thePass = RandomString.generate(commandService.getProperty(RECOVERY_PASSWORD_LENGTH)); - commandService.getManagement().performRegister(player, thePass, email, true); + management.performRegister(player, thePass, email, true); } } diff --git a/src/main/java/fr/xephi/authme/command/executable/unregister/UnregisterCommand.java b/src/main/java/fr/xephi/authme/command/executable/unregister/UnregisterCommand.java index 195f659ee..2d0a5bde6 100644 --- a/src/main/java/fr/xephi/authme/command/executable/unregister/UnregisterCommand.java +++ b/src/main/java/fr/xephi/authme/command/executable/unregister/UnregisterCommand.java @@ -4,12 +4,17 @@ import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.output.MessageKey; +import fr.xephi.authme.process.Management; import org.bukkit.entity.Player; +import javax.inject.Inject; import java.util.List; public class UnregisterCommand extends PlayerCommand { + @Inject + private Management management; + @Override public void runCommand(Player player, List arguments, CommandService commandService) { String playerPass = arguments.get(0); @@ -22,6 +27,6 @@ public class UnregisterCommand extends PlayerCommand { } // Unregister the player - commandService.getManagement().performUnregister(player, playerPass, false); + management.performUnregister(player, playerPass, false); } } diff --git a/src/main/java/fr/xephi/authme/initialization/AuthMeServiceInitializer.java b/src/main/java/fr/xephi/authme/initialization/AuthMeServiceInitializer.java index c2241c11d..72c2169c1 100644 --- a/src/main/java/fr/xephi/authme/initialization/AuthMeServiceInitializer.java +++ b/src/main/java/fr/xephi/authme/initialization/AuthMeServiceInitializer.java @@ -132,7 +132,8 @@ public class AuthMeServiceInitializer { * @return the instantiated object */ private T instantiate(Class clazz, Set> traversedClasses) { - Injection injection = firstNotNull(ConstructorInjection.provide(clazz), FieldInjection.provide(clazz)); + Injection injection = firstNotNull( + ConstructorInjection.provide(clazz), FieldInjection.provide(clazz), InstantiationFallback.provide(clazz)); if (injection == null) { throw new IllegalStateException("Did not find injection method for " + clazz + ". Make sure you have " + "a constructor with @Inject or fields with @Inject. Fields with @Inject require " diff --git a/src/main/java/fr/xephi/authme/initialization/BaseCommands.java b/src/main/java/fr/xephi/authme/initialization/BaseCommands.java deleted file mode 100644 index 8ff263abd..000000000 --- a/src/main/java/fr/xephi/authme/initialization/BaseCommands.java +++ /dev/null @@ -1,14 +0,0 @@ -package fr.xephi.authme.initialization; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Annotation to denote the collection of AuthMe commands. - */ -@Target({ElementType.PARAMETER, ElementType.FIELD}) -@Retention(RetentionPolicy.RUNTIME) -public @interface BaseCommands { -} diff --git a/src/main/java/fr/xephi/authme/initialization/FieldInjection.java b/src/main/java/fr/xephi/authme/initialization/FieldInjection.java index 1e7973e23..b8112b876 100644 --- a/src/main/java/fr/xephi/authme/initialization/FieldInjection.java +++ b/src/main/java/fr/xephi/authme/initialization/FieldInjection.java @@ -74,7 +74,7 @@ class FieldInjection implements Injection { * * @param clazz the class to provide field injection for * @param the class' type - * @return field injection provider for the given class + * @return field injection provider for the given class, or null if not applicable */ public static Provider> provide(final Class clazz) { return new Provider>() { @@ -85,7 +85,7 @@ class FieldInjection implements Injection { return null; } List fields = getInjectionFields(clazz); - return fields == null ? null : new FieldInjection<>(constructor, fields); + return fields.isEmpty() ? null : new FieldInjection<>(constructor, fields); } }; } diff --git a/src/main/java/fr/xephi/authme/initialization/InstantiationFallback.java b/src/main/java/fr/xephi/authme/initialization/InstantiationFallback.java new file mode 100644 index 000000000..f7017ce15 --- /dev/null +++ b/src/main/java/fr/xephi/authme/initialization/InstantiationFallback.java @@ -0,0 +1,84 @@ +package fr.xephi.authme.initialization; + +import javax.inject.Inject; +import javax.inject.Provider; +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; + +/** + * Fallback instantiation method for classes with an accessible no-args constructor + * and no no {@link Inject} annotations whatsoever. + */ +public class InstantiationFallback implements Injection { + + private final Constructor constructor; + + private InstantiationFallback(Constructor constructor) { + this.constructor = constructor; + } + + @Override + public Class[] getDependencies() { + return new Class[0]; + } + + @Override + public Class[] getDependencyAnnotations() { + return new Class[0]; + } + + @Override + public T instantiateWith(Object... values) { + if (values == null || values.length > 0) { + throw new UnsupportedOperationException("Instantiation fallback cannot have parameters"); + } + try { + return constructor.newInstance(); + } catch (InvocationTargetException | IllegalAccessException | InstantiationException e) { + throw new UnsupportedOperationException(e); + } + } + + /** + * Returns an instantiation fallback if the class is applicable. + * + * @param clazz the class + * @param the class' type + * @return instantiation fallback provider for the given class, or null if not applicable + */ + public static Provider> provide(final Class clazz) { + return new Provider>() { + @Override + public InstantiationFallback get() { + Constructor noArgsConstructor = getNoArgsConstructor(clazz); + // Return fallback only if we have no args constructor and no @Inject annotation anywhere + if (noArgsConstructor != null + && !isInjectAnnotationPresent(clazz.getDeclaredConstructors()) + && !isInjectAnnotationPresent(clazz.getDeclaredFields()) + && !isInjectAnnotationPresent(clazz.getDeclaredMethods())) { + return new InstantiationFallback<>(noArgsConstructor); + } + return null; + } + }; + } + + private static Constructor getNoArgsConstructor(Class clazz) { + try { + // Note ljacqu 20160504: getConstructor(), unlike getDeclaredConstructor(), only considers public members + return clazz.getConstructor(); + } catch (NoSuchMethodException e) { + return null; + } + } + + private static boolean isInjectAnnotationPresent(A[] accessibles) { + for (A accessible : accessibles) { + if (accessible.isAnnotationPresent(Inject.class)) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener19.java b/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener19.java index 8be48ba2b..f5a202775 100644 --- a/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener19.java +++ b/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener19.java @@ -1,12 +1,11 @@ package fr.xephi.authme.listener; +import fr.xephi.authme.settings.SpawnLoader; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.spigotmc.event.player.PlayerSpawnLocationEvent; -import fr.xephi.authme.AuthMe; - import javax.inject.Inject; /** @@ -15,13 +14,13 @@ import javax.inject.Inject; public class AuthMePlayerListener19 implements Listener { @Inject - private AuthMe plugin; - - public AuthMePlayerListener19() { } + private SpawnLoader spawnLoader; + + AuthMePlayerListener19() { } @EventHandler(priority = EventPriority.LOWEST) public void onPlayerSpawn(PlayerSpawnLocationEvent event) { - event.setSpawnLocation(plugin.getSpawnLocation(event.getPlayer())); + event.setSpawnLocation(spawnLoader.getSpawnLocation(event.getPlayer())); } } diff --git a/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java b/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java index bb85374d1..0e3162b89 100644 --- a/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java +++ b/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java @@ -5,6 +5,7 @@ import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.hooks.PluginHooks; import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.Messages; +import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.settings.NewSetting; import fr.xephi.authme.settings.SpawnLoader; import fr.xephi.authme.settings.properties.ProtectionSettings; @@ -34,6 +35,8 @@ public class AuthMeServerListener implements Listener { private SpawnLoader spawnLoader; @Inject private ValidationService validationService; + @Inject + private PermissionsManager permissionsManager; @EventHandler(priority = EventPriority.HIGHEST) public void onServerPing(ServerListPingEvent event) { @@ -53,7 +56,7 @@ public class AuthMeServerListener implements Listener { } // Call the onPluginDisable method in the permissions manager - plugin.getPermissionsManager().onPluginDisable(event); + permissionsManager.onPluginDisable(event); final String pluginName = event.getPlugin().getName(); if ("Essentials".equalsIgnoreCase(pluginName)) { @@ -86,7 +89,7 @@ public class AuthMeServerListener implements Listener { } // Call the onPluginEnable method in the permissions manager - plugin.getPermissionsManager().onPluginEnable(event); + permissionsManager.onPluginEnable(event); final String pluginName = event.getPlugin().getName(); if ("Essentials".equalsIgnoreCase(pluginName)) { diff --git a/src/test/java/fr/xephi/authme/command/CommandHandlerTest.java b/src/test/java/fr/xephi/authme/command/CommandHandlerTest.java index e5e6b7496..914fe195b 100644 --- a/src/test/java/fr/xephi/authme/command/CommandHandlerTest.java +++ b/src/test/java/fr/xephi/authme/command/CommandHandlerTest.java @@ -2,11 +2,13 @@ package fr.xephi.authme.command; import fr.xephi.authme.permission.PermissionsManager; import org.bukkit.command.CommandSender; -import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; -import org.mockito.MockitoAnnotations; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; import java.util.Collections; import java.util.List; @@ -35,23 +37,24 @@ import static org.mockito.Mockito.verify; /** * Test for {@link CommandHandler}. */ -@SuppressWarnings("ArraysAsListWithZeroOrOneArgument") // Justification: It's more readable to use asList() everywhere in the test when we often generated two lists where one // often consists of only one element, e.g. myMethod(asList("authme"), asList("my", "args"), ...) +@SuppressWarnings("ArraysAsListWithZeroOrOneArgument") +@RunWith(MockitoJUnitRunner.class) public class CommandHandlerTest { + @InjectMocks private CommandHandler handler; + + @Mock private CommandService serviceMock; + @Mock + private PermissionsManager permissionsManager; + @Captor private ArgumentCaptor> captor; - @Before - public void setUpCommandHandler() { - MockitoAnnotations.initMocks(this); - serviceMock = mock(CommandService.class); - handler = new CommandHandler(serviceMock); - } @Test public void shouldCallMappedCommandWithArgs() { @@ -109,9 +112,7 @@ public class CommandHandlerTest { CommandDescription command = mock(CommandDescription.class); given(serviceMock.mapPartsToCommand(any(CommandSender.class), anyListOf(String.class))).willReturn( new FoundCommandResult(command, asList("unreg"), asList("testPlayer"), 0.0, INCORRECT_ARGUMENTS)); - PermissionsManager permissionsManager = mock(PermissionsManager.class); given(permissionsManager.hasPermission(sender, command)).willReturn(true); - given(serviceMock.getPermissionsManager()).willReturn(permissionsManager); // when handler.processCommand(sender, bukkitLabel, bukkitArgs); @@ -135,9 +136,7 @@ public class CommandHandlerTest { CommandDescription command = mock(CommandDescription.class); given(serviceMock.mapPartsToCommand(any(CommandSender.class), anyListOf(String.class))).willReturn( new FoundCommandResult(command, asList("unreg"), asList("testPlayer"), 0.0, INCORRECT_ARGUMENTS)); - PermissionsManager permissionsManager = mock(PermissionsManager.class); given(permissionsManager.hasPermission(sender, command)).willReturn(false); - given(serviceMock.getPermissionsManager()).willReturn(permissionsManager); // when handler.processCommand(sender, bukkitLabel, bukkitArgs); diff --git a/src/test/java/fr/xephi/authme/command/CommandInitializerTest.java b/src/test/java/fr/xephi/authme/command/CommandInitializerTest.java index 9eac4f400..786ea4771 100644 --- a/src/test/java/fr/xephi/authme/command/CommandInitializerTest.java +++ b/src/test/java/fr/xephi/authme/command/CommandInitializerTest.java @@ -43,7 +43,7 @@ public class CommandInitializerTest { @SuppressWarnings("unchecked") @BeforeClass - public static void initializeCommandManager() { + public static void initializeCommandCollection() { AuthMeServiceInitializer initializer = mock(AuthMeServiceInitializer.class); when(initializer.newInstance(any(Class.class))).thenAnswer(new Answer() { @Override @@ -52,8 +52,8 @@ public class CommandInitializerTest { return mock(clazz); } }); - - commands = CommandInitializer.buildCommands(initializer); + CommandInitializer commandInitializer = new CommandInitializer(initializer); + commands = commandInitializer.getCommands(); } @Test diff --git a/src/test/java/fr/xephi/authme/command/CommandMapperTest.java b/src/test/java/fr/xephi/authme/command/CommandMapperTest.java index 77840e89e..ebcd0b646 100644 --- a/src/test/java/fr/xephi/authme/command/CommandMapperTest.java +++ b/src/test/java/fr/xephi/authme/command/CommandMapperTest.java @@ -41,7 +41,9 @@ public class CommandMapperTest { @Before public void setUpMocks() { permissionsManager = mock(PermissionsManager.class); - mapper = new CommandMapper(commands, permissionsManager); + CommandInitializer initializer = mock(CommandInitializer.class); + given(initializer.getCommands()).willReturn(commands); + mapper = new CommandMapper(initializer, permissionsManager); } // ----------- diff --git a/src/test/java/fr/xephi/authme/command/CommandServiceTest.java b/src/test/java/fr/xephi/authme/command/CommandServiceTest.java index 76685fce1..996197e64 100644 --- a/src/test/java/fr/xephi/authme/command/CommandServiceTest.java +++ b/src/test/java/fr/xephi/authme/command/CommandServiceTest.java @@ -1,15 +1,9 @@ package fr.xephi.authme.command; -import fr.xephi.authme.AuthMe; import fr.xephi.authme.command.help.HelpProvider; -import fr.xephi.authme.hooks.PluginHooks; import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.Messages; -import fr.xephi.authme.permission.PermissionsManager; -import fr.xephi.authme.process.Management; -import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.settings.NewSetting; -import fr.xephi.authme.settings.SpawnLoader; import fr.xephi.authme.settings.domain.Property; import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.util.BukkitService; @@ -42,24 +36,14 @@ public class CommandServiceTest { @InjectMocks 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 PluginHooks pluginHooks; - @Mock - private SpawnLoader spawnLoader; - @Mock private ValidationService validationService; @Mock private BukkitService bukkitService; @@ -122,29 +106,6 @@ public class CommandServiceTest { assertThat(captor.getAllValues(), equalTo(messages)); } - @Test - public void shouldReturnManagementObject() { - // given - Management management = mock(Management.class); - given(authMe.getManagement()).willReturn(management); - - // when - Management result = commandService.getManagement(); - - // then - assertThat(result, equalTo(management)); - verify(authMe).getManagement(); - } - - @Test - public void shouldReturnPermissionsManager() { - // given / when - PermissionsManager result = commandService.getPermissionsManager(); - - // then - assertThat(result, equalTo(permissionsManager)); - } - @Test public void shouldRetrieveMessage() { // given @@ -183,15 +144,6 @@ public class CommandServiceTest { assertThat(result, equalTo(settings)); } - @Test - public void shouldReturnAuthMe() { - // given/when - AuthMe result = commandService.getAuthMe(); - - // then - assertThat(result, equalTo(authMe)); - } - @Test public void shouldValidatePassword() { // given diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/FirstSpawnCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/FirstSpawnCommandTest.java index 0c70bd01b..42edaeb26 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/FirstSpawnCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/FirstSpawnCommandTest.java @@ -1,11 +1,14 @@ package fr.xephi.authme.command.executable.authme; import fr.xephi.authme.command.CommandService; -import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.settings.SpawnLoader; import org.bukkit.Location; import org.bukkit.entity.Player; import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; import java.util.Collections; @@ -21,18 +24,24 @@ import static org.mockito.Mockito.verify; /** * Test for {@link FirstSpawnCommand}. */ +@RunWith(MockitoJUnitRunner.class) public class FirstSpawnCommandTest { + @InjectMocks + private FirstSpawnCommand command; + + @Mock + private SpawnLoader spawnLoader; + + @Mock + private CommandService service; + @Test public void shouldTeleportToFirstSpawn() { // given Location firstSpawn = mock(Location.class); - SpawnLoader spawnLoader = mock(SpawnLoader.class); given(spawnLoader.getFirstSpawn()).willReturn(firstSpawn); - CommandService service = mock(CommandService.class); - given(service.getSpawnLoader()).willReturn(spawnLoader); Player player = mock(Player.class); - ExecutableCommand command = new FirstSpawnCommand(); // when command.executeCommand(player, Collections.emptyList(), service); @@ -45,12 +54,8 @@ public class FirstSpawnCommandTest { @Test public void shouldHandleMissingFirstSpawn() { // given - SpawnLoader spawnLoader = mock(SpawnLoader.class); given(spawnLoader.getFirstSpawn()).willReturn(null); - CommandService service = mock(CommandService.class); - given(service.getSpawnLoader()).willReturn(spawnLoader); Player player = mock(Player.class); - ExecutableCommand command = new FirstSpawnCommand(); // when command.executeCommand(player, Collections.emptyList(), service); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/ForceLoginCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/ForceLoginCommandTest.java index f6a01f2db..87819e333 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/ForceLoginCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/ForceLoginCommandTest.java @@ -9,6 +9,7 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @@ -21,8 +22,8 @@ import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.argThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; /** * Test for {@link ForceLoginCommand}. @@ -30,6 +31,15 @@ import static org.mockito.Mockito.verify; @RunWith(MockitoJUnitRunner.class) public class ForceLoginCommandTest { + @InjectMocks + private ForceLoginCommand command; + + @Mock + private Management management; + + @Mock + private PermissionsManager permissionsManager; + @Mock private CommandService commandService; @@ -40,7 +50,6 @@ public class ForceLoginCommandTest { Player player = mockPlayer(false, playerName); given(commandService.getPlayer(playerName)).willReturn(player); CommandSender sender = mock(CommandSender.class); - ExecutableCommand command = new ForceLoginCommand(); // when command.executeCommand(sender, Collections.singletonList(playerName), commandService); @@ -48,7 +57,7 @@ public class ForceLoginCommandTest { // then verify(commandService).getPlayer(playerName); verify(sender).sendMessage(argThat(equalTo("Player needs to be online!"))); - verify(commandService, never()).getManagement(); + verifyZeroInteractions(management); } @Test @@ -65,7 +74,7 @@ public class ForceLoginCommandTest { // then verify(commandService).getPlayer(playerName); verify(sender).sendMessage(argThat(equalTo("Player needs to be online!"))); - verify(commandService, never()).getManagement(); + verifyZeroInteractions(management); } @Test @@ -74,12 +83,8 @@ public class ForceLoginCommandTest { String playerName = "testTest"; Player player = mockPlayer(true, playerName); given(commandService.getPlayer(playerName)).willReturn(player); - PermissionsManager permissionsManager = mock(PermissionsManager.class); given(permissionsManager.hasPermission(player, PlayerPermission.CAN_LOGIN_BE_FORCED)).willReturn(false); - given(commandService.getPermissionsManager()).willReturn(permissionsManager); - CommandSender sender = mock(CommandSender.class); - ExecutableCommand command = new ForceLoginCommand(); // when command.executeCommand(sender, Collections.singletonList(playerName), commandService); @@ -87,7 +92,7 @@ public class ForceLoginCommandTest { // then verify(commandService).getPlayer(playerName); verify(sender).sendMessage(argThat(containsString("You cannot force login the player"))); - verify(commandService, never()).getManagement(); + verifyZeroInteractions(management); } @Test @@ -96,14 +101,8 @@ public class ForceLoginCommandTest { String playerName = "tester23"; Player player = mockPlayer(true, playerName); given(commandService.getPlayer(playerName)).willReturn(player); - PermissionsManager permissionsManager = mock(PermissionsManager.class); given(permissionsManager.hasPermission(player, PlayerPermission.CAN_LOGIN_BE_FORCED)).willReturn(true); - given(commandService.getPermissionsManager()).willReturn(permissionsManager); - Management management = mock(Management.class); - given(commandService.getManagement()).willReturn(management); - CommandSender sender = mock(CommandSender.class); - ExecutableCommand command = new ForceLoginCommand(); // when command.executeCommand(sender, Collections.singletonList(playerName), commandService); @@ -119,15 +118,9 @@ public class ForceLoginCommandTest { String senderName = "tester23"; Player player = mockPlayer(true, senderName); given(commandService.getPlayer(senderName)).willReturn(player); - PermissionsManager permissionsManager = mock(PermissionsManager.class); given(permissionsManager.hasPermission(player, PlayerPermission.CAN_LOGIN_BE_FORCED)).willReturn(true); - given(commandService.getPermissionsManager()).willReturn(permissionsManager); - Management management = mock(Management.class); - given(commandService.getManagement()).willReturn(management); - CommandSender sender = mock(CommandSender.class); given(sender.getName()).willReturn(senderName); - ExecutableCommand command = new ForceLoginCommand(); // when command.executeCommand(sender, Collections.emptyList(), commandService); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/ReloadCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/ReloadCommandTest.java index 99600c895..426234962 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/ReloadCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/ReloadCommandTest.java @@ -3,15 +3,17 @@ package fr.xephi.authme.command.executable.authme; import fr.xephi.authme.AuthMe; import fr.xephi.authme.TestHelper; import fr.xephi.authme.command.CommandService; -import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.output.MessageKey; import org.bukkit.command.CommandSender; import org.junit.BeforeClass; import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; import java.util.Collections; -import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.matches; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -20,8 +22,18 @@ import static org.mockito.Mockito.verify; /** * Test for {@link ReloadCommand}. */ +@RunWith(MockitoJUnitRunner.class) public class ReloadCommandTest { + @InjectMocks + private ReloadCommand command; + + @Mock + private AuthMe authMe; + + @Mock + private CommandService service; + @BeforeClass public static void setUpLogger() { TestHelper.setupLogger(); @@ -30,11 +42,7 @@ public class ReloadCommandTest { @Test public void shouldReload() throws Exception { // given - AuthMe authMe = mock(AuthMe.class); - CommandService service = mock(CommandService.class); - given(service.getAuthMe()).willReturn(authMe); CommandSender sender = mock(CommandSender.class); - ExecutableCommand command = new ReloadCommand(); // when command.executeCommand(sender, Collections.emptyList(), service); @@ -47,12 +55,8 @@ public class ReloadCommandTest { @Test public void shouldHandleReloadError() throws Exception { // given - AuthMe authMe = mock(AuthMe.class); doThrow(IllegalStateException.class).when(authMe).reload(); - CommandService service = mock(CommandService.class); - given(service.getAuthMe()).willReturn(authMe); CommandSender sender = mock(CommandSender.class); - ExecutableCommand command = new ReloadCommand(); // when command.executeCommand(sender, Collections.emptyList(), service); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/SetFirstSpawnCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/SetFirstSpawnCommandTest.java index 749648827..17163a3a7 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/SetFirstSpawnCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/SetFirstSpawnCommandTest.java @@ -1,11 +1,14 @@ package fr.xephi.authme.command.executable.authme; import fr.xephi.authme.command.CommandService; -import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.settings.SpawnLoader; import org.bukkit.Location; import org.bukkit.entity.Player; import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; import java.util.Collections; @@ -18,21 +21,25 @@ import static org.mockito.Mockito.verify; /** * Test for {@link SetFirstSpawnCommand}. */ +@RunWith(MockitoJUnitRunner.class) public class SetFirstSpawnCommandTest { + @InjectMocks + private SetFirstSpawnCommand command; + + @Mock + private SpawnLoader spawnLoader; + + @Mock + private CommandService service; + @Test public void shouldSetFirstSpawn() { // given Player player = mock(Player.class); Location location = mock(Location.class); given(player.getLocation()).willReturn(location); - - SpawnLoader spawnLoader = mock(SpawnLoader.class); given(spawnLoader.setFirstSpawn(location)).willReturn(true); - CommandService service = mock(CommandService.class); - given(service.getSpawnLoader()).willReturn(spawnLoader); - - ExecutableCommand command = new SetFirstSpawnCommand(); // when command.executeCommand(player, Collections.emptyList(), service); @@ -48,13 +55,7 @@ public class SetFirstSpawnCommandTest { Player player = mock(Player.class); Location location = mock(Location.class); given(player.getLocation()).willReturn(location); - - SpawnLoader spawnLoader = mock(SpawnLoader.class); given(spawnLoader.setFirstSpawn(location)).willReturn(false); - CommandService service = mock(CommandService.class); - given(service.getSpawnLoader()).willReturn(spawnLoader); - - ExecutableCommand command = new SetFirstSpawnCommand(); // when command.executeCommand(player, Collections.emptyList(), service); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/SetSpawnCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/SetSpawnCommandTest.java index e3e01f99e..77e916d95 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/SetSpawnCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/SetSpawnCommandTest.java @@ -1,11 +1,14 @@ package fr.xephi.authme.command.executable.authme; import fr.xephi.authme.command.CommandService; -import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.settings.SpawnLoader; import org.bukkit.Location; import org.bukkit.entity.Player; import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; import java.util.Collections; @@ -18,21 +21,25 @@ import static org.mockito.Mockito.verify; /** * Test for {@link SetSpawnCommand}. */ +@RunWith(MockitoJUnitRunner.class) public class SetSpawnCommandTest { + @InjectMocks + private SetSpawnCommand command; + + @Mock + private SpawnLoader spawnLoader; + + @Mock + private CommandService service; + @Test public void shouldSetSpawn() { // given Player player = mock(Player.class); Location location = mock(Location.class); given(player.getLocation()).willReturn(location); - - SpawnLoader spawnLoader = mock(SpawnLoader.class); given(spawnLoader.setSpawn(location)).willReturn(true); - CommandService service = mock(CommandService.class); - given(service.getSpawnLoader()).willReturn(spawnLoader); - - ExecutableCommand command = new SetSpawnCommand(); // when command.executeCommand(player, Collections.emptyList(), service); @@ -48,13 +55,7 @@ public class SetSpawnCommandTest { Player player = mock(Player.class); Location location = mock(Location.class); given(player.getLocation()).willReturn(location); - - SpawnLoader spawnLoader = mock(SpawnLoader.class); given(spawnLoader.setSpawn(location)).willReturn(false); - CommandService service = mock(CommandService.class); - given(service.getSpawnLoader()).willReturn(spawnLoader); - - ExecutableCommand command = new SetSpawnCommand(); // when command.executeCommand(player, Collections.emptyList(), service); diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/SpawnCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/SpawnCommandTest.java index 799d1ca47..64d006e23 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/SpawnCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/SpawnCommandTest.java @@ -1,11 +1,14 @@ package fr.xephi.authme.command.executable.authme; import fr.xephi.authme.command.CommandService; -import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.settings.SpawnLoader; import org.bukkit.Location; import org.bukkit.entity.Player; import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; import java.util.Collections; @@ -21,18 +24,24 @@ import static org.mockito.Mockito.verify; /** * Test for {@link SpawnCommand}. */ +@RunWith(MockitoJUnitRunner.class) public class SpawnCommandTest { + @InjectMocks + private SpawnCommand command; + + @Mock + private SpawnLoader spawnLoader; + + @Mock + private CommandService service; + @Test public void shouldTeleportToSpawn() { // given Location spawn = mock(Location.class); - SpawnLoader spawnLoader = mock(SpawnLoader.class); given(spawnLoader.getSpawn()).willReturn(spawn); - CommandService service = mock(CommandService.class); - given(service.getSpawnLoader()).willReturn(spawnLoader); Player player = mock(Player.class); - ExecutableCommand command = new SpawnCommand(); // when command.executeCommand(player, Collections.emptyList(), service); @@ -45,12 +54,8 @@ public class SpawnCommandTest { @Test public void shouldHandleMissingSpawn() { // given - SpawnLoader spawnLoader = mock(SpawnLoader.class); given(spawnLoader.getSpawn()).willReturn(null); - CommandService service = mock(CommandService.class); - given(service.getSpawnLoader()).willReturn(spawnLoader); Player player = mock(Player.class); - ExecutableCommand command = new SpawnCommand(); // when command.executeCommand(player, Collections.emptyList(), service); diff --git a/src/test/java/fr/xephi/authme/command/executable/email/AddEmailCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/email/AddEmailCommandTest.java index 1ea413559..9b91ee5b9 100644 --- a/src/test/java/fr/xephi/authme/command/executable/email/AddEmailCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/email/AddEmailCommandTest.java @@ -8,6 +8,7 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @@ -16,8 +17,8 @@ import java.util.Arrays; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; /** * Test for {@link AddEmailCommand}. @@ -25,20 +26,25 @@ import static org.mockito.Mockito.verify; @RunWith(MockitoJUnitRunner.class) public class AddEmailCommandTest { + @InjectMocks + private AddEmailCommand command; + @Mock private CommandService commandService; + @Mock + private Management management; + @Test public void shouldRejectNonPlayerSender() { // given CommandSender sender = mock(BlockCommandSender.class); - AddEmailCommand command = new AddEmailCommand(); // when command.executeCommand(sender, new ArrayList(), commandService); // then - verify(commandService, never()).getManagement(); + verifyZeroInteractions(management); } @Test @@ -47,9 +53,6 @@ public class AddEmailCommandTest { Player sender = mock(Player.class); String email = "mail@example"; given(commandService.validateEmail(email)).willReturn(true); - Management management = mock(Management.class); - given(commandService.getManagement()).willReturn(management); - AddEmailCommand command = new AddEmailCommand(); // when command.executeCommand(sender, Arrays.asList(email, email), commandService); @@ -64,13 +67,12 @@ public class AddEmailCommandTest { Player sender = mock(Player.class); String email = "asdfasdf@example.com"; given(commandService.validateEmail(email)).willReturn(true); - AddEmailCommand command = new AddEmailCommand(); // when command.executeCommand(sender, Arrays.asList(email, "wrongConf"), commandService); // then - verify(commandService, never()).getManagement(); + verifyZeroInteractions(management); verify(commandService).send(sender, MessageKey.CONFIRM_EMAIL_MESSAGE); } diff --git a/src/test/java/fr/xephi/authme/command/executable/email/ChangeEmailCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/email/ChangeEmailCommandTest.java index 7e6d2fb9c..d9f7e0cd2 100644 --- a/src/test/java/fr/xephi/authme/command/executable/email/ChangeEmailCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/email/ChangeEmailCommandTest.java @@ -5,49 +5,51 @@ import fr.xephi.authme.process.Management; import org.bukkit.command.BlockCommandSender; 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.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; import java.util.ArrayList; import java.util.Arrays; -import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; /** * Test for {@link ChangeEmailCommand}. */ +@RunWith(MockitoJUnitRunner.class) public class ChangeEmailCommandTest { + @InjectMocks + private ChangeEmailCommand command; + + @Mock + private Management management; + + @Mock private CommandService commandService; - @Before - public void setUpMocks() { - commandService = mock(CommandService.class); - } @Test public void shouldRejectNonPlayerSender() { // given CommandSender sender = mock(BlockCommandSender.class); - ChangeEmailCommand command = new ChangeEmailCommand(); // when command.executeCommand(sender, new ArrayList(), commandService); // then - verify(commandService, never()).getManagement(); + verifyZeroInteractions(management); } @Test public void shouldForwardData() { // given Player sender = mock(Player.class); - ChangeEmailCommand command = new ChangeEmailCommand(); - Management management = mock(Management.class); - given(commandService.getManagement()).willReturn(management); // when command.executeCommand(sender, Arrays.asList("new.mail@example.org", "old_mail@example.org"), commandService); diff --git a/src/test/java/fr/xephi/authme/command/executable/login/LoginCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/login/LoginCommandTest.java index 9a23bc178..2eede4a13 100644 --- a/src/test/java/fr/xephi/authme/command/executable/login/LoginCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/login/LoginCommandTest.java @@ -7,6 +7,7 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @@ -14,12 +15,11 @@ import java.util.ArrayList; import java.util.Collections; import static org.hamcrest.Matchers.containsString; -import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.argThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; /** * Test for {@link LoginCommand}. @@ -27,6 +27,12 @@ import static org.mockito.Mockito.verify; @RunWith(MockitoJUnitRunner.class) public class LoginCommandTest { + @InjectMocks + private LoginCommand command; + + @Mock + private Management management; + @Mock private CommandService commandService; @@ -34,13 +40,12 @@ public class LoginCommandTest { public void shouldStopIfSenderIsNotAPlayer() { // given CommandSender sender = mock(BlockCommandSender.class); - LoginCommand command = new LoginCommand(); // when command.executeCommand(sender, new ArrayList(), commandService); // then - verify(commandService, never()).getManagement(); + verifyZeroInteractions(management); verify(sender).sendMessage(argThat(containsString("only for players"))); } @@ -48,9 +53,6 @@ public class LoginCommandTest { public void shouldCallManagementForPlayerCaller() { // given Player sender = mock(Player.class); - LoginCommand command = new LoginCommand(); - Management management = mock(Management.class); - given(commandService.getManagement()).willReturn(management); // when command.executeCommand(sender, Collections.singletonList("password"), commandService); diff --git a/src/test/java/fr/xephi/authme/command/executable/logout/LogoutCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/logout/LogoutCommandTest.java index 7ac3ede65..bca24ac2e 100644 --- a/src/test/java/fr/xephi/authme/command/executable/logout/LogoutCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/logout/LogoutCommandTest.java @@ -7,22 +7,33 @@ 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.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; import java.util.ArrayList; import java.util.Collections; import static org.hamcrest.Matchers.containsString; -import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; /** * Test for {@link LogoutCommand}. */ +@RunWith(MockitoJUnitRunner.class) public class LogoutCommandTest { + @InjectMocks + private LogoutCommand command; + + @Mock + private Management management; + + @Mock private CommandService commandService; @Before @@ -34,13 +45,12 @@ public class LogoutCommandTest { public void shouldStopIfSenderIsNotAPlayer() { // given CommandSender sender = mock(BlockCommandSender.class); - LogoutCommand command = new LogoutCommand(); // when command.executeCommand(sender, new ArrayList(), commandService); // then - verify(commandService, never()).getManagement(); + verifyZeroInteractions(management); verify(sender).sendMessage(argThat(containsString("only for players"))); } @@ -48,9 +58,6 @@ public class LogoutCommandTest { public void shouldCallManagementForPlayerCaller() { // given Player sender = mock(Player.class); - LogoutCommand command = new LogoutCommand(); - Management management = mock(Management.class); - given(commandService.getManagement()).willReturn(management); // when command.executeCommand(sender, Collections.singletonList("password"), commandService); diff --git a/src/test/java/fr/xephi/authme/command/executable/register/RegisterCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/register/RegisterCommandTest.java index fecc3fccf..f33ad87e6 100644 --- a/src/test/java/fr/xephi/authme/command/executable/register/RegisterCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/register/RegisterCommandTest.java @@ -2,7 +2,6 @@ package fr.xephi.authme.command.executable.register; import fr.xephi.authme.TestHelper; import fr.xephi.authme.command.CommandService; -import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.process.Management; import fr.xephi.authme.security.HashAlgorithm; @@ -19,6 +18,7 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @@ -40,10 +40,15 @@ import static org.mockito.Mockito.verifyZeroInteractions; @RunWith(MockitoJUnitRunner.class) public class RegisterCommandTest { + @InjectMocks + private RegisterCommand command; + @Mock private CommandService commandService; + @Mock private Management management; + @Mock private Player sender; @@ -54,7 +59,6 @@ public class RegisterCommandTest { @Before public void linkMocksAndProvideSettingDefaults() { - given(commandService.getManagement()).willReturn(management); given(commandService.getProperty(SecuritySettings.PASSWORD_HASH)).willReturn(HashAlgorithm.BCRYPT); given(commandService.getProperty(RegistrationSettings.USE_EMAIL_REGISTRATION)).willReturn(false); given(commandService.getProperty(RestrictionSettings.ENABLE_PASSWORD_CONFIRMATION)).willReturn(false); @@ -64,7 +68,6 @@ public class RegisterCommandTest { public void shouldNotRunForNonPlayerSender() { // given CommandSender sender = mock(BlockCommandSender.class); - RegisterCommand command = new RegisterCommand(); // when command.executeCommand(sender, new ArrayList(), commandService); @@ -78,7 +81,6 @@ public class RegisterCommandTest { public void shouldForwardToManagementForTwoFactor() { // given given(commandService.getProperty(SecuritySettings.PASSWORD_HASH)).willReturn(HashAlgorithm.TWO_FACTOR); - ExecutableCommand command = new RegisterCommand(); // when command.executeCommand(sender, Collections.emptyList(), commandService); @@ -89,10 +91,7 @@ public class RegisterCommandTest { @Test public void shouldReturnErrorForEmptyArguments() { - // given - ExecutableCommand command = new RegisterCommand(); - - // when + // given / when command.executeCommand(sender, Collections.emptyList(), commandService); // then @@ -104,7 +103,6 @@ public class RegisterCommandTest { public void shouldReturnErrorForMissingConfirmation() { // given given(commandService.getProperty(RestrictionSettings.ENABLE_PASSWORD_CONFIRMATION)).willReturn(true); - ExecutableCommand command = new RegisterCommand(); // when command.executeCommand(sender, Collections.singletonList("arrrr"), commandService); @@ -119,7 +117,6 @@ public class RegisterCommandTest { // given given(commandService.getProperty(RegistrationSettings.USE_EMAIL_REGISTRATION)).willReturn(true); given(commandService.getProperty(RegistrationSettings.ENABLE_CONFIRM_EMAIL)).willReturn(true); - ExecutableCommand command = new RegisterCommand(); // when command.executeCommand(sender, Collections.singletonList("test@example.org"), commandService); @@ -135,7 +132,6 @@ public class RegisterCommandTest { given(commandService.getProperty(RegistrationSettings.USE_EMAIL_REGISTRATION)).willReturn(true); given(commandService.getProperty(RegistrationSettings.ENABLE_CONFIRM_EMAIL)).willReturn(false); given(commandService.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn(""); - ExecutableCommand command = new RegisterCommand(); // when command.executeCommand(sender, Collections.singletonList("myMail@example.tld"), commandService); @@ -155,8 +151,6 @@ public class RegisterCommandTest { given(commandService.getProperty(RegistrationSettings.ENABLE_CONFIRM_EMAIL)).willReturn(true); given(commandService.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn("server@example.com"); - ExecutableCommand command = new RegisterCommand(); - // when command.executeCommand(sender, Arrays.asList(playerMail, playerMail), commandService); @@ -176,8 +170,6 @@ public class RegisterCommandTest { given(commandService.getProperty(RegistrationSettings.ENABLE_CONFIRM_EMAIL)).willReturn(true); given(commandService.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn("server@example.com"); - ExecutableCommand command = new RegisterCommand(); - // when command.executeCommand(sender, Arrays.asList(playerMail, "invalid"), commandService); @@ -197,7 +189,6 @@ public class RegisterCommandTest { given(commandService.getProperty(RegistrationSettings.USE_EMAIL_REGISTRATION)).willReturn(true); given(commandService.getProperty(RegistrationSettings.ENABLE_CONFIRM_EMAIL)).willReturn(true); given(commandService.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn("server@example.com"); - ExecutableCommand command = new RegisterCommand(); // when command.executeCommand(sender, Arrays.asList(playerMail, playerMail), commandService); @@ -211,7 +202,6 @@ public class RegisterCommandTest { public void shouldRejectInvalidPasswordConfirmation() { // given given(commandService.getProperty(RestrictionSettings.ENABLE_PASSWORD_CONFIRMATION)).willReturn(true); - ExecutableCommand command = new RegisterCommand(); // when command.executeCommand(sender, Arrays.asList("myPass", "mypass"), commandService); @@ -223,10 +213,7 @@ public class RegisterCommandTest { @Test public void shouldPerformPasswordValidation() { - // given - ExecutableCommand command = new RegisterCommand(); - - // when + // given / when command.executeCommand(sender, Collections.singletonList("myPass"), commandService); // then diff --git a/src/test/java/fr/xephi/authme/initialization/AuthMeServiceInitializerTest.java b/src/test/java/fr/xephi/authme/initialization/AuthMeServiceInitializerTest.java index 0541c7049..63e4d01cd 100644 --- a/src/test/java/fr/xephi/authme/initialization/AuthMeServiceInitializerTest.java +++ b/src/test/java/fr/xephi/authme/initialization/AuthMeServiceInitializerTest.java @@ -8,6 +8,7 @@ import fr.xephi.authme.initialization.samples.ClassWithAbstractDependency; import fr.xephi.authme.initialization.samples.ClassWithAnnotations; import fr.xephi.authme.initialization.samples.Duration; import fr.xephi.authme.initialization.samples.FieldInjectionWithAnnotations; +import fr.xephi.authme.initialization.samples.InstantiationFallbackClasses; import fr.xephi.authme.initialization.samples.InvalidClass; import fr.xephi.authme.initialization.samples.InvalidPostConstruct; import fr.xephi.authme.initialization.samples.InvalidStaticFieldInjection; @@ -231,4 +232,16 @@ public class AuthMeServiceInitializerTest { initializer.newInstance(InvalidStaticFieldInjection.class); } + @Test + public void shouldFallbackToSimpleInstantiationForPlainClass() { + // given / when + InstantiationFallbackClasses.HasFallbackDependency result = + initializer.get(InstantiationFallbackClasses.HasFallbackDependency.class); + + // then + assertThat(result, not(nullValue())); + assertThat(result.getGammaService(), not(nullValue())); + assertThat(result.getFallbackDependency(), not(nullValue())); + } + } diff --git a/src/test/java/fr/xephi/authme/initialization/ConstructorInjectionTest.java b/src/test/java/fr/xephi/authme/initialization/ConstructorInjectionTest.java index df5493e71..c53a4321b 100644 --- a/src/test/java/fr/xephi/authme/initialization/ConstructorInjectionTest.java +++ b/src/test/java/fr/xephi/authme/initialization/ConstructorInjectionTest.java @@ -1,6 +1,7 @@ package fr.xephi.authme.initialization; import fr.xephi.authme.initialization.samples.AlphaService; +import fr.xephi.authme.initialization.samples.BetaManager; import fr.xephi.authme.initialization.samples.ClassWithAnnotations; import fr.xephi.authme.initialization.samples.Duration; import fr.xephi.authme.initialization.samples.GammaService; @@ -20,7 +21,6 @@ import static org.junit.Assert.assertThat; */ public class ConstructorInjectionTest { - @SuppressWarnings("unchecked") @Test public void shouldReturnDependencies() { // given @@ -74,8 +74,7 @@ public class ConstructorInjectionTest { @Test public void shouldReturnNullForNoConstructorInjection() { // given / when - @SuppressWarnings("rawtypes") - Injection injection = ConstructorInjection.provide(FieldInjection.class).get(); + Injection injection = ConstructorInjection.provide(BetaManager.class).get(); // then assertThat(injection, nullValue()); diff --git a/src/test/java/fr/xephi/authme/initialization/FieldInjectionTest.java b/src/test/java/fr/xephi/authme/initialization/FieldInjectionTest.java index 77035e4dd..9b25565e4 100644 --- a/src/test/java/fr/xephi/authme/initialization/FieldInjectionTest.java +++ b/src/test/java/fr/xephi/authme/initialization/FieldInjectionTest.java @@ -105,6 +105,15 @@ public class FieldInjectionTest { FieldInjection.provide(InvalidStaticFieldInjection.class).get(); } + @Test + public void shouldNotReturnFieldInjectionForZeroInjectFields() { + // given / when + Injection injection = FieldInjection.provide(NoInjectionClass.class).get(); + + // then + assertThat(injection, nullValue()); + } + private static class ThrowingConstructor { @SuppressWarnings("unused") @Inject @@ -115,4 +124,10 @@ public class FieldInjectionTest { throw new UnsupportedOperationException("Exception in constructor"); } } + + private static class NoInjectionClass { + + private BetaManager betaManager; + + } } diff --git a/src/test/java/fr/xephi/authme/initialization/InstantiationFallbackTest.java b/src/test/java/fr/xephi/authme/initialization/InstantiationFallbackTest.java new file mode 100644 index 000000000..c40648f64 --- /dev/null +++ b/src/test/java/fr/xephi/authme/initialization/InstantiationFallbackTest.java @@ -0,0 +1,68 @@ +package fr.xephi.authme.initialization; + +import fr.xephi.authme.initialization.samples.GammaService; +import fr.xephi.authme.initialization.samples.InstantiationFallbackClasses; +import org.junit.Test; + +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; + +/** + * Test for {@link InstantiationFallback}. + */ +public class InstantiationFallbackTest { + + @Test + public void shouldInstantiateClass() { + // given + Injection instantiation = + InstantiationFallback.provide(InstantiationFallbackClasses.FallbackClass.class).get(); + + // when + InstantiationFallbackClasses.FallbackClass result = instantiation.instantiateWith(); + + // then + assertThat(result, not(nullValue())); + } + + @Test(expected = RuntimeException.class) + public void shouldThrowIfArgumentsAreSupplied() { + // given + Injection instantiation = + InstantiationFallback.provide(InstantiationFallbackClasses.FallbackClass.class).get(); + + // when / then + instantiation.instantiateWith("some argument"); + } + + @Test + public void shouldReturnNullForClassWithInjectMethod() { + // given / when + Injection instantiation = + InstantiationFallback.provide(InstantiationFallbackClasses.InvalidInjectOnMethodClass.class).get(); + + // then + assertThat(instantiation, nullValue()); + } + + @Test + public void shouldReturnNullForMissingNoArgsConstructor() { + // given / when + Injection instantiation = + InstantiationFallback.provide(InstantiationFallbackClasses.InvalidFallbackClass.class).get(); + + // then + assertThat(instantiation, nullValue()); + } + + @Test + public void shouldReturnNullForDifferentInjectionType() { + // given / when + Injection instantiation = InstantiationFallback.provide(GammaService.class).get(); + + // then + assertThat(instantiation, nullValue()); + } + +} diff --git a/src/test/java/fr/xephi/authme/initialization/samples/InstantiationFallbackClasses.java b/src/test/java/fr/xephi/authme/initialization/samples/InstantiationFallbackClasses.java new file mode 100644 index 000000000..ae15029b0 --- /dev/null +++ b/src/test/java/fr/xephi/authme/initialization/samples/InstantiationFallbackClasses.java @@ -0,0 +1,45 @@ +package fr.xephi.authme.initialization.samples; + +import javax.inject.Inject; + +/** + * Sample class - triggers instantiation fallback. + */ +public abstract class InstantiationFallbackClasses { + + public static final class FallbackClass { + // No @Inject annotations, public no-args constructor + } + + public static final class HasFallbackDependency { + @Inject + private FallbackClass fallbackClass; + + @Inject + private GammaService gammaService; + + public GammaService getGammaService() { + return gammaService; + } + + public FallbackClass getFallbackDependency() { + return fallbackClass; + } + } + + public static final class InvalidFallbackClass { + private InvalidFallbackClass() { + // no-args constructor must be public for fallback instantiation + } + } + + public static final class InvalidInjectOnMethodClass { + // We don't support method injection but this should still be detected and an exception returned + // Only use instantiation fallback if we're sure there isn't some sort of misconfiguration + @Inject + public void setGammaService(GammaService gammaService) { + // -- + } + } + +} diff --git a/src/test/java/tools/commands/CommandPageCreater.java b/src/test/java/tools/commands/CommandPageCreater.java index ddfaf3e38..17308ebf8 100644 --- a/src/test/java/tools/commands/CommandPageCreater.java +++ b/src/test/java/tools/commands/CommandPageCreater.java @@ -35,7 +35,8 @@ public class CommandPageCreater implements ToolTask { @Override public void execute(Scanner scanner) { - final Set baseCommands = CommandInitializer.buildCommands(getMockInitializer()); + CommandInitializer commandInitializer = new CommandInitializer(getMockInitializer()); + final Set baseCommands = commandInitializer.getCommands(); NestedTagValue commandTags = new NestedTagValue(); addCommandsInfo(commandTags, baseCommands);