#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
This commit is contained in:
ljacqu 2016-05-08 11:15:56 +02:00
parent 3e6223dc5a
commit 5e5836f167
50 changed files with 554 additions and 332 deletions

View File

@ -8,7 +8,6 @@ import fr.xephi.authme.cache.backup.JsonCache;
import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.cache.limbo.LimboPlayer; import fr.xephi.authme.cache.limbo.LimboPlayer;
import fr.xephi.authme.command.CommandHandler; import fr.xephi.authme.command.CommandHandler;
import fr.xephi.authme.command.CommandInitializer;
import fr.xephi.authme.datasource.CacheDataSource; import fr.xephi.authme.datasource.CacheDataSource;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.datasource.DataSourceType; import fr.xephi.authme.datasource.DataSourceType;
@ -18,7 +17,6 @@ import fr.xephi.authme.datasource.SQLite;
import fr.xephi.authme.hooks.BungeeCordMessage; import fr.xephi.authme.hooks.BungeeCordMessage;
import fr.xephi.authme.hooks.PluginHooks; import fr.xephi.authme.hooks.PluginHooks;
import fr.xephi.authme.initialization.AuthMeServiceInitializer; import fr.xephi.authme.initialization.AuthMeServiceInitializer;
import fr.xephi.authme.initialization.BaseCommands;
import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.initialization.DataFolder;
import fr.xephi.authme.initialization.MetricsStarter; import fr.xephi.authme.initialization.MetricsStarter;
import fr.xephi.authme.listener.AuthMeBlockListener; import fr.xephi.authme.listener.AuthMeBlockListener;
@ -261,7 +259,6 @@ public class AuthMe extends JavaPlugin {
// Some statically injected things // Some statically injected things
initializer.register(PlayerCache.class, PlayerCache.getInstance()); initializer.register(PlayerCache.class, PlayerCache.getInstance());
initializer.register(LimboCache.class, LimboCache.getInstance()); initializer.register(LimboCache.class, LimboCache.getInstance());
initializer.provide(BaseCommands.class, CommandInitializer.buildCommands(initializer));
permsMan = initializer.get(PermissionsManager.class); permsMan = initializer.get(PermissionsManager.class);
bukkitService = initializer.get(BukkitService.class); bukkitService = initializer.get(BukkitService.class);

View File

@ -2,6 +2,7 @@ package fr.xephi.authme.command;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.help.HelpProvider; import fr.xephi.authme.command.help.HelpProvider;
import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.util.StringUtils; import fr.xephi.authme.util.StringUtils;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -23,6 +24,7 @@ public class CommandHandler {
private static final double SUGGEST_COMMAND_THRESHOLD = 0.75; private static final double SUGGEST_COMMAND_THRESHOLD = 0.75;
private final CommandService commandService; private final CommandService commandService;
private final PermissionsManager permissionsManager;
/** /**
* Create a command handler. * Create a command handler.
@ -30,8 +32,9 @@ public class CommandHandler {
* @param commandService The CommandService instance * @param commandService The CommandService instance
*/ */
@Inject @Inject
public CommandHandler(CommandService commandService) { public CommandHandler(CommandService commandService, PermissionsManager permissionsManager) {
this.commandService = commandService; this.commandService = commandService;
this.permissionsManager = permissionsManager;
} }
/** /**
@ -126,7 +129,7 @@ public class CommandHandler {
private void sendImproperArgumentsMessage(CommandSender sender, FoundCommandResult result) { private void sendImproperArgumentsMessage(CommandSender sender, FoundCommandResult result) {
CommandDescription command = result.getCommandDescription(); CommandDescription command = result.getCommandDescription();
if (!commandService.getPermissionsManager().hasPermission(sender, command)) { if (!permissionsManager.hasPermission(sender, command)) {
sendPermissionDeniedError(sender); sendPermissionDeniedError(sender);
return; return;
} }

View File

@ -37,6 +37,7 @@ import fr.xephi.authme.initialization.AuthMeServiceInitializer;
import fr.xephi.authme.permission.AdminPermission; import fr.xephi.authme.permission.AdminPermission;
import fr.xephi.authme.permission.PlayerPermission; import fr.xephi.authme.permission.PlayerPermission;
import javax.inject.Inject;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
@ -48,13 +49,23 @@ import static fr.xephi.authme.permission.DefaultPermission.OP_ONLY;
/** /**
* Initializes all available AuthMe commands. * Initializes all available AuthMe commands.
*/ */
public final class CommandInitializer { public class CommandInitializer {
private CommandInitializer() { private AuthMeServiceInitializer initializer;
// Helper class
private Set<CommandDescription> commands;
@Inject
public CommandInitializer(AuthMeServiceInitializer initializer) {
this.initializer = initializer;
buildCommands();
} }
public static Set<CommandDescription> buildCommands(AuthMeServiceInitializer initializer) { public Set<CommandDescription> getCommands() {
return commands;
}
private void buildCommands() {
// Register the base AuthMe Reloaded command // Register the base AuthMe Reloaded command
final CommandDescription AUTHME_BASE = CommandDescription.builder() final CommandDescription AUTHME_BASE = CommandDescription.builder()
.labels("authme") .labels("authme")
@ -402,18 +413,16 @@ public final class CommandInitializer {
EMAIL_BASE, EMAIL_BASE,
CAPTCHA_BASE); CAPTCHA_BASE);
setHelpOnAllBases(baseCommands, initializer); setHelpOnAllBases(baseCommands);
return baseCommands; commands = baseCommands;
} }
/** /**
* Set the help command on all base commands, e.g. to register /authme help or /register help. * 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 commands The list of base commands to register a help child command on
* @param initializer The service initializer
*/ */
private static void setHelpOnAllBases(Collection<CommandDescription> commands, private void setHelpOnAllBases(Collection<CommandDescription> commands) {
AuthMeServiceInitializer initializer) {
final HelpCommand helpCommandExecutable = initializer.newInstance(HelpCommand.class); final HelpCommand helpCommandExecutable = initializer.newInstance(HelpCommand.class);
final List<String> helpCommandLabels = Arrays.asList("help", "hlp", "h", "sos", "?"); final List<String> helpCommandLabels = Arrays.asList("help", "hlp", "h", "sos", "?");

View File

@ -1,7 +1,6 @@
package fr.xephi.authme.command; package fr.xephi.authme.command;
import fr.xephi.authme.command.executable.HelpCommand; import fr.xephi.authme.command.executable.HelpCommand;
import fr.xephi.authme.initialization.BaseCommands;
import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.util.CollectionUtils; import fr.xephi.authme.util.CollectionUtils;
import fr.xephi.authme.util.StringUtils; import fr.xephi.authme.util.StringUtils;
@ -31,8 +30,8 @@ public class CommandMapper {
private final PermissionsManager permissionsManager; private final PermissionsManager permissionsManager;
@Inject @Inject
public CommandMapper(@BaseCommands Set<CommandDescription> baseCommands, PermissionsManager permissionsManager) { public CommandMapper(CommandInitializer commandInitializer, PermissionsManager permissionsManager) {
this.baseCommands = baseCommands; this.baseCommands = commandInitializer.getCommands();
this.permissionsManager = permissionsManager; this.permissionsManager = permissionsManager;
} }

View File

@ -1,20 +1,16 @@
package fr.xephi.authme.command; package fr.xephi.authme.command;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.help.HelpProvider; import fr.xephi.authme.command.help.HelpProvider;
import fr.xephi.authme.hooks.PluginHooks;
import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.MessageKey;
import fr.xephi.authme.output.Messages; import fr.xephi.authme.output.Messages;
import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.process.Management;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.NewSetting; import fr.xephi.authme.settings.NewSetting;
import fr.xephi.authme.settings.SpawnLoader;
import fr.xephi.authme.settings.domain.Property; import fr.xephi.authme.settings.domain.Property;
import fr.xephi.authme.util.BukkitService; import fr.xephi.authme.util.BukkitService;
import fr.xephi.authme.util.ValidationService; import fr.xephi.authme.util.ValidationService;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import javax.inject.Inject; import javax.inject.Inject;
import java.util.Collection; import java.util.Collection;
@ -27,7 +23,7 @@ import java.util.List;
public class CommandService { public class CommandService {
@Inject @Inject
private AuthMe authMe; private BukkitScheduler scheduler;
@Inject @Inject
private Messages messages; private Messages messages;
@Inject @Inject
@ -36,16 +32,8 @@ public class CommandService {
private CommandMapper commandMapper; private CommandMapper commandMapper;
@SuppressWarnings("unused") @SuppressWarnings("unused")
@Inject @Inject
private PasswordSecurity passwordSecurity;
@Inject
private PermissionsManager permissionsManager;
@Inject
private NewSetting settings; private NewSetting settings;
@Inject @Inject
private PluginHooks pluginHooks;
@Inject
private SpawnLoader spawnLoader;
@Inject
private ValidationService validationService; private ValidationService validationService;
@Inject @Inject
private BukkitService bukkitService; private BukkitService bukkitService;
@ -86,19 +74,12 @@ public class CommandService {
* Run the given task asynchronously with the Bukkit scheduler. * Run the given task asynchronously with the Bukkit scheduler.
* *
* @param task The task to run * @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) { public BukkitTask runTaskAsynchronously(Runnable task) {
authMe.getServer().getScheduler().runTaskAsynchronously(authMe, task); return bukkitService.runTaskAsynchronously(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;
} }
/** /**
@ -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. * Retrieve a message by its message key.
* *
@ -163,13 +126,6 @@ public class CommandService {
return settings; return settings;
} }
public PluginHooks getPluginHooks() {
return pluginHooks;
}
public SpawnLoader getSpawnLoader() {
return spawnLoader;
}
/** /**
* Verifies whether a password is valid according to the plugin settings. * Verifies whether a password is valid according to the plugin settings.

View File

@ -13,15 +13,16 @@ import fr.xephi.authme.converter.xAuthConverter;
import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.MessageKey;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import javax.inject.Inject;
import java.util.List; import java.util.List;
public class ConverterCommand implements ExecutableCommand { public class ConverterCommand implements ExecutableCommand {
@Inject
private AuthMe authMe;
@Override @Override
public void executeCommand(CommandSender sender, List<String> arguments, CommandService commandService) { public void executeCommand(CommandSender sender, List<String> arguments, CommandService commandService) {
// AuthMe plugin instance
final AuthMe plugin = AuthMe.getInstance();
// Get the conversion job // Get the conversion job
String job = arguments.get(0); String job = arguments.get(0);
@ -36,22 +37,22 @@ public class ConverterCommand implements ExecutableCommand {
Converter converter = null; Converter converter = null;
switch (jobType) { switch (jobType) {
case XAUTH: case XAUTH:
converter = new xAuthConverter(plugin, sender); converter = new xAuthConverter(authMe, sender);
break; break;
case CRAZYLOGIN: case CRAZYLOGIN:
converter = new CrazyLoginConverter(plugin, sender); converter = new CrazyLoginConverter(authMe, sender);
break; break;
case RAKAMAK: case RAKAMAK:
converter = new RakamakConverter(plugin, sender); converter = new RakamakConverter(authMe, sender);
break; break;
case ROYALAUTH: case ROYALAUTH:
converter = new RoyalAuthConverter(plugin); converter = new RoyalAuthConverter(authMe);
break; break;
case VAUTH: case VAUTH:
converter = new vAuthConverter(plugin, sender); converter = new vAuthConverter(authMe, sender);
break; break;
case SQLITETOSQL: case SQLITETOSQL:
converter = new SqliteToSql(plugin, sender, commandService.getSettings()); converter = new SqliteToSql(authMe, sender, commandService.getSettings());
break; break;
default: default:
break; break;

View File

@ -2,8 +2,10 @@ package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.settings.SpawnLoader;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import javax.inject.Inject;
import java.util.List; import java.util.List;
/** /**
@ -11,10 +13,13 @@ import java.util.List;
*/ */
public class FirstSpawnCommand extends PlayerCommand { public class FirstSpawnCommand extends PlayerCommand {
@Inject
private SpawnLoader spawnLoader;
@Override @Override
public void runCommand(Player player, List<String> arguments, CommandService commandService) { public void runCommand(Player player, List<String> arguments, CommandService commandService) {
if (commandService.getSpawnLoader().getFirstSpawn() != null) { if (spawnLoader.getFirstSpawn() != null) {
player.teleport(commandService.getSpawnLoader().getFirstSpawn()); player.teleport(spawnLoader.getFirstSpawn());
} else { } else {
player.sendMessage("[AuthMe] First spawn has failed, please try to define the first spawn"); player.sendMessage("[AuthMe] First spawn has failed, please try to define the first spawn");
} }

View File

@ -2,9 +2,12 @@ package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.ExecutableCommand; 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.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import javax.inject.Inject;
import java.util.List; import java.util.List;
import static fr.xephi.authme.permission.PlayerPermission.CAN_LOGIN_BE_FORCED; 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 { public class ForceLoginCommand implements ExecutableCommand {
@Inject
private PermissionsManager permissionsManager;
@Inject
private Management management;
@Override @Override
public void executeCommand(CommandSender sender, List<String> arguments, CommandService commandService) { public void executeCommand(CommandSender sender, List<String> arguments, CommandService commandService) {
// Get the player query // Get the player query
@ -22,10 +31,10 @@ public class ForceLoginCommand implements ExecutableCommand {
Player player = commandService.getPlayer(playerName); Player player = commandService.getPlayer(playerName);
if (player == null || !player.isOnline()) { if (player == null || !player.isOnline()) {
sender.sendMessage("Player needs to be online!"); 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 + "!"); sender.sendMessage("You cannot force login the player " + playerName + "!");
} else { } else {
commandService.getManagement().performLogin(player, "dontneed", true); management.performLogin(player, "dontneed", true);
sender.sendMessage("Force login for " + playerName + " performed!"); sender.sendMessage("Force login for " + playerName + " performed!");
} }
} }

View File

@ -4,6 +4,7 @@ import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.hooks.PluginHooks;
import fr.xephi.authme.settings.properties.PurgeSettings; import fr.xephi.authme.settings.properties.PurgeSettings;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -21,11 +22,14 @@ public class PurgeBannedPlayersCommand implements ExecutableCommand {
@Inject @Inject
private DataSource dataSource; private DataSource dataSource;
@Inject
private PluginHooks pluginHooks;
@Inject
private AuthMe plugin;
@Override @Override
public void executeCommand(CommandSender sender, List<String> arguments, CommandService commandService) { public void executeCommand(CommandSender sender, List<String> arguments, CommandService commandService) {
// AuthMe plugin instance
final AuthMe plugin = commandService.getAuthMe();
// Get the list of banned players // Get the list of banned players
List<String> bannedPlayers = new ArrayList<>(); List<String> bannedPlayers = new ArrayList<>();
for (OfflinePlayer offlinePlayer : commandService.getBukkitService().getBannedPlayers()) { for (OfflinePlayer offlinePlayer : commandService.getBukkitService().getBannedPlayers()) {
@ -35,7 +39,7 @@ public class PurgeBannedPlayersCommand implements ExecutableCommand {
// Purge the banned players // Purge the banned players
dataSource.purgeBanned(bannedPlayers); dataSource.purgeBanned(bannedPlayers);
if (commandService.getProperty(PurgeSettings.REMOVE_ESSENTIALS_FILES) if (commandService.getProperty(PurgeSettings.REMOVE_ESSENTIALS_FILES)
&& commandService.getPluginHooks().isEssentialsAvailable()) && pluginHooks.isEssentialsAvailable())
plugin.dataManager.purgeEssentials(bannedPlayers); plugin.dataManager.purgeEssentials(bannedPlayers);
if (commandService.getProperty(PurgeSettings.REMOVE_PLAYER_DAT)) if (commandService.getProperty(PurgeSettings.REMOVE_PLAYER_DAT))
plugin.dataManager.purgeDat(bannedPlayers); plugin.dataManager.purgeDat(bannedPlayers);

View File

@ -4,6 +4,7 @@ import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.hooks.PluginHooks;
import fr.xephi.authme.settings.properties.PurgeSettings; import fr.xephi.authme.settings.properties.PurgeSettings;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -23,6 +24,12 @@ public class PurgeCommand implements ExecutableCommand {
@Inject @Inject
private DataSource dataSource; private DataSource dataSource;
@Inject
private PluginHooks pluginHooks;
@Inject
private AuthMe plugin;
@Override @Override
public void executeCommand(CommandSender sender, List<String> arguments, CommandService commandService) { public void executeCommand(CommandSender sender, List<String> arguments, CommandService commandService) {
// Get the days parameter // Get the days parameter
@ -56,9 +63,8 @@ public class PurgeCommand implements ExecutableCommand {
sender.sendMessage(ChatColor.GOLD + "Deleted " + purged.size() + " user accounts"); sender.sendMessage(ChatColor.GOLD + "Deleted " + purged.size() + " user accounts");
// Purge other data // Purge other data
AuthMe plugin = commandService.getAuthMe(); if (commandService.getProperty(PurgeSettings.REMOVE_ESSENTIALS_FILES)
if (commandService.getProperty(PurgeSettings.REMOVE_ESSENTIALS_FILES) && && pluginHooks.isEssentialsAvailable())
commandService.getPluginHooks().isEssentialsAvailable())
plugin.dataManager.purgeEssentials(purged); plugin.dataManager.purgeEssentials(purged);
if (commandService.getProperty(PurgeSettings.REMOVE_PLAYER_DAT)) if (commandService.getProperty(PurgeSettings.REMOVE_PLAYER_DAT))
plugin.dataManager.purgeDat(purged); plugin.dataManager.purgeDat(purged);

View File

@ -7,6 +7,7 @@ import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.MessageKey;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import javax.inject.Inject;
import java.util.List; import java.util.List;
/** /**
@ -14,9 +15,11 @@ import java.util.List;
*/ */
public class ReloadCommand implements ExecutableCommand { public class ReloadCommand implements ExecutableCommand {
@Inject
private AuthMe plugin;
@Override @Override
public void executeCommand(CommandSender sender, List<String> arguments, CommandService commandService) { public void executeCommand(CommandSender sender, List<String> arguments, CommandService commandService) {
AuthMe plugin = commandService.getAuthMe();
try { try {
plugin.reload(); plugin.reload();
commandService.send(sender, MessageKey.CONFIG_RELOAD_SUCCESS); commandService.send(sender, MessageKey.CONFIG_RELOAD_SUCCESS);

View File

@ -2,15 +2,20 @@ package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.settings.SpawnLoader;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import javax.inject.Inject;
import java.util.List; import java.util.List;
public class SetFirstSpawnCommand extends PlayerCommand { public class SetFirstSpawnCommand extends PlayerCommand {
@Inject
private SpawnLoader spawnLoader;
@Override @Override
public void runCommand(Player player, List<String> arguments, CommandService commandService) { public void runCommand(Player player, List<String> arguments, CommandService commandService) {
if (commandService.getSpawnLoader().setFirstSpawn(player.getLocation())) { if (spawnLoader.setFirstSpawn(player.getLocation())) {
player.sendMessage("[AuthMe] Correctly defined new first spawn point"); player.sendMessage("[AuthMe] Correctly defined new first spawn point");
} else { } else {
player.sendMessage("[AuthMe] SetFirstSpawn has failed, please retry"); player.sendMessage("[AuthMe] SetFirstSpawn has failed, please retry");

View File

@ -2,15 +2,20 @@ package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.settings.SpawnLoader;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import javax.inject.Inject;
import java.util.List; import java.util.List;
public class SetSpawnCommand extends PlayerCommand { public class SetSpawnCommand extends PlayerCommand {
@Inject
private SpawnLoader spawnLoader;
@Override @Override
public void runCommand(Player player, List<String> arguments, CommandService commandService) { public void runCommand(Player player, List<String> arguments, CommandService commandService) {
if (commandService.getSpawnLoader().setSpawn(player.getLocation())) { if (spawnLoader.setSpawn(player.getLocation())) {
player.sendMessage("[AuthMe] Correctly defined new spawn point"); player.sendMessage("[AuthMe] Correctly defined new spawn point");
} else { } else {
player.sendMessage("[AuthMe] SetSpawn has failed, please retry"); player.sendMessage("[AuthMe] SetSpawn has failed, please retry");

View File

@ -2,16 +2,21 @@ package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.settings.SpawnLoader;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import javax.inject.Inject;
import java.util.List; import java.util.List;
public class SpawnCommand extends PlayerCommand { public class SpawnCommand extends PlayerCommand {
@Inject
private SpawnLoader spawnLoader;
@Override @Override
public void runCommand(Player player, List<String> arguments, CommandService commandService) { public void runCommand(Player player, List<String> arguments, CommandService commandService) {
if (commandService.getSpawnLoader().getSpawn() != null) { if (spawnLoader.getSpawn() != null) {
player.teleport(commandService.getSpawnLoader().getSpawn()); player.teleport(spawnLoader.getSpawn());
} else { } else {
player.sendMessage("[AuthMe] Spawn has failed, please try to define the spawn"); player.sendMessage("[AuthMe] Spawn has failed, please try to define the spawn");
} }

View File

@ -36,6 +36,9 @@ public class UnregisterAdminCommand implements ExecutableCommand {
@Inject @Inject
private PlayerCache playerCache; private PlayerCache playerCache;
@Inject
private AuthMe authMe;
@Override @Override
public void executeCommand(final CommandSender sender, List<String> arguments, CommandService commandService) { public void executeCommand(final CommandSender sender, List<String> arguments, CommandService commandService) {
// Get the player name // Get the player name
@ -79,7 +82,6 @@ public class UnregisterAdminCommand implements ExecutableCommand {
* @param service the command service * @param service the command service
*/ */
private void applyUnregisteredEffectsAndTasks(Player target, CommandService service) { private void applyUnregisteredEffectsAndTasks(Player target, CommandService service) {
final AuthMe plugin = service.getAuthMe();
final BukkitService bukkitService = service.getBukkitService(); final BukkitService bukkitService = service.getBukkitService();
final String playerNameLowerCase = target.getName().toLowerCase(); 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 timeOut = service.getProperty(RestrictionSettings.TIMEOUT) * TICKS_PER_SECOND;
int interval = service.getProperty(RegistrationSettings.MESSAGE_INTERVAL); int interval = service.getProperty(RegistrationSettings.MESSAGE_INTERVAL);
if (timeOut != 0) { 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).setTimeoutTask(id);
} }
LimboCache.getInstance().getLimboPlayer(playerNameLowerCase).setMessageTask( 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))); playerNameLowerCase, MessageKey.REGISTER_MESSAGE, interval)));
if (service.getProperty(RegistrationSettings.APPLY_BLIND_EFFECT)) { if (service.getProperty(RegistrationSettings.APPLY_BLIND_EFFECT)) {

View File

@ -9,16 +9,21 @@ import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.settings.properties.SecuritySettings;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import javax.inject.Inject;
import java.util.List; import java.util.List;
public class CaptchaCommand extends PlayerCommand { public class CaptchaCommand extends PlayerCommand {
@Inject
private AuthMe plugin;
@Inject
private PlayerCache playerCache;
@Override @Override
public void runCommand(Player player, List<String> arguments, CommandService commandService) { public void runCommand(Player player, List<String> arguments, CommandService commandService) {
final String playerNameLowerCase = player.getName().toLowerCase(); final String playerNameLowerCase = player.getName().toLowerCase();
final String captcha = arguments.get(0); final String captcha = arguments.get(0);
final AuthMe plugin = commandService.getAuthMe();
PlayerCache playerCache = PlayerCache.getInstance();
// Command logic // Command logic
if (playerCache.isAuthenticated(playerNameLowerCase)) { if (playerCache.isAuthenticated(playerNameLowerCase)) {

View File

@ -3,8 +3,10 @@ package fr.xephi.authme.command.executable.email;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.MessageKey;
import fr.xephi.authme.process.Management;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import javax.inject.Inject;
import java.util.List; import java.util.List;
/** /**
@ -12,6 +14,9 @@ import java.util.List;
*/ */
public class AddEmailCommand extends PlayerCommand { public class AddEmailCommand extends PlayerCommand {
@Inject
private Management management;
@Override @Override
public void runCommand(Player player, List<String> arguments, CommandService commandService) { public void runCommand(Player player, List<String> arguments, CommandService commandService) {
String email = arguments.get(0); String email = arguments.get(0);
@ -19,7 +24,7 @@ public class AddEmailCommand extends PlayerCommand {
if (email.equals(emailConfirmation)) { if (email.equals(emailConfirmation)) {
// Closer inspection of the mail address handled by the async task // Closer inspection of the mail address handled by the async task
commandService.getManagement().performAddEmail(player, email); management.performAddEmail(player, email);
} else { } else {
commandService.send(player, MessageKey.CONFIRM_EMAIL_MESSAGE); commandService.send(player, MessageKey.CONFIRM_EMAIL_MESSAGE);
} }

View File

@ -2,8 +2,10 @@ package fr.xephi.authme.command.executable.email;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.process.Management;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import javax.inject.Inject;
import java.util.List; import java.util.List;
/** /**
@ -11,11 +13,14 @@ import java.util.List;
*/ */
public class ChangeEmailCommand extends PlayerCommand { public class ChangeEmailCommand extends PlayerCommand {
@Inject
private Management management;
@Override @Override
public void runCommand(Player player, List<String> arguments, CommandService commandService) { public void runCommand(Player player, List<String> arguments, CommandService commandService) {
String playerMailOld = arguments.get(0); String playerMailOld = arguments.get(0);
String playerMailNew = arguments.get(1); String playerMailNew = arguments.get(1);
commandService.getManagement().performChangeEmail(player, playerMailOld, playerMailNew); management.performChangeEmail(player, playerMailOld, playerMailNew);
} }
} }

View File

@ -29,11 +29,13 @@ public class RecoverEmailCommand extends PlayerCommand {
@Inject @Inject
private PlayerCache playerCache; private PlayerCache playerCache;
@Inject
private AuthMe plugin;
@Override @Override
public void runCommand(Player player, List<String> arguments, CommandService commandService) { public void runCommand(Player player, List<String> arguments, CommandService commandService) {
final String playerMail = arguments.get(0); final String playerMail = arguments.get(0);
final String playerName = player.getName(); final String playerName = player.getName();
final AuthMe plugin = commandService.getAuthMe();
if (plugin.mail == null) { if (plugin.mail == null) {
ConsoleLogger.showError("Mail API is not set"); ConsoleLogger.showError("Mail API is not set");

View File

@ -2,8 +2,10 @@ package fr.xephi.authme.command.executable.login;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.process.Management;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import javax.inject.Inject;
import java.util.List; import java.util.List;
/** /**
@ -11,9 +13,12 @@ import java.util.List;
*/ */
public class LoginCommand extends PlayerCommand { public class LoginCommand extends PlayerCommand {
@Inject
private Management management;
@Override @Override
public void runCommand(Player player, List<String> arguments, CommandService commandService) { public void runCommand(Player player, List<String> arguments, CommandService commandService) {
final String password = arguments.get(0); final String password = arguments.get(0);
commandService.getManagement().performLogin(player, password, false); management.performLogin(player, password, false);
} }
} }

View File

@ -2,8 +2,10 @@ package fr.xephi.authme.command.executable.logout;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.process.Management;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import javax.inject.Inject;
import java.util.List; import java.util.List;
/** /**
@ -11,8 +13,11 @@ import java.util.List;
*/ */
public class LogoutCommand extends PlayerCommand { public class LogoutCommand extends PlayerCommand {
@Inject
private Management management;
@Override @Override
public void runCommand(Player player, List<String> arguments, CommandService commandService) { public void runCommand(Player player, List<String> arguments, CommandService commandService) {
commandService.getManagement().performLogout(player); management.performLogout(player);
} }
} }

View File

@ -4,12 +4,14 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.MessageKey;
import fr.xephi.authme.process.Management;
import fr.xephi.authme.security.HashAlgorithm; import fr.xephi.authme.security.HashAlgorithm;
import fr.xephi.authme.security.RandomString; import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.settings.properties.EmailSettings; import fr.xephi.authme.settings.properties.EmailSettings;
import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.settings.properties.SecuritySettings;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import javax.inject.Inject;
import java.util.List; import java.util.List;
import static fr.xephi.authme.settings.properties.EmailSettings.RECOVERY_PASSWORD_LENGTH; 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 { public class RegisterCommand extends PlayerCommand {
@Inject
private Management management;
@Override @Override
public void runCommand(Player player, List<String> arguments, CommandService commandService) { public void runCommand(Player player, List<String> arguments, CommandService commandService) {
if (commandService.getProperty(SecuritySettings.PASSWORD_HASH) == HashAlgorithm.TWO_FACTOR) { if (commandService.getProperty(SecuritySettings.PASSWORD_HASH) == HashAlgorithm.TWO_FACTOR) {
//for two factor auth we don't need to check the usage //for two factor auth we don't need to check the usage
commandService.getManagement().performRegister(player, "", "", true); management.performRegister(player, "", "", true);
return; return;
} }
@ -50,7 +55,7 @@ public class RegisterCommand extends PlayerCommand {
if (commandService.getProperty(ENABLE_PASSWORD_CONFIRMATION) && !arguments.get(0).equals(arguments.get(1))) { if (commandService.getProperty(ENABLE_PASSWORD_CONFIRMATION) && !arguments.get(0).equals(arguments.get(1))) {
commandService.send(player, MessageKey.PASSWORD_MATCH_ERROR); commandService.send(player, MessageKey.PASSWORD_MATCH_ERROR);
} else { } 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); commandService.send(player, MessageKey.USAGE_REGISTER);
} else { } else {
String thePass = RandomString.generate(commandService.getProperty(RECOVERY_PASSWORD_LENGTH)); String thePass = RandomString.generate(commandService.getProperty(RECOVERY_PASSWORD_LENGTH));
commandService.getManagement().performRegister(player, thePass, email, true); management.performRegister(player, thePass, email, true);
} }
} }

View File

@ -4,12 +4,17 @@ import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.MessageKey;
import fr.xephi.authme.process.Management;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import javax.inject.Inject;
import java.util.List; import java.util.List;
public class UnregisterCommand extends PlayerCommand { public class UnregisterCommand extends PlayerCommand {
@Inject
private Management management;
@Override @Override
public void runCommand(Player player, List<String> arguments, CommandService commandService) { public void runCommand(Player player, List<String> arguments, CommandService commandService) {
String playerPass = arguments.get(0); String playerPass = arguments.get(0);
@ -22,6 +27,6 @@ public class UnregisterCommand extends PlayerCommand {
} }
// Unregister the player // Unregister the player
commandService.getManagement().performUnregister(player, playerPass, false); management.performUnregister(player, playerPass, false);
} }
} }

View File

@ -132,7 +132,8 @@ public class AuthMeServiceInitializer {
* @return the instantiated object * @return the instantiated object
*/ */
private <T> T instantiate(Class<T> clazz, Set<Class<?>> traversedClasses) { private <T> T instantiate(Class<T> clazz, Set<Class<?>> traversedClasses) {
Injection<T> injection = firstNotNull(ConstructorInjection.provide(clazz), FieldInjection.provide(clazz)); Injection<T> injection = firstNotNull(
ConstructorInjection.provide(clazz), FieldInjection.provide(clazz), InstantiationFallback.provide(clazz));
if (injection == null) { if (injection == null) {
throw new IllegalStateException("Did not find injection method for " + clazz + ". Make sure you have " 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 " + "a constructor with @Inject or fields with @Inject. Fields with @Inject require "

View File

@ -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 {
}

View File

@ -74,7 +74,7 @@ class FieldInjection<T> implements Injection<T> {
* *
* @param clazz the class to provide field injection for * @param clazz the class to provide field injection for
* @param <T> the class' type * @param <T> 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 <T> Provider<FieldInjection<T>> provide(final Class<T> clazz) { public static <T> Provider<FieldInjection<T>> provide(final Class<T> clazz) {
return new Provider<FieldInjection<T>>() { return new Provider<FieldInjection<T>>() {
@ -85,7 +85,7 @@ class FieldInjection<T> implements Injection<T> {
return null; return null;
} }
List<Field> fields = getInjectionFields(clazz); List<Field> fields = getInjectionFields(clazz);
return fields == null ? null : new FieldInjection<>(constructor, fields); return fields.isEmpty() ? null : new FieldInjection<>(constructor, fields);
} }
}; };
} }

View File

@ -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<T> implements Injection<T> {
private final Constructor<T> constructor;
private InstantiationFallback(Constructor<T> 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 <T> the class' type
* @return instantiation fallback provider for the given class, or null if not applicable
*/
public static <T> Provider<InstantiationFallback<T>> provide(final Class<T> clazz) {
return new Provider<InstantiationFallback<T>>() {
@Override
public InstantiationFallback<T> get() {
Constructor<T> 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 <T> Constructor<T> getNoArgsConstructor(Class<T> clazz) {
try {
// Note ljacqu 20160504: getConstructor(), unlike getDeclaredConstructor(), only considers public members
return clazz.getConstructor();
} catch (NoSuchMethodException e) {
return null;
}
}
private static <A extends AccessibleObject> boolean isInjectAnnotationPresent(A[] accessibles) {
for (A accessible : accessibles) {
if (accessible.isAnnotationPresent(Inject.class)) {
return true;
}
}
return false;
}
}

View File

@ -1,12 +1,11 @@
package fr.xephi.authme.listener; package fr.xephi.authme.listener;
import fr.xephi.authme.settings.SpawnLoader;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.spigotmc.event.player.PlayerSpawnLocationEvent; import org.spigotmc.event.player.PlayerSpawnLocationEvent;
import fr.xephi.authme.AuthMe;
import javax.inject.Inject; import javax.inject.Inject;
/** /**
@ -15,13 +14,13 @@ import javax.inject.Inject;
public class AuthMePlayerListener19 implements Listener { public class AuthMePlayerListener19 implements Listener {
@Inject @Inject
private AuthMe plugin; private SpawnLoader spawnLoader;
public AuthMePlayerListener19() { } AuthMePlayerListener19() { }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onPlayerSpawn(PlayerSpawnLocationEvent event) { public void onPlayerSpawn(PlayerSpawnLocationEvent event) {
event.setSpawnLocation(plugin.getSpawnLocation(event.getPlayer())); event.setSpawnLocation(spawnLoader.getSpawnLocation(event.getPlayer()));
} }
} }

View File

@ -5,6 +5,7 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.hooks.PluginHooks; import fr.xephi.authme.hooks.PluginHooks;
import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.MessageKey;
import fr.xephi.authme.output.Messages; import fr.xephi.authme.output.Messages;
import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.settings.NewSetting; import fr.xephi.authme.settings.NewSetting;
import fr.xephi.authme.settings.SpawnLoader; import fr.xephi.authme.settings.SpawnLoader;
import fr.xephi.authme.settings.properties.ProtectionSettings; import fr.xephi.authme.settings.properties.ProtectionSettings;
@ -34,6 +35,8 @@ public class AuthMeServerListener implements Listener {
private SpawnLoader spawnLoader; private SpawnLoader spawnLoader;
@Inject @Inject
private ValidationService validationService; private ValidationService validationService;
@Inject
private PermissionsManager permissionsManager;
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onServerPing(ServerListPingEvent event) { public void onServerPing(ServerListPingEvent event) {
@ -53,7 +56,7 @@ public class AuthMeServerListener implements Listener {
} }
// Call the onPluginDisable method in the permissions manager // Call the onPluginDisable method in the permissions manager
plugin.getPermissionsManager().onPluginDisable(event); permissionsManager.onPluginDisable(event);
final String pluginName = event.getPlugin().getName(); final String pluginName = event.getPlugin().getName();
if ("Essentials".equalsIgnoreCase(pluginName)) { if ("Essentials".equalsIgnoreCase(pluginName)) {
@ -86,7 +89,7 @@ public class AuthMeServerListener implements Listener {
} }
// Call the onPluginEnable method in the permissions manager // Call the onPluginEnable method in the permissions manager
plugin.getPermissionsManager().onPluginEnable(event); permissionsManager.onPluginEnable(event);
final String pluginName = event.getPlugin().getName(); final String pluginName = event.getPlugin().getName();
if ("Essentials".equalsIgnoreCase(pluginName)) { if ("Essentials".equalsIgnoreCase(pluginName)) {

View File

@ -2,11 +2,13 @@ package fr.xephi.authme.command;
import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PermissionsManager;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Captor; 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.Collections;
import java.util.List; import java.util.List;
@ -35,23 +37,24 @@ import static org.mockito.Mockito.verify;
/** /**
* Test for {@link CommandHandler}. * 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 // 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"), ...) // often consists of only one element, e.g. myMethod(asList("authme"), asList("my", "args"), ...)
@SuppressWarnings("ArraysAsListWithZeroOrOneArgument")
@RunWith(MockitoJUnitRunner.class)
public class CommandHandlerTest { public class CommandHandlerTest {
@InjectMocks
private CommandHandler handler; private CommandHandler handler;
@Mock
private CommandService serviceMock; private CommandService serviceMock;
@Mock
private PermissionsManager permissionsManager;
@Captor @Captor
private ArgumentCaptor<List<String>> captor; private ArgumentCaptor<List<String>> captor;
@Before
public void setUpCommandHandler() {
MockitoAnnotations.initMocks(this);
serviceMock = mock(CommandService.class);
handler = new CommandHandler(serviceMock);
}
@Test @Test
public void shouldCallMappedCommandWithArgs() { public void shouldCallMappedCommandWithArgs() {
@ -109,9 +112,7 @@ public class CommandHandlerTest {
CommandDescription command = mock(CommandDescription.class); CommandDescription command = mock(CommandDescription.class);
given(serviceMock.mapPartsToCommand(any(CommandSender.class), anyListOf(String.class))).willReturn( given(serviceMock.mapPartsToCommand(any(CommandSender.class), anyListOf(String.class))).willReturn(
new FoundCommandResult(command, asList("unreg"), asList("testPlayer"), 0.0, INCORRECT_ARGUMENTS)); new FoundCommandResult(command, asList("unreg"), asList("testPlayer"), 0.0, INCORRECT_ARGUMENTS));
PermissionsManager permissionsManager = mock(PermissionsManager.class);
given(permissionsManager.hasPermission(sender, command)).willReturn(true); given(permissionsManager.hasPermission(sender, command)).willReturn(true);
given(serviceMock.getPermissionsManager()).willReturn(permissionsManager);
// when // when
handler.processCommand(sender, bukkitLabel, bukkitArgs); handler.processCommand(sender, bukkitLabel, bukkitArgs);
@ -135,9 +136,7 @@ public class CommandHandlerTest {
CommandDescription command = mock(CommandDescription.class); CommandDescription command = mock(CommandDescription.class);
given(serviceMock.mapPartsToCommand(any(CommandSender.class), anyListOf(String.class))).willReturn( given(serviceMock.mapPartsToCommand(any(CommandSender.class), anyListOf(String.class))).willReturn(
new FoundCommandResult(command, asList("unreg"), asList("testPlayer"), 0.0, INCORRECT_ARGUMENTS)); new FoundCommandResult(command, asList("unreg"), asList("testPlayer"), 0.0, INCORRECT_ARGUMENTS));
PermissionsManager permissionsManager = mock(PermissionsManager.class);
given(permissionsManager.hasPermission(sender, command)).willReturn(false); given(permissionsManager.hasPermission(sender, command)).willReturn(false);
given(serviceMock.getPermissionsManager()).willReturn(permissionsManager);
// when // when
handler.processCommand(sender, bukkitLabel, bukkitArgs); handler.processCommand(sender, bukkitLabel, bukkitArgs);

View File

@ -43,7 +43,7 @@ public class CommandInitializerTest {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@BeforeClass @BeforeClass
public static void initializeCommandManager() { public static void initializeCommandCollection() {
AuthMeServiceInitializer initializer = mock(AuthMeServiceInitializer.class); AuthMeServiceInitializer initializer = mock(AuthMeServiceInitializer.class);
when(initializer.newInstance(any(Class.class))).thenAnswer(new Answer<Object>() { when(initializer.newInstance(any(Class.class))).thenAnswer(new Answer<Object>() {
@Override @Override
@ -52,8 +52,8 @@ public class CommandInitializerTest {
return mock(clazz); return mock(clazz);
} }
}); });
CommandInitializer commandInitializer = new CommandInitializer(initializer);
commands = CommandInitializer.buildCommands(initializer); commands = commandInitializer.getCommands();
} }
@Test @Test

View File

@ -41,7 +41,9 @@ public class CommandMapperTest {
@Before @Before
public void setUpMocks() { public void setUpMocks() {
permissionsManager = mock(PermissionsManager.class); permissionsManager = mock(PermissionsManager.class);
mapper = new CommandMapper(commands, permissionsManager); CommandInitializer initializer = mock(CommandInitializer.class);
given(initializer.getCommands()).willReturn(commands);
mapper = new CommandMapper(initializer, permissionsManager);
} }
// ----------- // -----------

View File

@ -1,15 +1,9 @@
package fr.xephi.authme.command; package fr.xephi.authme.command;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.help.HelpProvider; import fr.xephi.authme.command.help.HelpProvider;
import fr.xephi.authme.hooks.PluginHooks;
import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.MessageKey;
import fr.xephi.authme.output.Messages; import fr.xephi.authme.output.Messages;
import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.process.Management;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.NewSetting; import fr.xephi.authme.settings.NewSetting;
import fr.xephi.authme.settings.SpawnLoader;
import fr.xephi.authme.settings.domain.Property; import fr.xephi.authme.settings.domain.Property;
import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.settings.properties.SecuritySettings;
import fr.xephi.authme.util.BukkitService; import fr.xephi.authme.util.BukkitService;
@ -42,24 +36,14 @@ public class CommandServiceTest {
@InjectMocks @InjectMocks
private CommandService commandService; private CommandService commandService;
@Mock @Mock
private AuthMe authMe;
@Mock
private CommandMapper commandMapper; private CommandMapper commandMapper;
@Mock @Mock
private HelpProvider helpProvider; private HelpProvider helpProvider;
@Mock @Mock
private Messages messages; private Messages messages;
@Mock @Mock
private PasswordSecurity passwordSecurity;
@Mock
private PermissionsManager permissionsManager;
@Mock
private NewSetting settings; private NewSetting settings;
@Mock @Mock
private PluginHooks pluginHooks;
@Mock
private SpawnLoader spawnLoader;
@Mock
private ValidationService validationService; private ValidationService validationService;
@Mock @Mock
private BukkitService bukkitService; private BukkitService bukkitService;
@ -122,29 +106,6 @@ public class CommandServiceTest {
assertThat(captor.getAllValues(), equalTo(messages)); 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 @Test
public void shouldRetrieveMessage() { public void shouldRetrieveMessage() {
// given // given
@ -183,15 +144,6 @@ public class CommandServiceTest {
assertThat(result, equalTo(settings)); assertThat(result, equalTo(settings));
} }
@Test
public void shouldReturnAuthMe() {
// given/when
AuthMe result = commandService.getAuthMe();
// then
assertThat(result, equalTo(authMe));
}
@Test @Test
public void shouldValidatePassword() { public void shouldValidatePassword() {
// given // given

View File

@ -1,11 +1,14 @@
package fr.xephi.authme.command.executable.authme; package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.SpawnLoader; import fr.xephi.authme.settings.SpawnLoader;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.junit.Test; 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 java.util.Collections;
@ -21,18 +24,24 @@ import static org.mockito.Mockito.verify;
/** /**
* Test for {@link FirstSpawnCommand}. * Test for {@link FirstSpawnCommand}.
*/ */
@RunWith(MockitoJUnitRunner.class)
public class FirstSpawnCommandTest { public class FirstSpawnCommandTest {
@InjectMocks
private FirstSpawnCommand command;
@Mock
private SpawnLoader spawnLoader;
@Mock
private CommandService service;
@Test @Test
public void shouldTeleportToFirstSpawn() { public void shouldTeleportToFirstSpawn() {
// given // given
Location firstSpawn = mock(Location.class); Location firstSpawn = mock(Location.class);
SpawnLoader spawnLoader = mock(SpawnLoader.class);
given(spawnLoader.getFirstSpawn()).willReturn(firstSpawn); given(spawnLoader.getFirstSpawn()).willReturn(firstSpawn);
CommandService service = mock(CommandService.class);
given(service.getSpawnLoader()).willReturn(spawnLoader);
Player player = mock(Player.class); Player player = mock(Player.class);
ExecutableCommand command = new FirstSpawnCommand();
// when // when
command.executeCommand(player, Collections.<String>emptyList(), service); command.executeCommand(player, Collections.<String>emptyList(), service);
@ -45,12 +54,8 @@ public class FirstSpawnCommandTest {
@Test @Test
public void shouldHandleMissingFirstSpawn() { public void shouldHandleMissingFirstSpawn() {
// given // given
SpawnLoader spawnLoader = mock(SpawnLoader.class);
given(spawnLoader.getFirstSpawn()).willReturn(null); given(spawnLoader.getFirstSpawn()).willReturn(null);
CommandService service = mock(CommandService.class);
given(service.getSpawnLoader()).willReturn(spawnLoader);
Player player = mock(Player.class); Player player = mock(Player.class);
ExecutableCommand command = new FirstSpawnCommand();
// when // when
command.executeCommand(player, Collections.<String>emptyList(), service); command.executeCommand(player, Collections.<String>emptyList(), service);

View File

@ -9,6 +9,7 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner; 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.argThat;
import static org.mockito.Matchers.eq; import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
/** /**
* Test for {@link ForceLoginCommand}. * Test for {@link ForceLoginCommand}.
@ -30,6 +31,15 @@ import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class ForceLoginCommandTest { public class ForceLoginCommandTest {
@InjectMocks
private ForceLoginCommand command;
@Mock
private Management management;
@Mock
private PermissionsManager permissionsManager;
@Mock @Mock
private CommandService commandService; private CommandService commandService;
@ -40,7 +50,6 @@ public class ForceLoginCommandTest {
Player player = mockPlayer(false, playerName); Player player = mockPlayer(false, playerName);
given(commandService.getPlayer(playerName)).willReturn(player); given(commandService.getPlayer(playerName)).willReturn(player);
CommandSender sender = mock(CommandSender.class); CommandSender sender = mock(CommandSender.class);
ExecutableCommand command = new ForceLoginCommand();
// when // when
command.executeCommand(sender, Collections.singletonList(playerName), commandService); command.executeCommand(sender, Collections.singletonList(playerName), commandService);
@ -48,7 +57,7 @@ public class ForceLoginCommandTest {
// then // then
verify(commandService).getPlayer(playerName); verify(commandService).getPlayer(playerName);
verify(sender).sendMessage(argThat(equalTo("Player needs to be online!"))); verify(sender).sendMessage(argThat(equalTo("Player needs to be online!")));
verify(commandService, never()).getManagement(); verifyZeroInteractions(management);
} }
@Test @Test
@ -65,7 +74,7 @@ public class ForceLoginCommandTest {
// then // then
verify(commandService).getPlayer(playerName); verify(commandService).getPlayer(playerName);
verify(sender).sendMessage(argThat(equalTo("Player needs to be online!"))); verify(sender).sendMessage(argThat(equalTo("Player needs to be online!")));
verify(commandService, never()).getManagement(); verifyZeroInteractions(management);
} }
@Test @Test
@ -74,12 +83,8 @@ public class ForceLoginCommandTest {
String playerName = "testTest"; String playerName = "testTest";
Player player = mockPlayer(true, playerName); Player player = mockPlayer(true, playerName);
given(commandService.getPlayer(playerName)).willReturn(player); given(commandService.getPlayer(playerName)).willReturn(player);
PermissionsManager permissionsManager = mock(PermissionsManager.class);
given(permissionsManager.hasPermission(player, PlayerPermission.CAN_LOGIN_BE_FORCED)).willReturn(false); given(permissionsManager.hasPermission(player, PlayerPermission.CAN_LOGIN_BE_FORCED)).willReturn(false);
given(commandService.getPermissionsManager()).willReturn(permissionsManager);
CommandSender sender = mock(CommandSender.class); CommandSender sender = mock(CommandSender.class);
ExecutableCommand command = new ForceLoginCommand();
// when // when
command.executeCommand(sender, Collections.singletonList(playerName), commandService); command.executeCommand(sender, Collections.singletonList(playerName), commandService);
@ -87,7 +92,7 @@ public class ForceLoginCommandTest {
// then // then
verify(commandService).getPlayer(playerName); verify(commandService).getPlayer(playerName);
verify(sender).sendMessage(argThat(containsString("You cannot force login the player"))); verify(sender).sendMessage(argThat(containsString("You cannot force login the player")));
verify(commandService, never()).getManagement(); verifyZeroInteractions(management);
} }
@Test @Test
@ -96,14 +101,8 @@ public class ForceLoginCommandTest {
String playerName = "tester23"; String playerName = "tester23";
Player player = mockPlayer(true, playerName); Player player = mockPlayer(true, playerName);
given(commandService.getPlayer(playerName)).willReturn(player); given(commandService.getPlayer(playerName)).willReturn(player);
PermissionsManager permissionsManager = mock(PermissionsManager.class);
given(permissionsManager.hasPermission(player, PlayerPermission.CAN_LOGIN_BE_FORCED)).willReturn(true); 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); CommandSender sender = mock(CommandSender.class);
ExecutableCommand command = new ForceLoginCommand();
// when // when
command.executeCommand(sender, Collections.singletonList(playerName), commandService); command.executeCommand(sender, Collections.singletonList(playerName), commandService);
@ -119,15 +118,9 @@ public class ForceLoginCommandTest {
String senderName = "tester23"; String senderName = "tester23";
Player player = mockPlayer(true, senderName); Player player = mockPlayer(true, senderName);
given(commandService.getPlayer(senderName)).willReturn(player); given(commandService.getPlayer(senderName)).willReturn(player);
PermissionsManager permissionsManager = mock(PermissionsManager.class);
given(permissionsManager.hasPermission(player, PlayerPermission.CAN_LOGIN_BE_FORCED)).willReturn(true); 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); CommandSender sender = mock(CommandSender.class);
given(sender.getName()).willReturn(senderName); given(sender.getName()).willReturn(senderName);
ExecutableCommand command = new ForceLoginCommand();
// when // when
command.executeCommand(sender, Collections.<String>emptyList(), commandService); command.executeCommand(sender, Collections.<String>emptyList(), commandService);

View File

@ -3,15 +3,17 @@ package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.TestHelper; import fr.xephi.authme.TestHelper;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.MessageKey;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; 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 java.util.Collections;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.matches; import static org.mockito.Matchers.matches;
import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -20,8 +22,18 @@ import static org.mockito.Mockito.verify;
/** /**
* Test for {@link ReloadCommand}. * Test for {@link ReloadCommand}.
*/ */
@RunWith(MockitoJUnitRunner.class)
public class ReloadCommandTest { public class ReloadCommandTest {
@InjectMocks
private ReloadCommand command;
@Mock
private AuthMe authMe;
@Mock
private CommandService service;
@BeforeClass @BeforeClass
public static void setUpLogger() { public static void setUpLogger() {
TestHelper.setupLogger(); TestHelper.setupLogger();
@ -30,11 +42,7 @@ public class ReloadCommandTest {
@Test @Test
public void shouldReload() throws Exception { public void shouldReload() throws Exception {
// given // given
AuthMe authMe = mock(AuthMe.class);
CommandService service = mock(CommandService.class);
given(service.getAuthMe()).willReturn(authMe);
CommandSender sender = mock(CommandSender.class); CommandSender sender = mock(CommandSender.class);
ExecutableCommand command = new ReloadCommand();
// when // when
command.executeCommand(sender, Collections.<String>emptyList(), service); command.executeCommand(sender, Collections.<String>emptyList(), service);
@ -47,12 +55,8 @@ public class ReloadCommandTest {
@Test @Test
public void shouldHandleReloadError() throws Exception { public void shouldHandleReloadError() throws Exception {
// given // given
AuthMe authMe = mock(AuthMe.class);
doThrow(IllegalStateException.class).when(authMe).reload(); doThrow(IllegalStateException.class).when(authMe).reload();
CommandService service = mock(CommandService.class);
given(service.getAuthMe()).willReturn(authMe);
CommandSender sender = mock(CommandSender.class); CommandSender sender = mock(CommandSender.class);
ExecutableCommand command = new ReloadCommand();
// when // when
command.executeCommand(sender, Collections.<String>emptyList(), service); command.executeCommand(sender, Collections.<String>emptyList(), service);

View File

@ -1,11 +1,14 @@
package fr.xephi.authme.command.executable.authme; package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.SpawnLoader; import fr.xephi.authme.settings.SpawnLoader;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.junit.Test; 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 java.util.Collections;
@ -18,21 +21,25 @@ import static org.mockito.Mockito.verify;
/** /**
* Test for {@link SetFirstSpawnCommand}. * Test for {@link SetFirstSpawnCommand}.
*/ */
@RunWith(MockitoJUnitRunner.class)
public class SetFirstSpawnCommandTest { public class SetFirstSpawnCommandTest {
@InjectMocks
private SetFirstSpawnCommand command;
@Mock
private SpawnLoader spawnLoader;
@Mock
private CommandService service;
@Test @Test
public void shouldSetFirstSpawn() { public void shouldSetFirstSpawn() {
// given // given
Player player = mock(Player.class); Player player = mock(Player.class);
Location location = mock(Location.class); Location location = mock(Location.class);
given(player.getLocation()).willReturn(location); given(player.getLocation()).willReturn(location);
SpawnLoader spawnLoader = mock(SpawnLoader.class);
given(spawnLoader.setFirstSpawn(location)).willReturn(true); given(spawnLoader.setFirstSpawn(location)).willReturn(true);
CommandService service = mock(CommandService.class);
given(service.getSpawnLoader()).willReturn(spawnLoader);
ExecutableCommand command = new SetFirstSpawnCommand();
// when // when
command.executeCommand(player, Collections.<String>emptyList(), service); command.executeCommand(player, Collections.<String>emptyList(), service);
@ -48,13 +55,7 @@ public class SetFirstSpawnCommandTest {
Player player = mock(Player.class); Player player = mock(Player.class);
Location location = mock(Location.class); Location location = mock(Location.class);
given(player.getLocation()).willReturn(location); given(player.getLocation()).willReturn(location);
SpawnLoader spawnLoader = mock(SpawnLoader.class);
given(spawnLoader.setFirstSpawn(location)).willReturn(false); given(spawnLoader.setFirstSpawn(location)).willReturn(false);
CommandService service = mock(CommandService.class);
given(service.getSpawnLoader()).willReturn(spawnLoader);
ExecutableCommand command = new SetFirstSpawnCommand();
// when // when
command.executeCommand(player, Collections.<String>emptyList(), service); command.executeCommand(player, Collections.<String>emptyList(), service);

View File

@ -1,11 +1,14 @@
package fr.xephi.authme.command.executable.authme; package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.SpawnLoader; import fr.xephi.authme.settings.SpawnLoader;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.junit.Test; 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 java.util.Collections;
@ -18,21 +21,25 @@ import static org.mockito.Mockito.verify;
/** /**
* Test for {@link SetSpawnCommand}. * Test for {@link SetSpawnCommand}.
*/ */
@RunWith(MockitoJUnitRunner.class)
public class SetSpawnCommandTest { public class SetSpawnCommandTest {
@InjectMocks
private SetSpawnCommand command;
@Mock
private SpawnLoader spawnLoader;
@Mock
private CommandService service;
@Test @Test
public void shouldSetSpawn() { public void shouldSetSpawn() {
// given // given
Player player = mock(Player.class); Player player = mock(Player.class);
Location location = mock(Location.class); Location location = mock(Location.class);
given(player.getLocation()).willReturn(location); given(player.getLocation()).willReturn(location);
SpawnLoader spawnLoader = mock(SpawnLoader.class);
given(spawnLoader.setSpawn(location)).willReturn(true); given(spawnLoader.setSpawn(location)).willReturn(true);
CommandService service = mock(CommandService.class);
given(service.getSpawnLoader()).willReturn(spawnLoader);
ExecutableCommand command = new SetSpawnCommand();
// when // when
command.executeCommand(player, Collections.<String>emptyList(), service); command.executeCommand(player, Collections.<String>emptyList(), service);
@ -48,13 +55,7 @@ public class SetSpawnCommandTest {
Player player = mock(Player.class); Player player = mock(Player.class);
Location location = mock(Location.class); Location location = mock(Location.class);
given(player.getLocation()).willReturn(location); given(player.getLocation()).willReturn(location);
SpawnLoader spawnLoader = mock(SpawnLoader.class);
given(spawnLoader.setSpawn(location)).willReturn(false); given(spawnLoader.setSpawn(location)).willReturn(false);
CommandService service = mock(CommandService.class);
given(service.getSpawnLoader()).willReturn(spawnLoader);
ExecutableCommand command = new SetSpawnCommand();
// when // when
command.executeCommand(player, Collections.<String>emptyList(), service); command.executeCommand(player, Collections.<String>emptyList(), service);

View File

@ -1,11 +1,14 @@
package fr.xephi.authme.command.executable.authme; package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.SpawnLoader; import fr.xephi.authme.settings.SpawnLoader;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.junit.Test; 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 java.util.Collections;
@ -21,18 +24,24 @@ import static org.mockito.Mockito.verify;
/** /**
* Test for {@link SpawnCommand}. * Test for {@link SpawnCommand}.
*/ */
@RunWith(MockitoJUnitRunner.class)
public class SpawnCommandTest { public class SpawnCommandTest {
@InjectMocks
private SpawnCommand command;
@Mock
private SpawnLoader spawnLoader;
@Mock
private CommandService service;
@Test @Test
public void shouldTeleportToSpawn() { public void shouldTeleportToSpawn() {
// given // given
Location spawn = mock(Location.class); Location spawn = mock(Location.class);
SpawnLoader spawnLoader = mock(SpawnLoader.class);
given(spawnLoader.getSpawn()).willReturn(spawn); given(spawnLoader.getSpawn()).willReturn(spawn);
CommandService service = mock(CommandService.class);
given(service.getSpawnLoader()).willReturn(spawnLoader);
Player player = mock(Player.class); Player player = mock(Player.class);
ExecutableCommand command = new SpawnCommand();
// when // when
command.executeCommand(player, Collections.<String>emptyList(), service); command.executeCommand(player, Collections.<String>emptyList(), service);
@ -45,12 +54,8 @@ public class SpawnCommandTest {
@Test @Test
public void shouldHandleMissingSpawn() { public void shouldHandleMissingSpawn() {
// given // given
SpawnLoader spawnLoader = mock(SpawnLoader.class);
given(spawnLoader.getSpawn()).willReturn(null); given(spawnLoader.getSpawn()).willReturn(null);
CommandService service = mock(CommandService.class);
given(service.getSpawnLoader()).willReturn(spawnLoader);
Player player = mock(Player.class); Player player = mock(Player.class);
ExecutableCommand command = new SpawnCommand();
// when // when
command.executeCommand(player, Collections.<String>emptyList(), service); command.executeCommand(player, Collections.<String>emptyList(), service);

View File

@ -8,6 +8,7 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.runners.MockitoJUnitRunner;
@ -16,8 +17,8 @@ import java.util.Arrays;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
/** /**
* Test for {@link AddEmailCommand}. * Test for {@link AddEmailCommand}.
@ -25,20 +26,25 @@ import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class AddEmailCommandTest { public class AddEmailCommandTest {
@InjectMocks
private AddEmailCommand command;
@Mock @Mock
private CommandService commandService; private CommandService commandService;
@Mock
private Management management;
@Test @Test
public void shouldRejectNonPlayerSender() { public void shouldRejectNonPlayerSender() {
// given // given
CommandSender sender = mock(BlockCommandSender.class); CommandSender sender = mock(BlockCommandSender.class);
AddEmailCommand command = new AddEmailCommand();
// when // when
command.executeCommand(sender, new ArrayList<String>(), commandService); command.executeCommand(sender, new ArrayList<String>(), commandService);
// then // then
verify(commandService, never()).getManagement(); verifyZeroInteractions(management);
} }
@Test @Test
@ -47,9 +53,6 @@ public class AddEmailCommandTest {
Player sender = mock(Player.class); Player sender = mock(Player.class);
String email = "mail@example"; String email = "mail@example";
given(commandService.validateEmail(email)).willReturn(true); given(commandService.validateEmail(email)).willReturn(true);
Management management = mock(Management.class);
given(commandService.getManagement()).willReturn(management);
AddEmailCommand command = new AddEmailCommand();
// when // when
command.executeCommand(sender, Arrays.asList(email, email), commandService); command.executeCommand(sender, Arrays.asList(email, email), commandService);
@ -64,13 +67,12 @@ public class AddEmailCommandTest {
Player sender = mock(Player.class); Player sender = mock(Player.class);
String email = "asdfasdf@example.com"; String email = "asdfasdf@example.com";
given(commandService.validateEmail(email)).willReturn(true); given(commandService.validateEmail(email)).willReturn(true);
AddEmailCommand command = new AddEmailCommand();
// when // when
command.executeCommand(sender, Arrays.asList(email, "wrongConf"), commandService); command.executeCommand(sender, Arrays.asList(email, "wrongConf"), commandService);
// then // then
verify(commandService, never()).getManagement(); verifyZeroInteractions(management);
verify(commandService).send(sender, MessageKey.CONFIRM_EMAIL_MESSAGE); verify(commandService).send(sender, MessageKey.CONFIRM_EMAIL_MESSAGE);
} }

View File

@ -5,49 +5,51 @@ import fr.xephi.authme.process.Management;
import org.bukkit.command.BlockCommandSender; import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.junit.Before;
import org.junit.Test; 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.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
/** /**
* Test for {@link ChangeEmailCommand}. * Test for {@link ChangeEmailCommand}.
*/ */
@RunWith(MockitoJUnitRunner.class)
public class ChangeEmailCommandTest { public class ChangeEmailCommandTest {
@InjectMocks
private ChangeEmailCommand command;
@Mock
private Management management;
@Mock
private CommandService commandService; private CommandService commandService;
@Before
public void setUpMocks() {
commandService = mock(CommandService.class);
}
@Test @Test
public void shouldRejectNonPlayerSender() { public void shouldRejectNonPlayerSender() {
// given // given
CommandSender sender = mock(BlockCommandSender.class); CommandSender sender = mock(BlockCommandSender.class);
ChangeEmailCommand command = new ChangeEmailCommand();
// when // when
command.executeCommand(sender, new ArrayList<String>(), commandService); command.executeCommand(sender, new ArrayList<String>(), commandService);
// then // then
verify(commandService, never()).getManagement(); verifyZeroInteractions(management);
} }
@Test @Test
public void shouldForwardData() { public void shouldForwardData() {
// given // given
Player sender = mock(Player.class); Player sender = mock(Player.class);
ChangeEmailCommand command = new ChangeEmailCommand();
Management management = mock(Management.class);
given(commandService.getManagement()).willReturn(management);
// when // when
command.executeCommand(sender, Arrays.asList("new.mail@example.org", "old_mail@example.org"), commandService); command.executeCommand(sender, Arrays.asList("new.mail@example.org", "old_mail@example.org"), commandService);

View File

@ -7,6 +7,7 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.runners.MockitoJUnitRunner;
@ -14,12 +15,11 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.argThat; import static org.mockito.Matchers.argThat;
import static org.mockito.Matchers.eq; import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
/** /**
* Test for {@link LoginCommand}. * Test for {@link LoginCommand}.
@ -27,6 +27,12 @@ import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class LoginCommandTest { public class LoginCommandTest {
@InjectMocks
private LoginCommand command;
@Mock
private Management management;
@Mock @Mock
private CommandService commandService; private CommandService commandService;
@ -34,13 +40,12 @@ public class LoginCommandTest {
public void shouldStopIfSenderIsNotAPlayer() { public void shouldStopIfSenderIsNotAPlayer() {
// given // given
CommandSender sender = mock(BlockCommandSender.class); CommandSender sender = mock(BlockCommandSender.class);
LoginCommand command = new LoginCommand();
// when // when
command.executeCommand(sender, new ArrayList<String>(), commandService); command.executeCommand(sender, new ArrayList<String>(), commandService);
// then // then
verify(commandService, never()).getManagement(); verifyZeroInteractions(management);
verify(sender).sendMessage(argThat(containsString("only for players"))); verify(sender).sendMessage(argThat(containsString("only for players")));
} }
@ -48,9 +53,6 @@ public class LoginCommandTest {
public void shouldCallManagementForPlayerCaller() { public void shouldCallManagementForPlayerCaller() {
// given // given
Player sender = mock(Player.class); Player sender = mock(Player.class);
LoginCommand command = new LoginCommand();
Management management = mock(Management.class);
given(commandService.getManagement()).willReturn(management);
// when // when
command.executeCommand(sender, Collections.singletonList("password"), commandService); command.executeCommand(sender, Collections.singletonList("password"), commandService);

View File

@ -7,22 +7,33 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; 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.ArrayList;
import java.util.Collections; import java.util.Collections;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.argThat; import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
/** /**
* Test for {@link LogoutCommand}. * Test for {@link LogoutCommand}.
*/ */
@RunWith(MockitoJUnitRunner.class)
public class LogoutCommandTest { public class LogoutCommandTest {
@InjectMocks
private LogoutCommand command;
@Mock
private Management management;
@Mock
private CommandService commandService; private CommandService commandService;
@Before @Before
@ -34,13 +45,12 @@ public class LogoutCommandTest {
public void shouldStopIfSenderIsNotAPlayer() { public void shouldStopIfSenderIsNotAPlayer() {
// given // given
CommandSender sender = mock(BlockCommandSender.class); CommandSender sender = mock(BlockCommandSender.class);
LogoutCommand command = new LogoutCommand();
// when // when
command.executeCommand(sender, new ArrayList<String>(), commandService); command.executeCommand(sender, new ArrayList<String>(), commandService);
// then // then
verify(commandService, never()).getManagement(); verifyZeroInteractions(management);
verify(sender).sendMessage(argThat(containsString("only for players"))); verify(sender).sendMessage(argThat(containsString("only for players")));
} }
@ -48,9 +58,6 @@ public class LogoutCommandTest {
public void shouldCallManagementForPlayerCaller() { public void shouldCallManagementForPlayerCaller() {
// given // given
Player sender = mock(Player.class); Player sender = mock(Player.class);
LogoutCommand command = new LogoutCommand();
Management management = mock(Management.class);
given(commandService.getManagement()).willReturn(management);
// when // when
command.executeCommand(sender, Collections.singletonList("password"), commandService); command.executeCommand(sender, Collections.singletonList("password"), commandService);

View File

@ -2,7 +2,6 @@ package fr.xephi.authme.command.executable.register;
import fr.xephi.authme.TestHelper; import fr.xephi.authme.TestHelper;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.MessageKey;
import fr.xephi.authme.process.Management; import fr.xephi.authme.process.Management;
import fr.xephi.authme.security.HashAlgorithm; import fr.xephi.authme.security.HashAlgorithm;
@ -19,6 +18,7 @@ import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.runners.MockitoJUnitRunner;
@ -40,10 +40,15 @@ import static org.mockito.Mockito.verifyZeroInteractions;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class RegisterCommandTest { public class RegisterCommandTest {
@InjectMocks
private RegisterCommand command;
@Mock @Mock
private CommandService commandService; private CommandService commandService;
@Mock @Mock
private Management management; private Management management;
@Mock @Mock
private Player sender; private Player sender;
@ -54,7 +59,6 @@ public class RegisterCommandTest {
@Before @Before
public void linkMocksAndProvideSettingDefaults() { public void linkMocksAndProvideSettingDefaults() {
given(commandService.getManagement()).willReturn(management);
given(commandService.getProperty(SecuritySettings.PASSWORD_HASH)).willReturn(HashAlgorithm.BCRYPT); given(commandService.getProperty(SecuritySettings.PASSWORD_HASH)).willReturn(HashAlgorithm.BCRYPT);
given(commandService.getProperty(RegistrationSettings.USE_EMAIL_REGISTRATION)).willReturn(false); given(commandService.getProperty(RegistrationSettings.USE_EMAIL_REGISTRATION)).willReturn(false);
given(commandService.getProperty(RestrictionSettings.ENABLE_PASSWORD_CONFIRMATION)).willReturn(false); given(commandService.getProperty(RestrictionSettings.ENABLE_PASSWORD_CONFIRMATION)).willReturn(false);
@ -64,7 +68,6 @@ public class RegisterCommandTest {
public void shouldNotRunForNonPlayerSender() { public void shouldNotRunForNonPlayerSender() {
// given // given
CommandSender sender = mock(BlockCommandSender.class); CommandSender sender = mock(BlockCommandSender.class);
RegisterCommand command = new RegisterCommand();
// when // when
command.executeCommand(sender, new ArrayList<String>(), commandService); command.executeCommand(sender, new ArrayList<String>(), commandService);
@ -78,7 +81,6 @@ public class RegisterCommandTest {
public void shouldForwardToManagementForTwoFactor() { public void shouldForwardToManagementForTwoFactor() {
// given // given
given(commandService.getProperty(SecuritySettings.PASSWORD_HASH)).willReturn(HashAlgorithm.TWO_FACTOR); given(commandService.getProperty(SecuritySettings.PASSWORD_HASH)).willReturn(HashAlgorithm.TWO_FACTOR);
ExecutableCommand command = new RegisterCommand();
// when // when
command.executeCommand(sender, Collections.<String>emptyList(), commandService); command.executeCommand(sender, Collections.<String>emptyList(), commandService);
@ -89,10 +91,7 @@ public class RegisterCommandTest {
@Test @Test
public void shouldReturnErrorForEmptyArguments() { public void shouldReturnErrorForEmptyArguments() {
// given // given / when
ExecutableCommand command = new RegisterCommand();
// when
command.executeCommand(sender, Collections.<String>emptyList(), commandService); command.executeCommand(sender, Collections.<String>emptyList(), commandService);
// then // then
@ -104,7 +103,6 @@ public class RegisterCommandTest {
public void shouldReturnErrorForMissingConfirmation() { public void shouldReturnErrorForMissingConfirmation() {
// given // given
given(commandService.getProperty(RestrictionSettings.ENABLE_PASSWORD_CONFIRMATION)).willReturn(true); given(commandService.getProperty(RestrictionSettings.ENABLE_PASSWORD_CONFIRMATION)).willReturn(true);
ExecutableCommand command = new RegisterCommand();
// when // when
command.executeCommand(sender, Collections.singletonList("arrrr"), commandService); command.executeCommand(sender, Collections.singletonList("arrrr"), commandService);
@ -119,7 +117,6 @@ public class RegisterCommandTest {
// given // given
given(commandService.getProperty(RegistrationSettings.USE_EMAIL_REGISTRATION)).willReturn(true); given(commandService.getProperty(RegistrationSettings.USE_EMAIL_REGISTRATION)).willReturn(true);
given(commandService.getProperty(RegistrationSettings.ENABLE_CONFIRM_EMAIL)).willReturn(true); given(commandService.getProperty(RegistrationSettings.ENABLE_CONFIRM_EMAIL)).willReturn(true);
ExecutableCommand command = new RegisterCommand();
// when // when
command.executeCommand(sender, Collections.singletonList("test@example.org"), commandService); 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.USE_EMAIL_REGISTRATION)).willReturn(true);
given(commandService.getProperty(RegistrationSettings.ENABLE_CONFIRM_EMAIL)).willReturn(false); given(commandService.getProperty(RegistrationSettings.ENABLE_CONFIRM_EMAIL)).willReturn(false);
given(commandService.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn(""); given(commandService.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn("");
ExecutableCommand command = new RegisterCommand();
// when // when
command.executeCommand(sender, Collections.singletonList("myMail@example.tld"), commandService); 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(RegistrationSettings.ENABLE_CONFIRM_EMAIL)).willReturn(true);
given(commandService.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn("server@example.com"); given(commandService.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn("server@example.com");
ExecutableCommand command = new RegisterCommand();
// when // when
command.executeCommand(sender, Arrays.asList(playerMail, playerMail), commandService); 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(RegistrationSettings.ENABLE_CONFIRM_EMAIL)).willReturn(true);
given(commandService.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn("server@example.com"); given(commandService.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn("server@example.com");
ExecutableCommand command = new RegisterCommand();
// when // when
command.executeCommand(sender, Arrays.asList(playerMail, "invalid"), commandService); 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.USE_EMAIL_REGISTRATION)).willReturn(true);
given(commandService.getProperty(RegistrationSettings.ENABLE_CONFIRM_EMAIL)).willReturn(true); given(commandService.getProperty(RegistrationSettings.ENABLE_CONFIRM_EMAIL)).willReturn(true);
given(commandService.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn("server@example.com"); given(commandService.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn("server@example.com");
ExecutableCommand command = new RegisterCommand();
// when // when
command.executeCommand(sender, Arrays.asList(playerMail, playerMail), commandService); command.executeCommand(sender, Arrays.asList(playerMail, playerMail), commandService);
@ -211,7 +202,6 @@ public class RegisterCommandTest {
public void shouldRejectInvalidPasswordConfirmation() { public void shouldRejectInvalidPasswordConfirmation() {
// given // given
given(commandService.getProperty(RestrictionSettings.ENABLE_PASSWORD_CONFIRMATION)).willReturn(true); given(commandService.getProperty(RestrictionSettings.ENABLE_PASSWORD_CONFIRMATION)).willReturn(true);
ExecutableCommand command = new RegisterCommand();
// when // when
command.executeCommand(sender, Arrays.asList("myPass", "mypass"), commandService); command.executeCommand(sender, Arrays.asList("myPass", "mypass"), commandService);
@ -223,10 +213,7 @@ public class RegisterCommandTest {
@Test @Test
public void shouldPerformPasswordValidation() { public void shouldPerformPasswordValidation() {
// given // given / when
ExecutableCommand command = new RegisterCommand();
// when
command.executeCommand(sender, Collections.singletonList("myPass"), commandService); command.executeCommand(sender, Collections.singletonList("myPass"), commandService);
// then // then

View File

@ -8,6 +8,7 @@ import fr.xephi.authme.initialization.samples.ClassWithAbstractDependency;
import fr.xephi.authme.initialization.samples.ClassWithAnnotations; import fr.xephi.authme.initialization.samples.ClassWithAnnotations;
import fr.xephi.authme.initialization.samples.Duration; import fr.xephi.authme.initialization.samples.Duration;
import fr.xephi.authme.initialization.samples.FieldInjectionWithAnnotations; 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.InvalidClass;
import fr.xephi.authme.initialization.samples.InvalidPostConstruct; import fr.xephi.authme.initialization.samples.InvalidPostConstruct;
import fr.xephi.authme.initialization.samples.InvalidStaticFieldInjection; import fr.xephi.authme.initialization.samples.InvalidStaticFieldInjection;
@ -231,4 +232,16 @@ public class AuthMeServiceInitializerTest {
initializer.newInstance(InvalidStaticFieldInjection.class); 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()));
}
} }

View File

@ -1,6 +1,7 @@
package fr.xephi.authme.initialization; package fr.xephi.authme.initialization;
import fr.xephi.authme.initialization.samples.AlphaService; 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.ClassWithAnnotations;
import fr.xephi.authme.initialization.samples.Duration; import fr.xephi.authme.initialization.samples.Duration;
import fr.xephi.authme.initialization.samples.GammaService; import fr.xephi.authme.initialization.samples.GammaService;
@ -20,7 +21,6 @@ import static org.junit.Assert.assertThat;
*/ */
public class ConstructorInjectionTest { public class ConstructorInjectionTest {
@SuppressWarnings("unchecked")
@Test @Test
public void shouldReturnDependencies() { public void shouldReturnDependencies() {
// given // given
@ -74,8 +74,7 @@ public class ConstructorInjectionTest {
@Test @Test
public void shouldReturnNullForNoConstructorInjection() { public void shouldReturnNullForNoConstructorInjection() {
// given / when // given / when
@SuppressWarnings("rawtypes") Injection<BetaManager> injection = ConstructorInjection.provide(BetaManager.class).get();
Injection<FieldInjection> injection = ConstructorInjection.provide(FieldInjection.class).get();
// then // then
assertThat(injection, nullValue()); assertThat(injection, nullValue());

View File

@ -105,6 +105,15 @@ public class FieldInjectionTest {
FieldInjection.provide(InvalidStaticFieldInjection.class).get(); FieldInjection.provide(InvalidStaticFieldInjection.class).get();
} }
@Test
public void shouldNotReturnFieldInjectionForZeroInjectFields() {
// given / when
Injection<NoInjectionClass> injection = FieldInjection.provide(NoInjectionClass.class).get();
// then
assertThat(injection, nullValue());
}
private static class ThrowingConstructor { private static class ThrowingConstructor {
@SuppressWarnings("unused") @SuppressWarnings("unused")
@Inject @Inject
@ -115,4 +124,10 @@ public class FieldInjectionTest {
throw new UnsupportedOperationException("Exception in constructor"); throw new UnsupportedOperationException("Exception in constructor");
} }
} }
private static class NoInjectionClass {
private BetaManager betaManager;
}
} }

View File

@ -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<InstantiationFallbackClasses.FallbackClass> 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<InstantiationFallbackClasses.FallbackClass> instantiation =
InstantiationFallback.provide(InstantiationFallbackClasses.FallbackClass.class).get();
// when / then
instantiation.instantiateWith("some argument");
}
@Test
public void shouldReturnNullForClassWithInjectMethod() {
// given / when
Injection<InstantiationFallbackClasses.InvalidInjectOnMethodClass> instantiation =
InstantiationFallback.provide(InstantiationFallbackClasses.InvalidInjectOnMethodClass.class).get();
// then
assertThat(instantiation, nullValue());
}
@Test
public void shouldReturnNullForMissingNoArgsConstructor() {
// given / when
Injection<InstantiationFallbackClasses.InvalidFallbackClass> instantiation =
InstantiationFallback.provide(InstantiationFallbackClasses.InvalidFallbackClass.class).get();
// then
assertThat(instantiation, nullValue());
}
@Test
public void shouldReturnNullForDifferentInjectionType() {
// given / when
Injection<GammaService> instantiation = InstantiationFallback.provide(GammaService.class).get();
// then
assertThat(instantiation, nullValue());
}
}

View File

@ -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) {
// --
}
}
}

View File

@ -35,7 +35,8 @@ public class CommandPageCreater implements ToolTask {
@Override @Override
public void execute(Scanner scanner) { public void execute(Scanner scanner) {
final Set<CommandDescription> baseCommands = CommandInitializer.buildCommands(getMockInitializer()); CommandInitializer commandInitializer = new CommandInitializer(getMockInitializer());
final Set<CommandDescription> baseCommands = commandInitializer.getCommands();
NestedTagValue commandTags = new NestedTagValue(); NestedTagValue commandTags = new NestedTagValue();
addCommandsInfo(commandTags, baseCommands); addCommandsInfo(commandTags, baseCommands);