#937 Add option for AuthMe to run in sync

- Create BukkitService#runTaskOptionallyAsync and BukkitService#scheduleSyncTaskFromOptionallyAsyncTask whose behavior depends on a new setting
- Use the new methods where applicable
- Declare events async or sync depending on the new setting
This commit is contained in:
ljacqu 2016-09-18 21:58:14 +02:00
parent ff9f50f63f
commit 4eab258993
20 changed files with 169 additions and 172 deletions

View File

@ -179,11 +179,11 @@ public class AuthMe extends JavaPlugin {
ConsoleLogger.setLogger(getLogger()); ConsoleLogger.setLogger(getLogger());
ConsoleLogger.setLogFile(new File(getDataFolder(), LOG_FILENAME)); ConsoleLogger.setLogFile(new File(getDataFolder(), LOG_FILENAME));
bukkitService = new BukkitService(this); // Load settings and set up the console and console filter
settings = Initializer.createSettings(this);
bukkitService = new BukkitService(this, settings);
Initializer initializer = new Initializer(this, bukkitService); Initializer initializer = new Initializer(this, bukkitService);
// Load settings and set up the console and console filter
settings = initializer.createSettings();
ConsoleLogger.setLoggingOptions(settings); ConsoleLogger.setLoggingOptions(settings);
initializer.setupConsoleFilter(settings, getLogger()); initializer.setupConsoleFilter(settings, getLogger());

View File

@ -55,7 +55,7 @@ public class ChangePasswordAdminCommand implements ExecutableCommand {
// Set the password // Set the password
final String playerNameLowerCase = playerName.toLowerCase(); final String playerNameLowerCase = playerName.toLowerCase();
bukkitService.runTaskAsynchronously(new Runnable() { bukkitService.runTaskOptionallyAsync(new Runnable() {
@Override @Override
public void run() { public void run() {

View File

@ -55,7 +55,7 @@ public class RegisterAdminCommand implements ExecutableCommand {
return; return;
} }
bukkitService.runTaskAsynchronously(new Runnable() { bukkitService.runTaskOptionallyAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -80,7 +80,7 @@ public class RegisterAdminCommand implements ExecutableCommand {
ConsoleLogger.info(sender.getName() + " registered " + playerName); ConsoleLogger.info(sender.getName() + " registered " + playerName);
final Player player = bukkitService.getPlayerExact(playerName); final Player player = bukkitService.getPlayerExact(playerName);
if (player != null) { if (player != null) {
bukkitService.scheduleSyncDelayedTask(new Runnable() { bukkitService.scheduleSyncTaskFromOptionallyAsyncTask(new Runnable() {
@Override @Override
public void run() { public void run() {
limboCache.restoreData(player); limboCache.restoreData(player);

View File

@ -41,7 +41,7 @@ public class SetEmailCommand implements ExecutableCommand {
return; return;
} }
bukkitService.runTaskAsynchronously(new Runnable() { bukkitService.runTaskOptionallyAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
// Validate the user // Validate the user
@ -68,7 +68,6 @@ public class SetEmailCommand implements ExecutableCommand {
// Show a status message // Show a status message
commandService.send(sender, MessageKey.EMAIL_CHANGED_SUCCESS); commandService.send(sender, MessageKey.EMAIL_CHANGED_SUCCESS);
} }
}); });
} }

View File

@ -19,9 +19,10 @@ public class AuthMeAsyncPreLoginEvent extends CustomEvent {
* Constructor. * Constructor.
* *
* @param player The player * @param player The player
* @param isAsync True if the event is async, false otherwise
*/ */
public AuthMeAsyncPreLoginEvent(Player player) { public AuthMeAsyncPreLoginEvent(Player player, boolean isAsync) {
super(true); super(isAsync);
this.player = player; this.player = player;
} }

View File

@ -22,9 +22,10 @@ public class ProtectInventoryEvent extends CustomEvent implements Cancellable {
* Constructor. * Constructor.
* *
* @param player The player * @param player The player
* @param isAsync True if the event is async, false otherwise
*/ */
public ProtectInventoryEvent(Player player) { public ProtectInventoryEvent(Player player, boolean isAsync) {
super(true); super(isAsync);
this.player = player; this.player = player;
this.storedInventory = player.getInventory().getContents(); this.storedInventory = player.getInventory().getContents();
this.storedArmor = player.getInventory().getArmorContents(); this.storedArmor = player.getInventory().getArmorContents();

View File

@ -58,9 +58,10 @@ public class Initializer {
/** /**
* Loads the plugin's settings. * Loads the plugin's settings.
* *
* @return The settings instance, or null if it could not be constructed * @param authMe the plugin instance
* @return the settings instance, or null if it could not be constructed
*/ */
public Settings createSettings() throws Exception { public static Settings createSettings(AuthMe authMe) throws Exception {
File configFile = new File(authMe.getDataFolder(), "config.yml"); File configFile = new File(authMe.getDataFolder(), "config.yml");
PropertyResource resource = new YamlFileResource(configFile); PropertyResource resource = new YamlFileResource(configFile);
SettingsMigrationService migrationService = new SettingsMigrationService(authMe.getDataFolder()); SettingsMigrationService migrationService = new SettingsMigrationService(authMe.getDataFolder());

View File

@ -15,7 +15,9 @@ import org.bukkit.entity.Player;
import javax.inject.Inject; import javax.inject.Inject;
/**
* Performs auth actions, e.g. when a player joins, registers or wants to change his password.
*/
public class Management { public class Management {
@Inject @Inject
@ -41,100 +43,51 @@ public class Management {
@Inject @Inject
private AsyncChangePassword asyncChangePassword; private AsyncChangePassword asyncChangePassword;
Management() { } Management() {
public void performLogin(final Player player, final String password, final boolean forceLogin) {
runTask(new Runnable() {
@Override
public void run() {
asynchronousLogin.login(player, password, forceLogin);
}
});
} }
public void performLogout(final Player player) {
runTask(new Runnable() { public void performLogin(Player player, String password, boolean forceLogin) {
@Override runTask(() -> asynchronousLogin.login(player, password, forceLogin));
public void run() {
asynchronousLogout.logout(player);
}
});
} }
public void performRegister(final Player player, final String password, final String email, final boolean autoLogin) { public void performLogout(Player player) {
runTask(new Runnable() { runTask(() -> asynchronousLogout.logout(player));
@Override
public void run() {
asyncRegister.register(player, password, email, autoLogin);
}
});
} }
public void performUnregister(final Player player, final String password) { public void performRegister(Player player, String password, String email, boolean autoLogin) {
runTask(new Runnable() { runTask(() -> asyncRegister.register(player, password, email, autoLogin));
@Override
public void run() {
asynchronousUnregister.unregister(player, password);
}
});
} }
public void performUnregisterByAdmin(final CommandSender initiator, final String name, final Player player) { public void performUnregister(Player player, String password) {
runTask(new Runnable() { runTask(() -> asynchronousUnregister.unregister(player, password));
@Override
public void run() {
asynchronousUnregister.adminUnregister(initiator, name, player);
}
});
} }
public void performJoin(final Player player) { public void performUnregisterByAdmin(CommandSender initiator, String name, Player player) {
runTask(new Runnable() { runTask(() -> asynchronousUnregister.adminUnregister(initiator, name, player));
@Override
public void run() {
asynchronousJoin.processJoin(player);
}
});
} }
public void performQuit(final Player player) { public void performJoin(Player player) {
runTask(new Runnable() { runTask(() -> asynchronousJoin.processJoin(player));
@Override
public void run() {
asynchronousQuit.processQuit(player);
}
});
} }
public void performAddEmail(final Player player, final String newEmail) { public void performQuit(Player player) {
runTask(new Runnable() { runTask(() -> asynchronousQuit.processQuit(player));
@Override
public void run() {
asyncAddEmail.addEmail(player, newEmail);
}
});
} }
public void performChangeEmail(final Player player, final String oldEmail, final String newEmail) { public void performAddEmail(Player player, String newEmail) {
runTask(new Runnable() { runTask(() -> asyncAddEmail.addEmail(player, newEmail));
@Override
public void run() {
asyncChangeEmail.changeEmail(player, oldEmail, newEmail);
}
});
} }
public void performPasswordChange(final Player player, final String oldPassword, final String newPassword) { public void performChangeEmail(Player player, String oldEmail, String newEmail) {
runTask(new Runnable() { runTask(() -> asyncChangeEmail.changeEmail(player, oldEmail, newEmail));
@Override }
public void run() {
asyncChangePassword.changePassword(player, oldPassword, newPassword); public void performPasswordChange(Player player, String oldPassword, String newPassword) {
} runTask(() -> asyncChangePassword.changePassword(player, oldPassword, newPassword));
});
} }
private void runTask(Runnable runnable) { private void runTask(Runnable runnable) {
bukkitService.runTaskAsynchronously(runnable); bukkitService.runTaskOptionallyAsync(runnable);
} }
} }

View File

@ -36,51 +36,26 @@ public class SyncProcessManager {
public void processSyncEmailRegister(final Player player) { public void processSyncEmailRegister(final Player player) {
runTask(new Runnable() { runTask(() -> processSyncEmailRegister.processEmailRegister(player));
@Override
public void run() {
processSyncEmailRegister.processEmailRegister(player);
}
});
} }
public void processSyncPasswordRegister(final Player player) { public void processSyncPasswordRegister(final Player player) {
runTask(new Runnable() { runTask(() -> processSyncPasswordRegister.processPasswordRegister(player));
@Override
public void run() {
processSyncPasswordRegister.processPasswordRegister(player);
}
});
} }
public void processSyncPlayerLogout(final Player player) { public void processSyncPlayerLogout(final Player player) {
runTask(new Runnable() { runTask(() -> processSynchronousPlayerLogout.processSyncLogout(player));
@Override
public void run() {
processSynchronousPlayerLogout.processSyncLogout(player);
}
});
} }
public void processSyncPlayerLogin(final Player player) { public void processSyncPlayerLogin(final Player player) {
runTask(new Runnable() { runTask(() -> processSyncPlayerLogin.processPlayerLogin(player));
@Override
public void run() {
processSyncPlayerLogin.processPlayerLogin(player);
}
});
} }
public void processSyncPlayerQuit(final Player player) { public void processSyncPlayerQuit(final Player player) {
runTask(new Runnable() { runTask(() -> processSyncronousPlayerQuit.processSyncQuit(player));
@Override
public void run() {
processSyncronousPlayerQuit.processSyncQuit(player);
}
});
} }
private void runTask(Runnable runnable) { private void runTask(Runnable runnable) {
bukkitService.scheduleSyncDelayedTask(runnable); bukkitService.scheduleSyncTaskFromOptionallyAsyncTask(runnable);
} }
} }

View File

@ -91,12 +91,7 @@ public class AsynchronousJoin implements AsynchronousProcess {
if (service.getProperty(RestrictionSettings.FORCE_SURVIVAL_MODE) if (service.getProperty(RestrictionSettings.FORCE_SURVIVAL_MODE)
&& !service.hasPermission(player, PlayerStatePermission.BYPASS_FORCE_SURVIVAL)) { && !service.hasPermission(player, PlayerStatePermission.BYPASS_FORCE_SURVIVAL)) {
bukkitService.runTask(new Runnable() { bukkitService.runTask(() -> player.setGameMode(GameMode.SURVIVAL));
@Override
public void run() {
player.setGameMode(GameMode.SURVIVAL);
}
});
} }
if (service.getProperty(HooksSettings.DISABLE_SOCIAL_SPY)) { if (service.getProperty(HooksSettings.DISABLE_SOCIAL_SPY)) {
@ -104,7 +99,7 @@ public class AsynchronousJoin implements AsynchronousProcess {
} }
if (isNameRestricted(name, ip, player.getAddress().getHostName())) { if (isNameRestricted(name, ip, player.getAddress().getHostName())) {
bukkitService.scheduleSyncDelayedTask(new Runnable() { bukkitService.scheduleSyncTaskFromOptionallyAsyncTask(new Runnable() {
@Override @Override
public void run() { public void run() {
player.kickPlayer(service.retrieveSingleMessage(MessageKey.NOT_OWNER_ERROR)); player.kickPlayer(service.retrieveSingleMessage(MessageKey.NOT_OWNER_ERROR));
@ -129,7 +124,8 @@ public class AsynchronousJoin implements AsynchronousProcess {
// Protect inventory // Protect inventory
if (service.getProperty(PROTECT_INVENTORY_BEFORE_LOGIN)) { if (service.getProperty(PROTECT_INVENTORY_BEFORE_LOGIN)) {
ProtectInventoryEvent ev = new ProtectInventoryEvent(player); final boolean isAsync = service.getProperty(PluginSettings.USE_ASYNC_TASKS);
ProtectInventoryEvent ev = new ProtectInventoryEvent(player, isAsync);
bukkitService.callEvent(ev); bukkitService.callEvent(ev);
if (ev.isCancelled()) { if (ev.isCancelled()) {
player.updateInventory(); player.updateInventory();
@ -144,12 +140,7 @@ public class AsynchronousJoin implements AsynchronousProcess {
playerCache.removePlayer(name); playerCache.removePlayer(name);
if (auth != null && auth.getIp().equals(ip)) { if (auth != null && auth.getIp().equals(ip)) {
service.send(player, MessageKey.SESSION_RECONNECTION); service.send(player, MessageKey.SESSION_RECONNECTION);
bukkitService.runTaskAsynchronously(new Runnable() { bukkitService.runTaskOptionallyAsync(() -> asynchronousLogin.login(player, "dontneed", true));
@Override
public void run() {
asynchronousLogin.login(player, "dontneed", true);
}
});
return; return;
} else if (service.getProperty(PluginSettings.SESSIONS_EXPIRE_ON_IP_CHANGE)) { } else if (service.getProperty(PluginSettings.SESSIONS_EXPIRE_ON_IP_CHANGE)) {
service.send(player, MessageKey.SESSION_EXPIRED); service.send(player, MessageKey.SESSION_EXPIRED);
@ -171,7 +162,7 @@ public class AsynchronousJoin implements AsynchronousProcess {
final int registrationTimeout = service.getProperty(RestrictionSettings.TIMEOUT) * TICKS_PER_SECOND; final int registrationTimeout = service.getProperty(RestrictionSettings.TIMEOUT) * TICKS_PER_SECOND;
bukkitService.scheduleSyncDelayedTask(new Runnable() { bukkitService.scheduleSyncTaskFromOptionallyAsyncTask(new Runnable() {
@Override @Override
public void run() { public void run() {
player.setOp(false); player.setOp(false);
@ -248,7 +239,7 @@ public class AsynchronousJoin implements AsynchronousProcess {
&& !"localhost".equalsIgnoreCase(ip) && !"localhost".equalsIgnoreCase(ip)
&& countOnlinePlayersByIp(ip) > service.getProperty(RestrictionSettings.MAX_JOIN_PER_IP)) { && countOnlinePlayersByIp(ip) > service.getProperty(RestrictionSettings.MAX_JOIN_PER_IP)) {
bukkitService.scheduleSyncDelayedTask(new Runnable() { bukkitService.scheduleSyncTaskFromOptionallyAsyncTask(new Runnable() {
@Override @Override
public void run() { public void run() {
player.kickPlayer(service.retrieveSingleMessage(MessageKey.SAME_IP_ONLINE)); player.kickPlayer(service.retrieveSingleMessage(MessageKey.SAME_IP_ONLINE));

View File

@ -21,6 +21,7 @@ import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.properties.DatabaseSettings; import fr.xephi.authme.settings.properties.DatabaseSettings;
import fr.xephi.authme.settings.properties.EmailSettings; import fr.xephi.authme.settings.properties.EmailSettings;
import fr.xephi.authme.settings.properties.HooksSettings; import fr.xephi.authme.settings.properties.HooksSettings;
import fr.xephi.authme.settings.properties.PluginSettings;
import fr.xephi.authme.settings.properties.RestrictionSettings; import fr.xephi.authme.settings.properties.RestrictionSettings;
import fr.xephi.authme.task.PlayerDataTaskManager; import fr.xephi.authme.task.PlayerDataTaskManager;
import fr.xephi.authme.util.BukkitService; import fr.xephi.authme.util.BukkitService;
@ -110,7 +111,8 @@ public class AsynchronousLogin implements AsynchronousProcess {
} }
} }
AuthMeAsyncPreLoginEvent event = new AuthMeAsyncPreLoginEvent(player); boolean isAsync = service.getProperty(PluginSettings.USE_ASYNC_TASKS);
AuthMeAsyncPreLoginEvent event = new AuthMeAsyncPreLoginEvent(player, isAsync);
bukkitService.callEvent(event); bukkitService.callEvent(event);
if (!event.canLogin()) { if (!event.canLogin()) {
return null; return null;

View File

@ -67,7 +67,8 @@ public class AsyncRegister implements AsynchronousProcess {
private BukkitService bukkitService; private BukkitService bukkitService;
AsyncRegister() { } AsyncRegister() {
}
private boolean preRegisterCheck(Player player, String password) { private boolean preRegisterCheck(Player player, String password) {
final String name = player.getName().toLowerCase(); final String name = player.getName().toLowerCase();
@ -171,12 +172,7 @@ public class AsyncRegister implements AsynchronousProcess {
} }
if (!service.getProperty(RegistrationSettings.FORCE_LOGIN_AFTER_REGISTER) && autoLogin) { if (!service.getProperty(RegistrationSettings.FORCE_LOGIN_AFTER_REGISTER) && autoLogin) {
bukkitService.runTaskAsynchronously(new Runnable(){ bukkitService.runTaskOptionallyAsync(() -> asynchronousLogin.login(player, "dontneed", true));
@Override
public void run() {
asynchronousLogin.login(player, "dontneed", true);
}
});
} }
syncProcessManager.processSyncPasswordRegister(player); syncProcessManager.processSyncPasswordRegister(player);

View File

@ -68,6 +68,13 @@ public class PluginSettings implements SettingsHolder {
public static final Property<LogLevel> LOG_LEVEL = public static final Property<LogLevel> LOG_LEVEL =
newProperty(LogLevel.class, "settings.logLevel", LogLevel.FINE); newProperty(LogLevel.class, "settings.logLevel", LogLevel.FINE);
@Comment({
"By default we schedule async tasks when talking to the database",
"If you want typical communication with the database to happen synchronously, set this to false"
})
public static final Property<Boolean> USE_ASYNC_TASKS =
newProperty("settings.useAsyncTasks", true);
private PluginSettings() { private PluginSettings() {
} }

View File

@ -2,6 +2,9 @@ package fr.xephi.authme.util;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.initialization.SettingsDependent;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.PluginSettings;
import org.bukkit.BanEntry; import org.bukkit.BanEntry;
import org.bukkit.BanList; import org.bukkit.BanList;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -23,9 +26,9 @@ import java.util.Date;
import java.util.Set; import java.util.Set;
/** /**
* Service for operations requiring server entities, such as for scheduling. * Service for operations requiring the Bukkit API, such as for scheduling.
*/ */
public class BukkitService { public class BukkitService implements SettingsDependent {
/** Number of ticks per second in the Bukkit main thread. */ /** Number of ticks per second in the Bukkit main thread. */
public static final int TICKS_PER_SECOND = 20; public static final int TICKS_PER_SECOND = 20;
@ -35,10 +38,12 @@ public class BukkitService {
private final AuthMe authMe; private final AuthMe authMe;
private final boolean getOnlinePlayersIsCollection; private final boolean getOnlinePlayersIsCollection;
private Method getOnlinePlayers; private Method getOnlinePlayers;
private boolean useAsyncTasks;
public BukkitService(AuthMe authMe) { public BukkitService(AuthMe authMe, Settings settings) {
this.authMe = authMe; this.authMe = authMe;
getOnlinePlayersIsCollection = initializeOnlinePlayersIsCollectionField(); getOnlinePlayersIsCollection = initializeOnlinePlayersIsCollectionField();
reload(settings);
} }
/** /**
@ -66,6 +71,21 @@ public class BukkitService {
return Bukkit.getScheduler().scheduleSyncDelayedTask(authMe, task, delay); return Bukkit.getScheduler().scheduleSyncDelayedTask(authMe, task, delay);
} }
/**
* Schedules a synchronous task if async tasks are enabled; if not, it runs the task immediately.
* Use this when {@link #runTaskOptionallyAsync(Runnable) optionally asynchronous tasks} have to
* run something synchronously.
*
* @param task the task to be run
*/
public void scheduleSyncTaskFromOptionallyAsyncTask(Runnable task) {
if (useAsyncTasks) {
scheduleSyncDelayedTask(task);
} else {
task.run();
}
}
/** /**
* Returns a task that will run on the next server tick. * Returns a task that will run on the next server tick.
* *
@ -92,6 +112,20 @@ public class BukkitService {
return Bukkit.getScheduler().runTaskLater(authMe, task, delay); return Bukkit.getScheduler().runTaskLater(authMe, task, delay);
} }
/**
* Schedules this task to run asynchronously or immediately executes it based on
* AuthMe's configuration.
*
* @param task the task to run
*/
public void runTaskOptionallyAsync(Runnable task) {
if (useAsyncTasks) {
runTaskAsynchronously(task);
} else {
task.run();
}
}
/** /**
* <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>
@ -237,6 +271,11 @@ public class BukkitService {
return Bukkit.getWorld(name); return Bukkit.getWorld(name);
} }
@Override
public void reload(Settings settings) {
useAsyncTasks = settings.getProperty(PluginSettings.USE_ASYNC_TASKS);
}
/** /**
* Method run upon initialization to verify whether or not the Bukkit implementation * Method run upon initialization to verify whether or not the Bukkit implementation
* returns the online players as a Collection. * returns the online players as a Collection.

View File

@ -271,6 +271,9 @@ settings:
# FINE for some additional detailed ones (like password failed), # FINE for some additional detailed ones (like password failed),
# and DEBUG for debug messages # and DEBUG for debug messages
logLevel: 'FINE' logLevel: 'FINE'
# By default we schedule async tasks when talking to the database
# If you want typical communication with the database to happen synchronously, set this to false
useAsyncTasks: true
ExternalBoardOptions: ExternalBoardOptions:
# MySQL column for the salt, needed for some forum/cms support # MySQL column for the salt, needed for some forum/cms support
mySQLColumnSalt: '' mySQLColumnSalt: ''

View File

@ -87,6 +87,20 @@ public final class TestHelper {
runnable.run(); runnable.run();
} }
/**
* Execute a {@link Runnable} passed to a mock's {@link BukkitService#runTaskOptionallyAsync} method.
* Note that calling this method expects that there be a runnable sent to the method and will fail
* otherwise.
*
* @param service The mock service
*/
public static void runOptionallyAsyncTask(BukkitService service) {
ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class);
verify(service).runTaskOptionallyAsync(captor.capture());
Runnable runnable = captor.getValue();
runnable.run();
}
/** /**
* Execute a {@link Runnable} passed to a mock's {@link BukkitService#scheduleSyncDelayedTask(Runnable)} * Execute a {@link Runnable} passed to a mock's {@link BukkitService#scheduleSyncDelayedTask(Runnable)}
* method. Note that calling this method expects that there be a runnable sent to the method and will fail * method. Note that calling this method expects that there be a runnable sent to the method and will fail
@ -115,6 +129,20 @@ public final class TestHelper {
runnable.run(); runnable.run();
} }
/**
* Execute a {@link Runnable} passed to a mock's {@link BukkitService#scheduleSyncTaskFromOptionallyAsyncTask}
* method. Note that calling this method expects that there be a runnable sent to the method and will fail
* otherwise.
*
* @param service The mock service
*/
public static void runSyncTaskFromOptionallyAsyncTask(BukkitService service) {
ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class);
verify(service).scheduleSyncTaskFromOptionallyAsyncTask(captor.capture());
Runnable runnable = captor.getValue();
runnable.run();
}
/** /**
* Assign the necessary fields on ConsoleLogger with mocks. * Assign the necessary fields on ConsoleLogger with mocks.
* *

View File

@ -21,7 +21,7 @@ import org.mockito.runners.MockitoJUnitRunner;
import java.util.Arrays; import java.util.Arrays;
import static fr.xephi.authme.TestHelper.runInnerRunnable; import static fr.xephi.authme.TestHelper.runOptionallyAsyncTask;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -89,7 +89,7 @@ public class ChangePasswordAdminCommandTest {
// when // when
command.executeCommand(sender, Arrays.asList(player, password)); command.executeCommand(sender, Arrays.asList(player, password));
runInnerRunnable(bukkitService); runOptionallyAsyncTask(bukkitService);
// then // then
verify(service).send(sender, MessageKey.UNKNOWN_USER); verify(service).send(sender, MessageKey.UNKNOWN_USER);
@ -114,7 +114,7 @@ public class ChangePasswordAdminCommandTest {
// when // when
command.executeCommand(sender, Arrays.asList(player, password)); command.executeCommand(sender, Arrays.asList(player, password));
runInnerRunnable(bukkitService); runOptionallyAsyncTask(bukkitService);
// then // then
verify(validationService).validatePassword(password, player); verify(validationService).validatePassword(password, player);
@ -142,7 +142,7 @@ public class ChangePasswordAdminCommandTest {
// when // when
command.executeCommand(sender, Arrays.asList(player, password)); command.executeCommand(sender, Arrays.asList(player, password));
runInnerRunnable(bukkitService); runOptionallyAsyncTask(bukkitService);
// then // then
verify(validationService).validatePassword(password, player); verify(validationService).validatePassword(password, player);
@ -169,7 +169,7 @@ public class ChangePasswordAdminCommandTest {
// when // when
command.executeCommand(sender, Arrays.asList(player, password)); command.executeCommand(sender, Arrays.asList(player, password));
runInnerRunnable(bukkitService); runOptionallyAsyncTask(bukkitService);
// then // then
verify(validationService).validatePassword(password, player); verify(validationService).validatePassword(password, player);

View File

@ -23,6 +23,7 @@ import org.mockito.runners.MockitoJUnitRunner;
import java.util.Arrays; import java.util.Arrays;
import static fr.xephi.authme.TestHelper.runSyncTaskFromOptionallyAsyncTask;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@ -92,7 +93,7 @@ public class RegisterAdminCommandTest {
// when // when
command.executeCommand(sender, Arrays.asList(user, password)); command.executeCommand(sender, Arrays.asList(user, password));
TestHelper.runInnerRunnable(bukkitService); TestHelper.runOptionallyAsyncTask(bukkitService);
// then // then
verify(validationService).validatePassword(password, user); verify(validationService).validatePassword(password, user);
@ -114,7 +115,7 @@ public class RegisterAdminCommandTest {
// when // when
command.executeCommand(sender, Arrays.asList(user, password)); command.executeCommand(sender, Arrays.asList(user, password));
TestHelper.runInnerRunnable(bukkitService); TestHelper.runOptionallyAsyncTask(bukkitService);
// then // then
verify(validationService).validatePassword(password, user); verify(validationService).validatePassword(password, user);
@ -139,7 +140,7 @@ public class RegisterAdminCommandTest {
// when // when
command.executeCommand(sender, Arrays.asList(user, password)); command.executeCommand(sender, Arrays.asList(user, password));
TestHelper.runInnerRunnable(bukkitService); TestHelper.runOptionallyAsyncTask(bukkitService);
// then // then
verify(validationService).validatePassword(password, user); verify(validationService).validatePassword(password, user);
@ -168,8 +169,8 @@ public class RegisterAdminCommandTest {
// when // when
command.executeCommand(sender, Arrays.asList(user, password)); command.executeCommand(sender, Arrays.asList(user, password));
TestHelper.runInnerRunnable(bukkitService); TestHelper.runOptionallyAsyncTask(bukkitService);
runSyncDelayedTask(bukkitService); runSyncTaskFromOptionallyAsyncTask(bukkitService);
// then // then
verify(validationService).validatePassword(password, user); verify(validationService).validatePassword(password, user);
@ -186,11 +187,4 @@ public class RegisterAdminCommandTest {
assertThat(auth.getNickname(), equalTo(name.toLowerCase())); assertThat(auth.getNickname(), equalTo(name.toLowerCase()));
assertThat(auth.getPassword(), equalTo(hashedPassword)); assertThat(auth.getPassword(), equalTo(hashedPassword));
} }
private static void runSyncDelayedTask(BukkitService bukkitService) {
ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class);
verify(bukkitService).scheduleSyncDelayedTask(captor.capture());
Runnable runnable = captor.getValue();
runnable.run();
}
} }

View File

@ -15,7 +15,7 @@ import org.mockito.runners.MockitoJUnitRunner;
import java.util.Arrays; import java.util.Arrays;
import static fr.xephi.authme.TestHelper.runInnerRunnable; import static fr.xephi.authme.TestHelper.runOptionallyAsyncTask;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -73,7 +73,7 @@ public class SetEmailCommandTest {
// when // when
command.executeCommand(sender, Arrays.asList(user, email)); command.executeCommand(sender, Arrays.asList(user, email));
runInnerRunnable(bukkitService); runOptionallyAsyncTask(bukkitService);
// then // then
verify(commandService).validateEmail(email); verify(commandService).validateEmail(email);
@ -95,7 +95,7 @@ public class SetEmailCommandTest {
// when // when
command.executeCommand(sender, Arrays.asList(user, email)); command.executeCommand(sender, Arrays.asList(user, email));
runInnerRunnable(bukkitService); runOptionallyAsyncTask(bukkitService);
// then // then
verify(commandService).validateEmail(email); verify(commandService).validateEmail(email);
@ -120,7 +120,7 @@ public class SetEmailCommandTest {
// when // when
command.executeCommand(sender, Arrays.asList(user, email)); command.executeCommand(sender, Arrays.asList(user, email));
runInnerRunnable(bukkitService); runOptionallyAsyncTask(bukkitService);
// then // then
verify(commandService).validateEmail(email); verify(commandService).validateEmail(email);
@ -146,7 +146,7 @@ public class SetEmailCommandTest {
// when // when
command.executeCommand(sender, Arrays.asList(user, email)); command.executeCommand(sender, Arrays.asList(user, email));
runInnerRunnable(bukkitService); runOptionallyAsyncTask(bukkitService);
// then // then
verify(commandService).validateEmail(email); verify(commandService).validateEmail(email);
@ -173,7 +173,7 @@ public class SetEmailCommandTest {
// when // when
command.executeCommand(sender, Arrays.asList(user, email)); command.executeCommand(sender, Arrays.asList(user, email));
runInnerRunnable(bukkitService); runOptionallyAsyncTask(bukkitService);
// then // then
verify(commandService).validateEmail(email); verify(commandService).validateEmail(email);

View File

@ -2,6 +2,8 @@ package fr.xephi.authme.util;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.ReflectionTestUtils;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.PluginSettings;
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;
@ -13,6 +15,7 @@ import java.util.Collection;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
/** /**
@ -23,6 +26,8 @@ public class BukkitServiceTest {
@Mock @Mock
private AuthMe authMe; private AuthMe authMe;
@Mock
private Settings settings;
/** /**
* Checks that {@link BukkitService#getOnlinePlayersIsCollection} is initialized to {@code true} on startup; * Checks that {@link BukkitService#getOnlinePlayersIsCollection} is initialized to {@code true} on startup;
@ -31,7 +36,8 @@ public class BukkitServiceTest {
@Test @Test
public void shouldHavePlayerListAsCollectionMethod() { public void shouldHavePlayerListAsCollectionMethod() {
// given // given
BukkitService bukkitService = new BukkitService(authMe); given(settings.getProperty(PluginSettings.USE_ASYNC_TASKS)).willReturn(true);
BukkitService bukkitService = new BukkitService(authMe, settings);
// when // when
boolean doesMethodReturnCollection = ReflectionTestUtils boolean doesMethodReturnCollection = ReflectionTestUtils
@ -44,7 +50,8 @@ public class BukkitServiceTest {
@Test @Test
public void shouldRetrieveListOfOnlinePlayersFromReflectedMethod() { public void shouldRetrieveListOfOnlinePlayersFromReflectedMethod() {
// given // given
BukkitService bukkitService = new BukkitService(authMe); given(settings.getProperty(PluginSettings.USE_ASYNC_TASKS)).willReturn(true);
BukkitService bukkitService = new BukkitService(authMe, settings);
ReflectionTestUtils.setField(BukkitService.class, bukkitService, "getOnlinePlayersIsCollection", false); ReflectionTestUtils.setField(BukkitService.class, bukkitService, "getOnlinePlayersIsCollection", false);
ReflectionTestUtils.setField(BukkitService.class, bukkitService, "getOnlinePlayers", ReflectionTestUtils.setField(BukkitService.class, bukkitService, "getOnlinePlayers",
ReflectionTestUtils.getMethod(BukkitServiceTest.class, "onlinePlayersImpl")); ReflectionTestUtils.getMethod(BukkitServiceTest.class, "onlinePlayersImpl"));