Move getOnlinePlayers() from Utils to BukkitService; delete Wrapper

This commit is contained in:
ljacqu 2016-04-23 15:24:41 +02:00
parent a78e0408c6
commit 59d3bc95c0
26 changed files with 262 additions and 428 deletions

View File

@ -250,6 +250,7 @@ public class AuthMe extends JavaPlugin {
return; return;
} }
bukkitService = new BukkitService(this);
pluginHooks = new PluginHooks(server.getPluginManager()); pluginHooks = new PluginHooks(server.getPluginManager());
MigrationService.changePlainTextToSha256(newSettings, database, new SHA256()); MigrationService.changePlainTextToSha256(newSettings, database, new SHA256());
@ -257,8 +258,6 @@ public class AuthMe extends JavaPlugin {
// Initialize spawn loader // Initialize spawn loader
spawnLoader = new SpawnLoader(getDataFolder(), newSettings, pluginHooks); spawnLoader = new SpawnLoader(getDataFolder(), newSettings, pluginHooks);
bukkitService = new BukkitService(this);
permsMan = initializePermissionsManager(); permsMan = initializePermissionsManager();
antiBot = new AntiBot(newSettings, messages, permsMan, bukkitService); antiBot = new AntiBot(newSettings, messages, permsMan, bukkitService);
ValidationService validationService = new ValidationService(newSettings, database, permsMan); ValidationService validationService = new ValidationService(newSettings, database, permsMan);
@ -297,7 +296,7 @@ public class AuthMe extends JavaPlugin {
// Set up the management // Set up the management
ProcessService processService = new ProcessService(newSettings, messages, this, database, ProcessService processService = new ProcessService(newSettings, messages, this, database,
passwordSecurity, pluginHooks, spawnLoader, validationService); passwordSecurity, pluginHooks, spawnLoader, validationService, bukkitService);
management = new Management(this, processService, database, PlayerCache.getInstance()); management = new Management(this, processService, database, PlayerCache.getInstance());
// Set up the BungeeCord hook // Set up the BungeeCord hook
@ -400,7 +399,7 @@ public class AuthMe extends JavaPlugin {
private void reloadSupportHook() { private void reloadSupportHook() {
if (database != null) { if (database != null) {
int playersOnline = Utils.getOnlinePlayers().size(); int playersOnline = bukkitService.getOnlinePlayers().size();
if (playersOnline < 1) { if (playersOnline < 1) {
database.purgeLogged(); database.purgeLogged();
} else if (Settings.reloadSupport) { } else if (Settings.reloadSupport) {
@ -499,9 +498,11 @@ public class AuthMe extends JavaPlugin {
@Override @Override
public void onDisable() { public void onDisable() {
// Save player data // Save player data
Collection<? extends Player> players = Utils.getOnlinePlayers(); if (bukkitService != null) {
for (Player player : players) { Collection<? extends Player> players = bukkitService.getOnlinePlayers();
savePlayer(player); for (Player player : players) {
savePlayer(player);
}
} }
// Do backup on stop if enabled // Do backup on stop if enabled
@ -660,7 +661,7 @@ public class AuthMe extends JavaPlugin {
tabComplete = null; tabComplete = null;
} }
if (newSettings.getProperty(RestrictionSettings.HIDE_TABLIST_BEFORE_LOGIN) && tablistHider == null) { if (newSettings.getProperty(RestrictionSettings.HIDE_TABLIST_BEFORE_LOGIN) && tablistHider == null) {
tablistHider = new AuthMeTablistPacketAdapter(this); tablistHider = new AuthMeTablistPacketAdapter(this, bukkitService);
tablistHider.register(); tablistHider.register();
} else if (tablistHider != null) { } else if (tablistHider != null) {
tablistHider.unregister(); tablistHider.unregister();
@ -769,7 +770,7 @@ public class AuthMe extends JavaPlugin {
} }
public String replaceAllInfo(String message, Player player) { public String replaceAllInfo(String message, Player player) {
String playersOnline = Integer.toString(Utils.getOnlinePlayers().size()); String playersOnline = Integer.toString(bukkitService.getOnlinePlayers().size());
String ipAddress = Utils.getPlayerIp(player); String ipAddress = Utils.getPlayerIp(player);
return message return message
.replace("&", "\u00a7") .replace("&", "\u00a7")
@ -786,7 +787,7 @@ public class AuthMe extends JavaPlugin {
public boolean isLoggedIp(String name, String ip) { public boolean isLoggedIp(String name, String ip) {
int count = 0; int count = 0;
for (Player player : Utils.getOnlinePlayers()) { for (Player player : bukkitService.getOnlinePlayers()) {
if (ip.equalsIgnoreCase(Utils.getPlayerIp(player)) if (ip.equalsIgnoreCase(Utils.getPlayerIp(player))
&& database.isLogged(player.getName().toLowerCase()) && database.isLogged(player.getName().toLowerCase())
&& !player.getName().equalsIgnoreCase(name)) { && !player.getName().equalsIgnoreCase(name)) {

View File

@ -10,8 +10,8 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer; import com.google.gson.JsonSerializer;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.settings.Settings;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.io.File; import java.io.File;
@ -24,7 +24,7 @@ public class JsonCache {
private final File cacheDir; private final File cacheDir;
public JsonCache() { public JsonCache() {
cacheDir = Settings.CACHE_FOLDER; cacheDir = new File(AuthMe.getInstance().getDataFolder(), "cache");
if (!cacheDir.exists() && !cacheDir.isDirectory() && !cacheDir.mkdir()) { if (!cacheDir.exists() && !cacheDir.isDirectory() && !cacheDir.mkdir()) {
ConsoleLogger.showError("Failed to create cache directory."); ConsoleLogger.showError("Failed to create cache directory.");
} }

View File

@ -19,6 +19,7 @@ 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 java.util.Collection;
import java.util.List; import java.util.List;
/** /**
@ -231,4 +232,12 @@ public class CommandService {
return bukkitService.getPlayerExact(name); return bukkitService.getPlayerExact(name);
} }
public Collection<? extends Player> getOnlinePlayers() {
return bukkitService.getOnlinePlayers();
}
public BukkitService getBukkitService() {
return bukkitService;
}
} }

View File

@ -63,10 +63,9 @@ public class UnregisterAdminCommand implements ExecutableCommand {
LimboCache.getInstance().getLimboPlayer(playerNameLowerCase).setTimeoutTask(id); LimboCache.getInstance().getLimboPlayer(playerNameLowerCase).setTimeoutTask(id);
} }
LimboCache.getInstance().getLimboPlayer(playerNameLowerCase).setMessageTask( LimboCache.getInstance().getLimboPlayer(playerNameLowerCase).setMessageTask(
scheduler.runTask( scheduler.runTask(plugin, new MessageTask(commandService.getBukkitService(), plugin.getMessages(),
plugin, new MessageTask(plugin, playerNameLowerCase, MessageKey.REGISTER_MESSAGE, interval) playerNameLowerCase, MessageKey.REGISTER_MESSAGE, interval)));
)
);
if (commandService.getProperty(RegistrationSettings.APPLY_BLIND_EFFECT)) { if (commandService.getProperty(RegistrationSettings.APPLY_BLIND_EFFECT)) {
target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, timeOut, 2)); target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, timeOut, 2));
} }

View File

@ -3,11 +3,11 @@ package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe; 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.util.Utils;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.Collection;
import java.util.List; import java.util.List;
import static fr.xephi.authme.settings.properties.PluginSettings.HELP_HEADER; import static fr.xephi.authme.settings.properties.PluginSettings.HELP_HEADER;
@ -22,11 +22,12 @@ public class VersionCommand implements ExecutableCommand {
sender.sendMessage(ChatColor.GOLD + "Version: " + ChatColor.WHITE + AuthMe.getPluginName() sender.sendMessage(ChatColor.GOLD + "Version: " + ChatColor.WHITE + AuthMe.getPluginName()
+ " v" + AuthMe.getPluginVersion() + ChatColor.GRAY + " (build: " + AuthMe.getPluginBuildNumber() + ")"); + " v" + AuthMe.getPluginVersion() + ChatColor.GRAY + " (build: " + AuthMe.getPluginBuildNumber() + ")");
sender.sendMessage(ChatColor.GOLD + "Developers:"); sender.sendMessage(ChatColor.GOLD + "Developers:");
printDeveloper(sender, "Xephi", "xephi59", "Lead Developer"); Collection<? extends Player> onlinePlayers = commandService.getOnlinePlayers();
printDeveloper(sender, "DNx5", "DNx5", "Developer"); printDeveloper(sender, "Xephi", "xephi59", "Lead Developer", onlinePlayers);
printDeveloper(sender, "games647", "games647", "Developer"); printDeveloper(sender, "DNx5", "DNx5", "Developer", onlinePlayers);
printDeveloper(sender, "Tim Visee", "timvisee", "Developer"); printDeveloper(sender, "games647", "games647", "Developer", onlinePlayers);
printDeveloper(sender, "Sgdc3", "sgdc3", "Project manager, Contributor"); printDeveloper(sender, "Tim Visee", "timvisee", "Developer", onlinePlayers);
printDeveloper(sender, "Sgdc3", "sgdc3", "Project manager, Contributor", onlinePlayers);
sender.sendMessage(ChatColor.GOLD + "Website: " + ChatColor.WHITE + sender.sendMessage(ChatColor.GOLD + "Website: " + ChatColor.WHITE +
"http://dev.bukkit.org/bukkit-plugins/authme-reloaded/"); "http://dev.bukkit.org/bukkit-plugins/authme-reloaded/");
sender.sendMessage(ChatColor.GOLD + "License: " + ChatColor.WHITE + "GNU GPL v3.0" sender.sendMessage(ChatColor.GOLD + "License: " + ChatColor.WHITE + "GNU GPL v3.0"
@ -38,12 +39,14 @@ public class VersionCommand implements ExecutableCommand {
/** /**
* Print a developer with proper styling. * Print a developer with proper styling.
* *
* @param sender The command sender. * @param sender The command sender
* @param name The display name of the developer. * @param name The display name of the developer
* @param minecraftName The Minecraft username of the developer, if available. * @param minecraftName The Minecraft username of the developer, if available
* @param function The function of the developer. * @param function The function of the developer
* @param onlinePlayers The list of online players
*/ */
private static void printDeveloper(CommandSender sender, String name, String minecraftName, String function) { private static void printDeveloper(CommandSender sender, String name, String minecraftName, String function,
Collection<? extends Player> onlinePlayers) {
// Print the name // Print the name
StringBuilder msg = new StringBuilder(); StringBuilder msg = new StringBuilder();
msg.append(" ") msg.append(" ")
@ -55,7 +58,7 @@ public class VersionCommand implements ExecutableCommand {
msg.append(ChatColor.GRAY).append(ChatColor.ITALIC).append(" (").append(function).append(")"); msg.append(ChatColor.GRAY).append(ChatColor.ITALIC).append(" (").append(function).append(")");
// Show the online status // Show the online status
if (isPlayerOnline(minecraftName)) { if (isPlayerOnline(minecraftName, onlinePlayers)) {
msg.append(ChatColor.GREEN).append(ChatColor.ITALIC).append(" (In-Game)"); msg.append(ChatColor.GREEN).append(ChatColor.ITALIC).append(" (In-Game)");
} }
@ -66,12 +69,13 @@ public class VersionCommand implements ExecutableCommand {
/** /**
* Check whether a player is online. * Check whether a player is online.
* *
* @param minecraftName The Minecraft player name. * @param minecraftName The Minecraft player name
* @param onlinePlayers List of online players
* *
* @return True if the player is online, false otherwise. * @return True if the player is online, false otherwise
*/ */
private static boolean isPlayerOnline(String minecraftName) { private static boolean isPlayerOnline(String minecraftName, Collection<? extends Player> onlinePlayers) {
for (Player player : Utils.getOnlinePlayers()) { for (Player player : onlinePlayers) {
if (player.getName().equalsIgnoreCase(minecraftName)) { if (player.getName().equalsIgnoreCase(minecraftName)) {
return true; return true;
} }

View File

@ -24,11 +24,13 @@ public class RakamakConverter implements Converter {
private final AuthMe instance; private final AuthMe instance;
private final DataSource database; private final DataSource database;
private final CommandSender sender; private final CommandSender sender;
private final File pluginFolder;
public RakamakConverter(AuthMe instance, CommandSender sender) { public RakamakConverter(AuthMe instance, CommandSender sender) {
this.instance = instance; this.instance = instance;
this.database = instance.getDataSource(); this.database = instance.getDataSource();
this.sender = sender; this.sender = sender;
pluginFolder = instance.getDataFolder();
} }
@Override @Override
@ -37,8 +39,8 @@ public class RakamakConverter implements Converter {
boolean useIP = Settings.rakamakUseIp; boolean useIP = Settings.rakamakUseIp;
String fileName = Settings.rakamakUsers; String fileName = Settings.rakamakUsers;
String ipFileName = Settings.rakamakUsersIp; String ipFileName = Settings.rakamakUsersIp;
File source = new File(Settings.PLUGIN_FOLDER, fileName); File source = new File(pluginFolder, fileName);
File ipfiles = new File(Settings.PLUGIN_FOLDER, ipFileName); File ipfiles = new File(pluginFolder, ipFileName);
HashMap<String, String> playerIP = new HashMap<>(); HashMap<String, String> playerIP = new HashMap<>();
HashMap<String, HashedPassword> playerPSW = new HashMap<>(); HashMap<String, HashedPassword> playerPSW = new HashMap<>();
try { try {

View File

@ -96,7 +96,7 @@ public class AuthMePlayerListener implements Listener {
event.setCancelled(true); event.setCancelled(true);
sendLoginOrRegisterMessage(player); sendLoginOrRegisterMessage(player);
} else if (settings.getProperty(RestrictionSettings.HIDE_CHAT)) { } else if (settings.getProperty(RestrictionSettings.HIDE_CHAT)) {
for (Player p : Utils.getOnlinePlayers()) { for (Player p : bukkitService.getOnlinePlayers()) {
if (!PlayerCache.getInstance().isAuthenticated(p.getName())) { if (!PlayerCache.getInstance().isAuthenticated(p.getName())) {
event.getRecipients().remove(p); event.getRecipients().remove(p);
} }
@ -319,11 +319,11 @@ public class AuthMePlayerListener implements Listener {
if (event.getResult() == PlayerLoginEvent.Result.KICK_FULL) { if (event.getResult() == PlayerLoginEvent.Result.KICK_FULL) {
if (permsMan.hasPermission(player, PlayerStatePermission.IS_VIP)) { if (permsMan.hasPermission(player, PlayerStatePermission.IS_VIP)) {
int playersOnline = Utils.getOnlinePlayers().size(); int playersOnline = bukkitService.getOnlinePlayers().size();
if (playersOnline > plugin.getServer().getMaxPlayers()) { if (playersOnline > plugin.getServer().getMaxPlayers()) {
event.allow(); event.allow();
} else { } else {
Player pl = plugin.generateKickPlayer(Utils.getOnlinePlayers()); Player pl = plugin.generateKickPlayer(bukkitService.getOnlinePlayers());
if (pl != null) { if (pl != null) {
pl.kickPlayer(m.retrieveSingle(MessageKey.KICK_FOR_VIP)); pl.kickPlayer(m.retrieveSingle(MessageKey.KICK_FOR_VIP));
event.allow(); event.allow();

View File

@ -13,22 +13,23 @@ import com.comphenix.protocol.wrappers.EnumWrappers.PlayerInfoAction;
import com.comphenix.protocol.wrappers.PlayerInfoData; import com.comphenix.protocol.wrappers.PlayerInfoData;
import com.comphenix.protocol.wrappers.WrappedChatComponent; import com.comphenix.protocol.wrappers.WrappedChatComponent;
import com.comphenix.protocol.wrappers.WrappedGameProfile; import com.comphenix.protocol.wrappers.WrappedGameProfile;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.util.Utils; import fr.xephi.authme.util.BukkitService;
import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.util.Arrays; import java.util.Arrays;
import java.util.logging.Level; import java.util.logging.Level;
import org.bukkit.entity.Player;
public class AuthMeTablistPacketAdapter extends PacketAdapter { public class AuthMeTablistPacketAdapter extends PacketAdapter {
public AuthMeTablistPacketAdapter(AuthMe plugin) { private final BukkitService bukkitService;
public AuthMeTablistPacketAdapter(AuthMe plugin, BukkitService bukkitService) {
super(plugin, ListenerPriority.NORMAL, PacketType.Play.Server.PLAYER_INFO); super(plugin, ListenerPriority.NORMAL, PacketType.Play.Server.PLAYER_INFO);
this.bukkitService = bukkitService;
} }
@Override @Override
@ -40,7 +41,7 @@ public class AuthMeTablistPacketAdapter extends PacketAdapter {
event.setCancelled(true); event.setCancelled(true);
} }
} catch (FieldAccessException e) { } catch (FieldAccessException e) {
ConsoleLogger.showError("Couldn't access field."); ConsoleLogger.logException("Couldn't access field", e);
} }
} }
} }
@ -67,7 +68,7 @@ public class AuthMeTablistPacketAdapter extends PacketAdapter {
} }
//triggers an update for others player to see them //triggers an update for others player to see them
for (Player onlinePlayer : Utils.getOnlinePlayers()) { for (Player onlinePlayer : bukkitService.getOnlinePlayers()) {
if (onlinePlayer.equals(receiver) || !receiver.canSee(onlinePlayer)) { if (onlinePlayer.equals(receiver) || !receiver.canSee(onlinePlayer)) {
continue; continue;
} }

View File

@ -10,11 +10,15 @@ import fr.xephi.authme.security.crypts.HashedPassword;
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.domain.Property; import fr.xephi.authme.settings.domain.Property;
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.event.Event; import org.bukkit.event.Event;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
import java.util.Collection;
/** /**
* Service for asynchronous and synchronous processes. * Service for asynchronous and synchronous processes.
*/ */
@ -28,10 +32,11 @@ public class ProcessService {
private final PluginHooks pluginHooks; private final PluginHooks pluginHooks;
private final SpawnLoader spawnLoader; private final SpawnLoader spawnLoader;
private final ValidationService validationService; private final ValidationService validationService;
private final BukkitService bukkitService;
public ProcessService(NewSetting settings, Messages messages, AuthMe authMe, DataSource dataSource, public ProcessService(NewSetting settings, Messages messages, AuthMe authMe, DataSource dataSource,
PasswordSecurity passwordSecurity, PluginHooks pluginHooks, PasswordSecurity passwordSecurity, PluginHooks pluginHooks, SpawnLoader spawnLoader,
SpawnLoader spawnLoader, ValidationService validationService) { ValidationService validationService, BukkitService bukkitService) {
this.settings = settings; this.settings = settings;
this.messages = messages; this.messages = messages;
this.authMe = authMe; this.authMe = authMe;
@ -40,6 +45,7 @@ public class ProcessService {
this.pluginHooks = pluginHooks; this.pluginHooks = pluginHooks;
this.spawnLoader = spawnLoader; this.spawnLoader = spawnLoader;
this.validationService = validationService; this.validationService = validationService;
this.bukkitService = bukkitService;
} }
/** /**
@ -209,4 +215,12 @@ public class ProcessService {
return validationService.isEmailFreeForRegistration(email, sender); return validationService.isEmailFreeForRegistration(email, sender);
} }
public Collection<? extends Player> getOnlinePlayers() {
return bukkitService.getOnlinePlayers();
}
public BukkitService getBukkitService() {
return bukkitService;
}
} }

View File

@ -217,7 +217,8 @@ public class AsynchronousJoin implements Process {
: MessageKey.REGISTER_MESSAGE; : MessageKey.REGISTER_MESSAGE;
} }
if (msgInterval > 0 && LimboCache.getInstance().getLimboPlayer(name) != null) { if (msgInterval > 0 && LimboCache.getInstance().getLimboPlayer(name) != null) {
BukkitTask msgTask = service.runTask(new MessageTask(plugin, name, msg, msgInterval)); BukkitTask msgTask = service.runTask(new MessageTask(service.getBukkitService(), plugin.getMessages(),
name, msg, msgInterval));
LimboCache.getInstance().getLimboPlayer(name).setMessageTask(msgTask); LimboCache.getInstance().getLimboPlayer(name).setMessageTask(msgTask);
} }
} }
@ -303,7 +304,7 @@ public class AsynchronousJoin implements Process {
private boolean hasJoinedIp(String name, String ip) { private boolean hasJoinedIp(String name, String ip) {
int count = 0; int count = 0;
for (Player player : Utils.getOnlinePlayers()) { for (Player player : service.getOnlinePlayers()) {
if (ip.equalsIgnoreCase(Utils.getPlayerIp(player)) if (ip.equalsIgnoreCase(Utils.getPlayerIp(player))
&& !player.getName().equalsIgnoreCase(name)) { && !player.getName().equalsIgnoreCase(name)) {
count++; count++;

View File

@ -97,8 +97,8 @@ public class AsynchronousLogin implements Process {
String[] msg = service.getProperty(RegistrationSettings.USE_EMAIL_REGISTRATION) String[] msg = service.getProperty(RegistrationSettings.USE_EMAIL_REGISTRATION)
? service.retrieveMessage(MessageKey.REGISTER_EMAIL_MESSAGE) ? service.retrieveMessage(MessageKey.REGISTER_EMAIL_MESSAGE)
: service.retrieveMessage(MessageKey.REGISTER_MESSAGE); : service.retrieveMessage(MessageKey.REGISTER_MESSAGE);
BukkitTask messageTask = service.runTask( BukkitTask messageTask = service.runTask(new MessageTask(service.getBukkitService(),
new MessageTask(plugin, name, msg, service.getProperty(RegistrationSettings.MESSAGE_INTERVAL))); name, msg, service.getProperty(RegistrationSettings.MESSAGE_INTERVAL)));
limboPlayer.setMessageTask(messageTask); limboPlayer.setMessageTask(messageTask);
} }
return null; return null;
@ -223,7 +223,7 @@ public class AsynchronousLogin implements Process {
return; return;
} }
String message = "[AuthMe] " + StringUtils.join(", ", auths) + "."; String message = "[AuthMe] " + StringUtils.join(", ", auths) + ".";
for (Player player : Utils.getOnlinePlayers()) { for (Player player : service.getOnlinePlayers()) {
if (plugin.getPermissionsManager().hasPermission(player, AdminPermission.SEE_OTHER_ACCOUNTS) if (plugin.getPermissionsManager().hasPermission(player, AdminPermission.SEE_OTHER_ACCOUNTS)
|| (player.getName().equals(this.player.getName()) || (player.getName().equals(this.player.getName())
&& plugin.getPermissionsManager().hasPermission(player, PlayerPermission.SEE_OWN_ACCOUNTS))) { && plugin.getPermissionsManager().hasPermission(player, PlayerPermission.SEE_OWN_ACCOUNTS))) {

View File

@ -174,7 +174,7 @@ public class ProcessSyncPlayerLogin implements Process {
String jm = AuthMePlayerListener.joinMessage.get(name); String jm = AuthMePlayerListener.joinMessage.get(name);
if (jm != null) { if (jm != null) {
if (!jm.isEmpty()) { if (!jm.isEmpty()) {
for (Player p : Utils.getOnlinePlayers()) { for (Player p : service.getOnlinePlayers()) {
if (p.isOnline()) { if (p.isOnline()) {
p.sendMessage(jm); p.sendMessage(jm);
} }

View File

@ -74,7 +74,8 @@ public class ProcessSynchronousPlayerLogout implements Process {
BukkitTask id = service.runTaskLater(new TimeoutTask(plugin, name, player), timeOut); BukkitTask id = service.runTaskLater(new TimeoutTask(plugin, name, player), timeOut);
LimboCache.getInstance().getLimboPlayer(name).setTimeoutTask(id); LimboCache.getInstance().getLimboPlayer(name).setTimeoutTask(id);
} }
BukkitTask msgT = service.runTask(new MessageTask(plugin, name, MessageKey.LOGIN_MESSAGE, interval)); BukkitTask msgT = service.runTask(new MessageTask(service.getBukkitService(), plugin.getMessages(),
name, MessageKey.LOGIN_MESSAGE, interval));
LimboCache.getInstance().getLimboPlayer(name).setMessageTask(msgT); LimboCache.getInstance().getLimboPlayer(name).setMessageTask(msgT);
if (player.isInsideVehicle() && player.getVehicle() != null) { if (player.isInsideVehicle() && player.getVehicle() != null) {
player.getVehicle().eject(); player.getVehicle().eject();

View File

@ -52,7 +52,7 @@ public class ProcessSyncEmailRegister implements Process {
limbo.setTimeoutTask(id); limbo.setTimeoutTask(id);
} }
BukkitTask messageTask = service.runTask(new MessageTask( BukkitTask messageTask = service.runTask(new MessageTask(
service.getAuthMe(), name, service.retrieveMessage(MessageKey.LOGIN_MESSAGE), msgInterval)); service.getBukkitService(), name, service.retrieveMessage(MessageKey.LOGIN_MESSAGE), msgInterval));
limbo.setMessageTask(messageTask); limbo.setMessageTask(messageTask);
} }

View File

@ -32,8 +32,8 @@ import static fr.xephi.authme.util.BukkitService.TICKS_PER_SECOND;
*/ */
public class ProcessSyncPasswordRegister implements Process { public class ProcessSyncPasswordRegister implements Process {
protected final Player player; private final Player player;
protected final String name; private final String name;
private final AuthMe plugin; private final AuthMe plugin;
private final ProcessService service; private final ProcessService service;
@ -74,7 +74,8 @@ public class ProcessSyncPasswordRegister implements Process {
task = service.runTaskLater(new TimeoutTask(service.getAuthMe(), name, player), delay); task = service.runTaskLater(new TimeoutTask(service.getAuthMe(), name, player), delay);
cache.getLimboPlayer(name).setTimeoutTask(task); cache.getLimboPlayer(name).setTimeoutTask(task);
} }
task = service.runTask(new MessageTask(plugin, name, MessageKey.LOGIN_MESSAGE, interval)); task = service.runTask(new MessageTask(service.getBukkitService(), plugin.getMessages(),
name, MessageKey.LOGIN_MESSAGE, interval));
cache.getLimboPlayer(name).setMessageTask(task); cache.getLimboPlayer(name).setMessageTask(task);
if (player.isInsideVehicle() && player.getVehicle() != null) { if (player.isInsideVehicle() && player.getVehicle() != null) {
player.getVehicle().eject(); player.getVehicle().eject();

View File

@ -20,7 +20,6 @@ import fr.xephi.authme.util.Utils.GroupType;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType; import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
public class AsynchronousUnregister implements Process { public class AsynchronousUnregister implements Process {
@ -73,13 +72,12 @@ public class AsynchronousUnregister implements Process {
LimboCache.getInstance().addLimboPlayer(player); LimboCache.getInstance().addLimboPlayer(player);
LimboPlayer limboPlayer = LimboCache.getInstance().getLimboPlayer(name); LimboPlayer limboPlayer = LimboCache.getInstance().getLimboPlayer(name);
int interval = service.getProperty(RegistrationSettings.MESSAGE_INTERVAL); int interval = service.getProperty(RegistrationSettings.MESSAGE_INTERVAL);
BukkitScheduler scheduler = plugin.getServer().getScheduler();
if (timeOut != 0) { if (timeOut != 0) {
BukkitTask id = scheduler.runTaskLater(plugin, new TimeoutTask(plugin, name, player), timeOut); BukkitTask id = service.runTaskLater(new TimeoutTask(plugin, name, player), timeOut);
limboPlayer.setTimeoutTask(id); limboPlayer.setTimeoutTask(id);
} }
limboPlayer.setMessageTask(scheduler.runTask(plugin, limboPlayer.setMessageTask(service.runTask(new MessageTask(service.getBukkitService(),
new MessageTask(plugin, name, MessageKey.REGISTER_MESSAGE, interval))); plugin.getMessages(), name, MessageKey.REGISTER_MESSAGE, interval)));
service.send(player, MessageKey.UNREGISTERED_SUCCESS); service.send(player, MessageKey.UNREGISTERED_SUCCESS);
ConsoleLogger.info(player.getDisplayName() + " unregistered himself"); ConsoleLogger.info(player.getDisplayName() + " unregistered himself");
return; return;

View File

@ -8,10 +8,8 @@ import fr.xephi.authme.settings.properties.PluginSettings;
import fr.xephi.authme.settings.properties.RegistrationSettings; import fr.xephi.authme.settings.properties.RegistrationSettings;
import fr.xephi.authme.settings.properties.RestrictionSettings; import fr.xephi.authme.settings.properties.RestrictionSettings;
import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.settings.properties.SecuritySettings;
import fr.xephi.authme.util.Wrapper;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -22,8 +20,6 @@ import java.util.regex.Pattern;
*/ */
public final class Settings { public final class Settings {
public static final File PLUGIN_FOLDER = Wrapper.getInstance().getDataFolder();
public static final File CACHE_FOLDER = new File(PLUGIN_FOLDER, "cache");
public static List<String> allowCommands; public static List<String> allowCommands;
public static List<String> getUnrestrictedName; public static List<String> getUnrestrictedName;
public static List<String> getForcedWorlds; public static List<String> getForcedWorlds;

View File

@ -1,10 +1,10 @@
package fr.xephi.authme.task; package fr.xephi.authme.task;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.MessageKey;
import fr.xephi.authme.util.Utils; import fr.xephi.authme.output.Messages;
import fr.xephi.authme.util.BukkitService;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
@ -12,28 +12,27 @@ import org.bukkit.scheduler.BukkitTask;
*/ */
public class MessageTask implements Runnable { public class MessageTask implements Runnable {
private final AuthMe plugin; private final BukkitService bukkitService;
private final String name; private final String name;
private final String[] msg; private final String[] msg;
private final int interval; private final int interval;
/** /*
* Constructor for MessageTask. * Constructor.
*
* @param plugin AuthMe
* @param name String
* @param lines String[]
* @param interval int
*/ */
public MessageTask(AuthMe plugin, String name, String[] lines, int interval) { public MessageTask(BukkitService bukkitService, String name, String[] lines, int interval) {
this.plugin = plugin; this.bukkitService = bukkitService;
this.name = name; this.name = name;
this.msg = lines; this.msg = lines;
this.interval = interval; this.interval = interval;
} }
public MessageTask(AuthMe plugin, String name, MessageKey messageKey, int interval) { /*
this(plugin, name, plugin.getMessages().retrieve(messageKey), interval); * Constructor.
*/
public MessageTask(BukkitService bukkitService, Messages messages, String name, MessageKey messageKey,
int interval) {
this(bukkitService, name, messages.retrieve(messageKey), interval);
} }
@Override @Override
@ -42,12 +41,12 @@ public class MessageTask implements Runnable {
return; return;
} }
for (Player player : Utils.getOnlinePlayers()) { for (Player player : bukkitService.getOnlinePlayers()) {
if (player.getName().equalsIgnoreCase(name)) { if (player.getName().equalsIgnoreCase(name)) {
for (String ms : msg) { for (String ms : msg) {
player.sendMessage(ms); player.sendMessage(ms);
} }
BukkitTask nextTask = plugin.getServer().getScheduler().runTaskLater(plugin, this, interval * 20); BukkitTask nextTask = bukkitService.runTaskLater(this, interval * 20);
if (LimboCache.getInstance().hasLimboPlayer(name)) { if (LimboCache.getInstance().hasLimboPlayer(name)) {
LimboCache.getInstance().getLimboPlayer(name).setMessageTask(nextTask); LimboCache.getInstance().getLimboPlayer(name).setMessageTask(nextTask);
} }

View File

@ -1,11 +1,17 @@
package fr.xephi.authme.util; package fr.xephi.authme.util;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Set; import java.util.Set;
/** /**
@ -19,9 +25,12 @@ public class BukkitService {
public static final int TICKS_PER_MINUTE = 60 * TICKS_PER_SECOND; public static final int TICKS_PER_MINUTE = 60 * TICKS_PER_SECOND;
private final AuthMe authMe; private final AuthMe authMe;
private final boolean getOnlinePlayersIsCollection;
private Method getOnlinePlayers;
public BukkitService(AuthMe authMe) { public BukkitService(AuthMe authMe) {
this.authMe = authMe; this.authMe = authMe;
getOnlinePlayersIsCollection = initializeOnlinePlayersIsCollectionField();
} }
/** /**
@ -61,6 +70,20 @@ public class BukkitService {
return Bukkit.getScheduler().runTask(authMe, task); return Bukkit.getScheduler().runTask(authMe, task);
} }
/**
* Returns a task that will run after the specified number of server
* ticks.
*
* @param task the task to be run
* @param delay the ticks to wait before running the task
* @return a BukkitTask that contains the id number
* @throws IllegalArgumentException if plugin is null
* @throws IllegalArgumentException if task is null
*/
public BukkitTask runTaskLater(Runnable task, long delay) {
return Bukkit.getScheduler().runTaskLater(authMe, task, delay);
}
/** /**
* <b>Asynchronous tasks should never access any API in Bukkit. Great care * <b>Asynchronous tasks should never access any API in Bukkit. Great care
* should be taken to assure the thread-safety of asynchronous tasks.</b> * should be taken to assure the thread-safety of asynchronous tasks.</b>
@ -102,8 +125,60 @@ public class BukkitService {
* @return a set containing banned players * @return a set containing banned players
*/ */
public Set<OfflinePlayer> getBannedPlayers() { public Set<OfflinePlayer> getBannedPlayers() {
Bukkit.getBannedPlayers(); return Bukkit.getBannedPlayers();
return authMe.getServer().getBannedPlayers(); }
/**
* Safe way to retrieve the list of online players from the server. Depending on the
* implementation of the server, either an array of {@link Player} instances is being returned,
* or a Collection. Always use this wrapper to retrieve online players instead of {@link
* Bukkit#getOnlinePlayers()} directly.
*
* @return collection of online players
*
* @see <a href="https://www.spigotmc.org/threads/solved-cant-use-new-getonlineplayers.33061/">SpigotMC
* forum</a>
* @see <a href="http://stackoverflow.com/questions/32130851/player-changed-from-array-to-collection">StackOverflow</a>
*/
@SuppressWarnings("unchecked")
public Collection<? extends Player> getOnlinePlayers() {
if (getOnlinePlayersIsCollection) {
return Bukkit.getOnlinePlayers();
}
try {
// The lookup of a method via Reflections is rather expensive, so we keep a reference to it
if (getOnlinePlayers == null) {
getOnlinePlayers = Bukkit.class.getDeclaredMethod("getOnlinePlayers");
}
Object obj = getOnlinePlayers.invoke(null);
if (obj instanceof Collection<?>) {
return (Collection<? extends Player>) obj;
} else if (obj instanceof Player[]) {
return Arrays.asList((Player[]) obj);
} else {
String type = (obj != null) ? obj.getClass().getName() : "null";
ConsoleLogger.showError("Unknown list of online players of type " + type);
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
ConsoleLogger.logException("Could not retrieve list of online players:", e);
}
return Collections.emptyList();
}
/**
* Method run upon initialization to verify whether or not the Bukkit implementation
* returns the online players as a Collection.
*
* @see #getOnlinePlayers()
*/
private static boolean initializeOnlinePlayersIsCollectionField() {
try {
Method method = Bukkit.class.getDeclaredMethod("getOnlinePlayers");
return method.getReturnType() == Collection.class;
} catch (NoSuchMethodException e) {
ConsoleLogger.showError("Error verifying if getOnlinePlayers is a collection! Method doesn't exist");
}
return false;
} }
} }

View File

@ -1,8 +1,8 @@
package fr.xephi.authme.util; package fr.xephi.authme.util;
import com.maxmind.geoip.LookupService; import com.maxmind.geoip.LookupService;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.settings.Settings;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@ -37,7 +37,8 @@ public class GeoLiteAPI {
if (lookupService != null) { if (lookupService != null) {
return true; return true;
} }
final File data = new File(Settings.PLUGIN_FOLDER, "GeoIP.dat"); final File pluginFolder = AuthMe.getInstance().getDataFolder();
final File data = new File(pluginFolder, "GeoIP.dat");
boolean dataIsOld = (System.currentTimeMillis() - data.lastModified()) > TimeUnit.DAYS.toMillis(30); boolean dataIsOld = (System.currentTimeMillis() - data.lastModified()) > TimeUnit.DAYS.toMillis(30);
if (dataIsOld && !data.delete()) { if (dataIsOld && !data.delete()) {
ConsoleLogger.showError("Failed to delete GeoLiteAPI database"); ConsoleLogger.showError("Failed to delete GeoLiteAPI database");

View File

@ -14,31 +14,16 @@ import org.bukkit.OfflinePlayer;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
/** /**
* Utility class for various operations used in the codebase. * Utility class for various operations used in the codebase.
*/ */
public final class Utils { public final class Utils {
private static AuthMe plugin; private static AuthMe plugin = AuthMe.getInstance();
private static Wrapper wrapper;
private static boolean getOnlinePlayersIsCollection = false;
private static Method getOnlinePlayers;
static {
wrapper = Wrapper.getInstance();
plugin = wrapper.getAuthMe();
initializeOnlinePlayersIsCollectionField();
}
private Utils() { private Utils() {
// Utility class
} }
/** /**
@ -167,12 +152,12 @@ public final class Utils {
final World world = theWorld; final World world = theWorld;
final Location loc = new Location(world, x, y, z); final Location loc = new Location(world, x, y, z);
Bukkit.getScheduler().scheduleSyncDelayedTask(wrapper.getAuthMe(), new Runnable() { Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override @Override
public void run() { public void run() {
AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(pl, loc); AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(pl, loc);
wrapper.getServer().getPluginManager().callEvent(tpEvent); plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
pl.teleport(tpEvent.getTo()); pl.teleport(tpEvent.getTo());
} }
@ -180,58 +165,6 @@ public final class Utils {
}); });
} }
/**
* Safe way to retrieve the list of online players from the server. Depending on the
* implementation of the server, either an array of {@link Player} instances is being returned,
* or a Collection. Always use this wrapper to retrieve online players instead of {@link
* Bukkit#getOnlinePlayers()} directly.
*
* @return collection of online players
*
* @see <a href="https://www.spigotmc.org/threads/solved-cant-use-new-getonlineplayers.33061/">SpigotMC
* forum</a>
* @see <a href="http://stackoverflow.com/questions/32130851/player-changed-from-array-to-collection">StackOverflow</a>
*/
@SuppressWarnings("unchecked")
public static Collection<? extends Player> getOnlinePlayers() {
if (getOnlinePlayersIsCollection) {
return Bukkit.getOnlinePlayers();
}
try {
// The lookup of a method via Reflections is rather expensive, so we keep a reference to it
if (getOnlinePlayers == null) {
getOnlinePlayers = Bukkit.class.getDeclaredMethod("getOnlinePlayers");
}
Object obj = getOnlinePlayers.invoke(null);
if (obj instanceof Collection<?>) {
return (Collection<? extends Player>) obj;
} else if (obj instanceof Player[]) {
return Arrays.asList((Player[]) obj);
} else {
String type = (obj != null) ? obj.getClass().getName() : "null";
ConsoleLogger.showError("Unknown list of online players of type " + type);
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
ConsoleLogger.logException("Could not retrieve list of online players:", e);
}
return Collections.emptyList();
}
/**
* Method run when the Utils class is loaded to verify whether or not the Bukkit implementation
* returns the online players as a Collection.
*
* @see Utils#getOnlinePlayers()
*/
private static void initializeOnlinePlayersIsCollectionField() {
try {
Method method = Bukkit.class.getDeclaredMethod("getOnlinePlayers");
getOnlinePlayersIsCollection = method.getReturnType() == Collection.class;
} catch (NoSuchMethodException e) {
ConsoleLogger.showError("Error verifying if getOnlinePlayers is a collection! Method doesn't exist");
}
}
public static boolean isNPC(Player player) { public static boolean isNPC(Player player) {
return player.hasMetadata("NPC") || plugin.getPluginHooks().isNpcInCombatTagPlus(player); return player.hasMetadata("NPC") || plugin.getPluginHooks().isNpcInCombatTagPlus(player);
} }
@ -240,7 +173,7 @@ public final class Utils {
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
Location spawn = plugin.getSpawnLocation(player); Location spawn = plugin.getSpawnLocation(player);
AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, spawn); AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, spawn);
wrapper.getServer().getPluginManager().callEvent(tpEvent); plugin.getServer().getPluginManager().callEvent(tpEvent);
if (!tpEvent.isCancelled()) { if (!tpEvent.isCancelled()) {
player.teleport(tpEvent.getTo()); player.teleport(tpEvent.getTo());
} }

View File

@ -1,74 +0,0 @@
package fr.xephi.authme.util;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.output.Messages;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.scheduler.BukkitScheduler;
import java.io.File;
/**
* Wrapper for the retrieval of common singletons used throughout the application.
* This class simply delegates the calls.
*/
public class Wrapper {
private static Wrapper singleton;
/**
* Package-private constructor for testing purposes to inject a mock instance.
*/
Wrapper() {
}
/**
* Package-private setter of the singleton field used for tests to inject a mock instance.
*
* @param wrapper The wrapper to use as singleton
*/
static void setSingleton(Wrapper wrapper) {
Wrapper.singleton = wrapper;
}
public static Wrapper getInstance() {
if (singleton == null) {
singleton = new Wrapper();
}
return singleton;
}
public AuthMe getAuthMe() {
return AuthMe.getInstance();
}
public Server getServer() {
return getAuthMe().getServer();
}
public Messages getMessages() {
return getAuthMe().getMessages();
}
public PlayerCache getPlayerCache() {
return PlayerCache.getInstance();
}
/**
* Return the folder containing plugin data via the AuthMe instance.
*
* @return The plugin data folder
* @see AuthMe#getDataFolder()
*/
public File getDataFolder() {
return getAuthMe().getDataFolder();
}
public BukkitScheduler getScheduler() {
return Bukkit.getScheduler();
}
}

View File

@ -10,6 +10,7 @@ import fr.xephi.authme.security.crypts.HashedPassword;
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.SecuritySettings; import fr.xephi.authme.settings.properties.SecuritySettings;
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.junit.Before; import org.junit.Before;
@ -47,11 +48,13 @@ public class ProcessServiceTest {
private SpawnLoader spawnLoader; private SpawnLoader spawnLoader;
@Mock @Mock
private PluginHooks pluginHooks; private PluginHooks pluginHooks;
@Mock
private BukkitService bukkitService;
@Before @Before
public void setUpService() { public void setUpService() {
processService = new ProcessService(settings, messages, authMe, dataSource, passwordSecurity, processService = new ProcessService(settings, messages, authMe, dataSource, passwordSecurity,
pluginHooks, spawnLoader, validationService); pluginHooks, spawnLoader, validationService, bukkitService);
} }
@Test @Test

View File

@ -0,0 +1,66 @@
package fr.xephi.authme.util;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ReflectionTestUtils;
import org.bukkit.entity.Player;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Collection;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
/**
* Test for {@link BukkitService}.
*/
@RunWith(MockitoJUnitRunner.class)
public class BukkitServiceTest {
@Mock
private AuthMe authMe;
/**
* Checks that {@link BukkitService#getOnlinePlayersIsCollection} is initialized to {@code true} on startup;
* the test scope is configured with a Bukkit implementation that returns a Collection and not an array.
*/
@Test
public void shouldHavePlayerListAsCollectionMethod() {
// given
BukkitService bukkitService = new BukkitService(authMe);
// when
boolean doesMethodReturnCollection = (Boolean) ReflectionTestUtils
.getFieldValue(BukkitService.class, bukkitService, "getOnlinePlayersIsCollection");
// then
assertThat(doesMethodReturnCollection, equalTo(true));
}
@Test
public void shouldRetrieveListOfOnlinePlayersFromReflectedMethod() {
// given
BukkitService bukkitService = new BukkitService(authMe);
ReflectionTestUtils.setField(BukkitService.class, bukkitService, "getOnlinePlayersIsCollection", false);
ReflectionTestUtils.setField(BukkitService.class, bukkitService, "getOnlinePlayers",
ReflectionTestUtils.getMethod(BukkitServiceTest.class, "onlinePlayersImpl"));
// when
Collection<? extends Player> players = bukkitService.getOnlinePlayers();
// then
assertThat(players, hasSize(2));
}
// Note: This method is used through reflections
public static Player[] onlinePlayersImpl() {
return new Player[]{
mock(Player.class), mock(Player.class)
};
}
}

View File

@ -1,106 +0,0 @@
package fr.xephi.authme.util;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ReflectionTestUtils;
import fr.xephi.authme.TestHelper;
import fr.xephi.authme.settings.Settings;
import org.bukkit.entity.Player;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import java.util.Collection;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
/**
* Test for the {@link Utils} class.
*/
public class UtilsTest {
private static AuthMe authMeMock;
/**
* The Utils class initializes its fields in a {@code static} block which is only executed once during the JUnit
* tests, too. It is therefore important to initialize the mocks once with {@code @BeforeClass}. Initializing with
* {@code @Before} as we usually do will create mocks that won't have any use in the Utils class.
*/
@BeforeClass
public static void setUpMocks() {
WrapperMock wrapperMock = WrapperMock.createInstance();
authMeMock = wrapperMock.getAuthMe();
TestHelper.setupLogger();
}
@Before
public void setIndirectMocks() {
// Since the mocks aren't set up for each test case it is important to reset them when verifying whether or not
// they have been called. We want to return null for permissions manager once so we initialize a mock for it
// before every test -- this is OK because it is retrieved via authMeMock. It is just crucial that authMeMock
// remain the same object.
reset(authMeMock);
}
@Test
public void shouldNotAddToNormalGroupIfPermissionsAreDisabled() {
// given
Settings.isPermissionCheckEnabled = false;
Player player = mock(Player.class);
// when
boolean result = Utils.addNormal(player, "test_group");
// then
assertThat(result, equalTo(false));
verify(authMeMock, never()).getPermissionsManager();
}
@Test
@Ignore
// TODO ljacqu 20160206: Running this test with all others results in an error
// because Utils is used elsewhere. The AuthMe field is set in a static block
// so creating the WrapperMock here will have no effect
public void shouldNotAddToNormalGroupIfPermManagerIsNull() {
// given
Settings.isPermissionCheckEnabled = true;
given(authMeMock.getPermissionsManager()).willReturn(null);
Player player = mock(Player.class);
// when
boolean result = Utils.addNormal(player, "test_group");
// then
assertThat(result, equalTo(false));
verify(authMeMock).getPermissionsManager();
}
@Test
public void shouldRetrieveListOfOnlinePlayersFromReflectedMethod() {
// given
ReflectionTestUtils.setField(Utils.class, null, "getOnlinePlayersIsCollection", false);
ReflectionTestUtils.setField(Utils.class, null, "getOnlinePlayers",
ReflectionTestUtils.getMethod(UtilsTest.class, "onlinePlayersImpl"));
// when
Collection<? extends Player> players = Utils.getOnlinePlayers();
// then
assertThat(players, hasSize(2));
}
// Note: This method is used through reflections
public static Player[] onlinePlayersImpl() {
return new Player[]{
mock(Player.class), mock(Player.class)
};
}
}

View File

@ -1,90 +0,0 @@
package fr.xephi.authme.util;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.output.Messages;
import org.bukkit.Server;
import org.bukkit.scheduler.BukkitScheduler;
import org.mockito.Mockito;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
* Class returning mocks for all calls in {@link Wrapper}.
* This class keeps track of its mocks and will always return
* the same one for each type.
*/
public class WrapperMock extends Wrapper {
private Map<Class<?>, Object> mocks = new HashMap<>();
private WrapperMock() {
super();
}
/**
* Create a new instance of the WrapperMock and inject it as singleton into the Wrapper class.
*
* @return The created singleton
*/
public static WrapperMock createInstance() {
WrapperMock instance = new WrapperMock();
Wrapper.setSingleton(instance);
return instance;
}
@Override
public Server getServer() {
return getMock(Server.class);
}
@Override
public AuthMe getAuthMe() {
return getMock(AuthMe.class);
}
@Override
public BukkitScheduler getScheduler() {
return getMock(BukkitScheduler.class);
}
@Override
public Messages getMessages() {
return getMock(Messages.class);
}
@Override
public PlayerCache getPlayerCache() {
return getMock(PlayerCache.class);
}
@Override
public File getDataFolder() {
return new File("/");
}
/**
* Return whether a mock of the given class type was created, i.e. verify whether a certain method was executed on
* the Wrapper to retrieve an entity.
*
* @param mockClass The class of the mock to verify
*
* @return True if the mock has been created, false otherwise
*/
public boolean wasMockCalled(Class<?> mockClass) {
return mocks.get(mockClass) != null;
}
private <T> T getMock(Class<T> clazz) {
Object o = mocks.get(clazz);
if (o == null) {
o = Mockito.mock(clazz);
mocks.put(clazz, o);
}
return clazz.cast(o);
}
}