Merge branch 'master' into packet-based-freeze

This commit is contained in:
Gabriele C 2019-08-06 17:40:39 +02:00
commit 063abf45bf
109 changed files with 953 additions and 400 deletions

26
pom.xml
View File

@ -105,6 +105,21 @@
<project.skipExtendedHashTests>true</project.skipExtendedHashTests> <project.skipExtendedHashTests>true</project.skipExtendedHashTests>
</properties> </properties>
</profile> </profile>
<!-- Skip javadoc generation for faster local build -->
<profile>
<id>skipJavadocGeneration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles> </profiles>
<build> <build>
@ -131,6 +146,16 @@
</resource> </resource>
</resources> </resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.1.1</version>
</plugin>
</plugins>
</pluginManagement>
<plugins> <plugins>
<!-- Enforce build environment --> <!-- Enforce build environment -->
<plugin> <plugin>
@ -222,7 +247,6 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
<version>3.1.1</version>
<configuration> <configuration>
<finalName>${project.finalNameBase}</finalName> <finalName>${project.finalNameBase}</finalName>
<!-- In sync with the source/target properties of the maven-compiler-plugin --> <!-- In sync with the source/target properties of the maven-compiler-plugin -->

View File

@ -12,6 +12,7 @@ import fr.xephi.authme.initialization.OnShutdownPlayerSaver;
import fr.xephi.authme.initialization.OnStartupTasks; import fr.xephi.authme.initialization.OnStartupTasks;
import fr.xephi.authme.initialization.SettingsProvider; import fr.xephi.authme.initialization.SettingsProvider;
import fr.xephi.authme.initialization.TaskCloser; import fr.xephi.authme.initialization.TaskCloser;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.listener.BlockListener; import fr.xephi.authme.listener.BlockListener;
import fr.xephi.authme.listener.EntityListener; import fr.xephi.authme.listener.EntityListener;
import fr.xephi.authme.listener.PlayerListener; import fr.xephi.authme.listener.PlayerListener;
@ -56,7 +57,7 @@ public class AuthMe extends JavaPlugin {
private static final String LOG_FILENAME = "authme.log"; private static final String LOG_FILENAME = "authme.log";
private static final int CLEANUP_INTERVAL = 5 * TICKS_PER_MINUTE; private static final int CLEANUP_INTERVAL = 5 * TICKS_PER_MINUTE;
// Default version and build number values // Version and build number values
private static String pluginVersion = "N/D"; private static String pluginVersion = "N/D";
private static String pluginBuildNumber = "Unknown"; private static String pluginBuildNumber = "Unknown";
@ -67,6 +68,7 @@ public class AuthMe extends JavaPlugin {
private BukkitService bukkitService; private BukkitService bukkitService;
private Injector injector; private Injector injector;
private BackupService backupService; private BackupService backupService;
private ConsoleLogger logger;
/** /**
* Constructor. * Constructor.
@ -78,8 +80,7 @@ public class AuthMe extends JavaPlugin {
* Constructor for unit testing. * Constructor for unit testing.
*/ */
@VisibleForTesting @VisibleForTesting
@SuppressWarnings("deprecation") // the super constructor is deprecated to mark it for unit testing only AuthMe(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) {
protected AuthMe(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) {
super(loader, description, dataFolder, file); super(loader, description, dataFolder, file);
} }
@ -120,14 +121,14 @@ public class AuthMe extends JavaPlugin {
// Check server version // Check server version
if (!isClassLoaded("org.bukkit.event.player.PlayerInteractAtEntityEvent")) { if (!isClassLoaded("org.bukkit.event.player.PlayerInteractAtEntityEvent")) {
ConsoleLogger.warning("You are running an unsupported server version! AuthMe requires MC 1.8.X or later!"); getLogger().warning("You are running an unsupported server version! AuthMe requires MC 1.8.X or later!");
stopOrUnload(); stopOrUnload();
return; return;
} }
// Prevent running AuthMeBridge due to major exploit issues // Prevent running AuthMeBridge due to major exploit issues
if (getServer().getPluginManager().isPluginEnabled("AuthMeBridge")) { if (getServer().getPluginManager().isPluginEnabled("AuthMeBridge")) {
ConsoleLogger.warning("Detected AuthMeBridge, support for it has been dropped as it was " getLogger().warning("Detected AuthMeBridge, support for it has been dropped as it was "
+ "causing exploit issues, please use AuthMeBungee instead! Aborting!"); + "causing exploit issues, please use AuthMeBungee instead! Aborting!");
stopOrUnload(); stopOrUnload();
return; return;
@ -139,10 +140,10 @@ public class AuthMe extends JavaPlugin {
} catch (Throwable th) { } catch (Throwable th) {
YamlParseException yamlParseException = ExceptionUtils.findThrowableInCause(YamlParseException.class, th); YamlParseException yamlParseException = ExceptionUtils.findThrowableInCause(YamlParseException.class, th);
if (yamlParseException == null) { if (yamlParseException == null) {
ConsoleLogger.logException("Aborting initialization of AuthMe:", th); logger.logException("Aborting initialization of AuthMe:", th);
th.printStackTrace(); th.printStackTrace();
} else { } else {
ConsoleLogger.logException("File '" + yamlParseException.getFile() + "' contains invalid YAML. " logger.logException("File '" + yamlParseException.getFile() + "' contains invalid YAML. "
+ "Please run its contents through http://yamllint.com", yamlParseException); + "Please run its contents through http://yamllint.com", yamlParseException);
} }
stopOrUnload(); stopOrUnload();
@ -159,8 +160,7 @@ public class AuthMe extends JavaPlugin {
OnStartupTasks.sendMetrics(this, settings); OnStartupTasks.sendMetrics(this, settings);
// Successful message // Successful message
ConsoleLogger.info("AuthMe " + getPluginVersion() + " build n." + getPluginBuildNumber() logger.info("AuthMe " + getPluginVersion() + " build n." + getPluginBuildNumber() + " successfully enabled!");
+ " correctly enabled!");
// Purge on start if enabled // Purge on start if enabled
PurgeService purgeService = injector.getSingleton(PurgeService.class); PurgeService purgeService = injector.getSingleton(PurgeService.class);
@ -192,8 +192,7 @@ public class AuthMe extends JavaPlugin {
*/ */
private void initialize() { private void initialize() {
// Set the Logger instance and log file path // Set the Logger instance and log file path
ConsoleLogger.setLogger(getLogger()); ConsoleLogger.initialize(getLogger(), new File(getDataFolder(), LOG_FILENAME));
ConsoleLogger.setLogFile(new File(getDataFolder(), LOG_FILENAME));
// Check java version // Check java version
if (!SystemUtils.isJavaVersionAtLeast(1.8f)) { if (!SystemUtils.isJavaVersionAtLeast(1.8f)) {
@ -217,8 +216,9 @@ public class AuthMe extends JavaPlugin {
// Get settings and set up logger // Get settings and set up logger
settings = injector.getSingleton(Settings.class); settings = injector.getSingleton(Settings.class);
ConsoleLogger.setLoggingOptions(settings); ConsoleLoggerFactory.reloadSettings(settings);
OnStartupTasks.setupConsoleFilter(settings, getLogger()); logger = ConsoleLoggerFactory.get(AuthMe.class);
OnStartupTasks.setupConsoleFilter(getLogger());
// Set all service fields on the AuthMe class // Set all service fields on the AuthMe class
instantiateServices(injector); instantiateServices(injector);
@ -294,7 +294,7 @@ public class AuthMe extends JavaPlugin {
*/ */
public void stopOrUnload() { public void stopOrUnload() {
if (settings == null || settings.getProperty(SecuritySettings.STOP_SERVER_ON_PROBLEM)) { if (settings == null || settings.getProperty(SecuritySettings.STOP_SERVER_ON_PROBLEM)) {
ConsoleLogger.warning("THE SERVER IS GOING TO SHUT DOWN AS DEFINED IN THE CONFIGURATION!"); getLogger().warning("THE SERVER IS GOING TO SHUT DOWN AS DEFINED IN THE CONFIGURATION!");
setEnabled(false); setEnabled(false);
getServer().shutdown(); getServer().shutdown();
} else { } else {
@ -321,8 +321,8 @@ public class AuthMe extends JavaPlugin {
new TaskCloser(this, database).run(); new TaskCloser(this, database).run();
// Disabled correctly // Disabled correctly
ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " disabled!"); logger.info("AuthMe " + this.getDescription().getVersion() + " disabled!");
ConsoleLogger.close(); ConsoleLogger.closeFileWriter();
} }
/** /**

View File

@ -1,15 +1,19 @@
package fr.xephi.authme; package fr.xephi.authme;
import com.google.common.base.Throwables; import com.google.common.base.Throwables;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.output.LogLevel; import fr.xephi.authme.output.LogLevel;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.PluginSettings;
import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.settings.properties.SecuritySettings;
import fr.xephi.authme.util.ExceptionUtils; import fr.xephi.authme.util.ExceptionUtils;
import java.io.Closeable;
import java.io.File; import java.io.File;
import java.io.FileWriter; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Arrays; import java.util.Arrays;
@ -20,64 +24,73 @@ import java.util.logging.Logger;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
* The plugin's static logger. * AuthMe logger.
*/ */
public final class ConsoleLogger { public final class ConsoleLogger {
private static final String NEW_LINE = System.getProperty("line.separator"); private static final String NEW_LINE = System.getProperty("line.separator");
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("[MM-dd HH:mm:ss]"); private static final DateFormat DATE_FORMAT = new SimpleDateFormat("[MM-dd HH:mm:ss]");
private static Logger logger;
private static LogLevel logLevel = LogLevel.INFO;
private static boolean useLogging = false;
private static File logFile;
private static FileWriter fileWriter;
private ConsoleLogger() { // Outside references
private static File logFile;
private static Logger logger;
// Shared state
private static OutputStreamWriter fileWriter;
// Individual state
private final String name;
private LogLevel logLevel = LogLevel.INFO;
/**
* Constructor.
*
* @param name the name of this logger (the fully qualified class name using it)
*/
public ConsoleLogger(String name) {
this.name = name;
} }
// -------- // --------
// Configurations // Configurations
// -------- // --------
/** public static void initialize(Logger logger, File logFile) {
* Set the logger to use.
*
* @param logger The logger
*/
public static void setLogger(Logger logger) {
ConsoleLogger.logger = logger; ConsoleLogger.logger = logger;
}
/**
* Set the file to log to if enabled.
*
* @param logFile The log file
*/
public static void setLogFile(File logFile) {
ConsoleLogger.logFile = logFile; ConsoleLogger.logFile = logFile;
} }
/** /**
* Load the required settings. * Sets logging settings which are shared by all logger instances.
* *
* @param settings The settings instance * @param settings the settings to read from
*/ */
public static void setLoggingOptions(Settings settings) { public static void initializeSharedSettings(Settings settings) {
ConsoleLogger.logLevel = settings.getProperty(PluginSettings.LOG_LEVEL); boolean useLogging = settings.getProperty(SecuritySettings.USE_LOGGING);
ConsoleLogger.useLogging = settings.getProperty(SecuritySettings.USE_LOGGING);
if (useLogging) { if (useLogging) {
if (fileWriter == null) { initializeFileWriter();
try {
fileWriter = new FileWriter(logFile, true);
} catch (IOException e) {
ConsoleLogger.logException("Failed to create the log file:", e);
}
}
} else { } else {
close(); closeFileWriter();
} }
} }
/**
* Sets logging settings which are individual to all loggers.
*
* @param settings the settings to read from
*/
public void initializeSettings(Settings settings) {
this.logLevel = settings.getProperty(PluginSettings.LOG_LEVEL);
}
public LogLevel getLogLevel() {
return logLevel;
}
public String getName() {
return name;
}
// -------- // --------
// Logging methods // Logging methods
@ -88,7 +101,7 @@ public final class ConsoleLogger {
* *
* @param message The message to log * @param message The message to log
*/ */
public static void warning(String message) { public void warning(String message) {
logger.warning(message); logger.warning(message);
writeLog("[WARN] " + message); writeLog("[WARN] " + message);
} }
@ -100,7 +113,7 @@ public final class ConsoleLogger {
* @param message The message to accompany the exception * @param message The message to accompany the exception
* @param th The Throwable to log * @param th The Throwable to log
*/ */
public static void logException(String message, Throwable th) { public void logException(String message, Throwable th) {
warning(message + " " + ExceptionUtils.formatException(th)); warning(message + " " + ExceptionUtils.formatException(th));
writeLog(Throwables.getStackTraceAsString(th)); writeLog(Throwables.getStackTraceAsString(th));
} }
@ -110,7 +123,7 @@ public final class ConsoleLogger {
* *
* @param message The message to log * @param message The message to log
*/ */
public static void info(String message) { public void info(String message) {
logger.info(message); logger.info(message);
writeLog("[INFO] " + message); writeLog("[INFO] " + message);
} }
@ -123,7 +136,7 @@ public final class ConsoleLogger {
* *
* @param message The message to log * @param message The message to log
*/ */
public static void fine(String message) { public void fine(String message) {
if (logLevel.includes(LogLevel.FINE)) { if (logLevel.includes(LogLevel.FINE)) {
logger.info(message); logger.info(message);
writeLog("[FINE] " + message); writeLog("[FINE] " + message);
@ -142,7 +155,7 @@ public final class ConsoleLogger {
* *
* @param message The message to log * @param message The message to log
*/ */
public static void debug(String message) { public void debug(String message) {
if (logLevel.includes(LogLevel.DEBUG)) { if (logLevel.includes(LogLevel.DEBUG)) {
String debugMessage = "[DEBUG] " + message; String debugMessage = "[DEBUG] " + message;
logger.info(debugMessage); logger.info(debugMessage);
@ -155,7 +168,7 @@ public final class ConsoleLogger {
* *
* @param msgSupplier the message supplier * @param msgSupplier the message supplier
*/ */
public static void debug(Supplier<String> msgSupplier) { public void debug(Supplier<String> msgSupplier) {
if (logLevel.includes(LogLevel.DEBUG)) { if (logLevel.includes(LogLevel.DEBUG)) {
String debugMessage = "[DEBUG] " + msgSupplier.get(); String debugMessage = "[DEBUG] " + msgSupplier.get();
logger.info(debugMessage); logger.info(debugMessage);
@ -169,7 +182,7 @@ public final class ConsoleLogger {
* @param message the message * @param message the message
* @param param1 parameter to replace in the message * @param param1 parameter to replace in the message
*/ */
public static void debug(String message, Object param1) { public void debug(String message, Object param1) {
if (logLevel.includes(LogLevel.DEBUG)) { if (logLevel.includes(LogLevel.DEBUG)) {
String debugMessage = "[DEBUG] " + message; String debugMessage = "[DEBUG] " + message;
logger.log(Level.INFO, debugMessage, param1); logger.log(Level.INFO, debugMessage, param1);
@ -185,7 +198,7 @@ public final class ConsoleLogger {
* @param param2 second param to replace in message * @param param2 second param to replace in message
*/ */
// Avoids array creation if DEBUG level is disabled // Avoids array creation if DEBUG level is disabled
public static void debug(String message, Object param1, Object param2) { public void debug(String message, Object param1, Object param2) {
if (logLevel.includes(LogLevel.DEBUG)) { if (logLevel.includes(LogLevel.DEBUG)) {
debug(message, new Object[]{param1, param2}); debug(message, new Object[]{param1, param2});
} }
@ -197,7 +210,7 @@ public final class ConsoleLogger {
* @param message the message * @param message the message
* @param params the params to replace in the message * @param params the params to replace in the message
*/ */
public static void debug(String message, Object... params) { public void debug(String message, Object... params) {
if (logLevel.includes(LogLevel.DEBUG)) { if (logLevel.includes(LogLevel.DEBUG)) {
String debugMessage = "[DEBUG] " + message; String debugMessage = "[DEBUG] " + message;
logger.log(Level.INFO, debugMessage, params); logger.log(Level.INFO, debugMessage, params);
@ -206,21 +219,21 @@ public final class ConsoleLogger {
} }
} }
// -------- // --------
// Helpers // Helpers
// -------- // --------
/** /**
* Close all file handles. * Closes the file writer.
*/ */
public static void close() { public static void closeFileWriter() {
if (fileWriter != null) { if (fileWriter != null) {
try { try {
fileWriter.flush(); fileWriter.flush();
fileWriter.close();
fileWriter = null;
} catch (IOException ignored) { } catch (IOException ignored) {
} finally {
closeSilently(fileWriter);
fileWriter = null;
} }
} }
} }
@ -231,7 +244,7 @@ public final class ConsoleLogger {
* @param message The message to write to the log * @param message The message to write to the log
*/ */
private static void writeLog(String message) { private static void writeLog(String message) {
if (useLogging) { if (fileWriter != null) {
String dateTime; String dateTime;
synchronized (DATE_FORMAT) { synchronized (DATE_FORMAT) {
dateTime = DATE_FORMAT.format(new Date()); dateTime = DATE_FORMAT.format(new Date());
@ -246,4 +259,31 @@ public final class ConsoleLogger {
} }
} }
} }
private static void closeSilently(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException ignored) {
}
}
}
/**
* Populates the {@link #fileWriter} field if it is null, handling any exceptions that might
* arise during its creation.
*/
private static void initializeFileWriter() {
if (fileWriter == null) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(logFile, true);
fileWriter = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
} catch (Exception e) {
closeSilently(fos);
ConsoleLoggerFactory.get(ConsoleLogger.class)
.logException("Failed to create the log file:", e);
}
}
}
} }

View File

@ -14,6 +14,7 @@ import fr.xephi.authme.datasource.converter.RoyalAuthConverter;
import fr.xephi.authme.datasource.converter.SqliteToSql; import fr.xephi.authme.datasource.converter.SqliteToSql;
import fr.xephi.authme.datasource.converter.VAuthConverter; import fr.xephi.authme.datasource.converter.VAuthConverter;
import fr.xephi.authme.datasource.converter.XAuthConverter; import fr.xephi.authme.datasource.converter.XAuthConverter;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.CommonService;
@ -31,6 +32,8 @@ public class ConverterCommand implements ExecutableCommand {
@VisibleForTesting @VisibleForTesting
static final Map<String, Class<? extends Converter>> CONVERTERS = getConverters(); static final Map<String, Class<? extends Converter>> CONVERTERS = getConverters();
private final ConsoleLogger logger = ConsoleLoggerFactory.get(ConverterCommand.class);
@Inject @Inject
private CommonService commonService; private CommonService commonService;
@ -59,7 +62,7 @@ public class ConverterCommand implements ExecutableCommand {
converter.execute(sender); converter.execute(sender);
} catch (Exception e) { } catch (Exception e) {
commonService.send(sender, MessageKey.ERROR); commonService.send(sender, MessageKey.ERROR);
ConsoleLogger.logException("Error during conversion:", e); logger.logException("Error during conversion:", e);
} }
} }
}); });

View File

@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.security.crypts.HashedPassword; import fr.xephi.authme.security.crypts.HashedPassword;
@ -22,6 +23,8 @@ import java.util.List;
*/ */
public class RegisterAdminCommand implements ExecutableCommand { public class RegisterAdminCommand implements ExecutableCommand {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(RegisterAdminCommand.class);
@Inject @Inject
private PasswordSecurity passwordSecurity; private PasswordSecurity passwordSecurity;
@ -70,7 +73,7 @@ public class RegisterAdminCommand implements ExecutableCommand {
} }
commonService.send(sender, MessageKey.REGISTER_SUCCESS); commonService.send(sender, MessageKey.REGISTER_SUCCESS);
ConsoleLogger.info(sender.getName() + " registered " + playerName); logger.info(sender.getName() + " registered " + playerName);
final Player player = bukkitService.getPlayerExact(playerName); final Player player = bukkitService.getPlayerExact(playerName);
if (player != null) { if (player != null) {
bukkitService.scheduleSyncTaskFromOptionallyAsyncTask(() -> bukkitService.scheduleSyncTaskFromOptionallyAsyncTask(() ->

View File

@ -7,6 +7,7 @@ import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.initialization.Reloadable; import fr.xephi.authme.initialization.Reloadable;
import fr.xephi.authme.initialization.SettingsDependent; import fr.xephi.authme.initialization.SettingsDependent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.CommonService;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
@ -23,6 +24,8 @@ import java.util.List;
*/ */
public class ReloadCommand implements ExecutableCommand { public class ReloadCommand implements ExecutableCommand {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(ReloadCommand.class);
@Inject @Inject
private AuthMe plugin; private AuthMe plugin;
@ -48,7 +51,7 @@ public class ReloadCommand implements ExecutableCommand {
public void executeCommand(CommandSender sender, List<String> arguments) { public void executeCommand(CommandSender sender, List<String> arguments) {
try { try {
settings.reload(); settings.reload();
ConsoleLogger.setLoggingOptions(settings); ConsoleLoggerFactory.reloadSettings(settings);
settingsWarner.logWarningsForMisconfigurations(); settingsWarner.logWarningsForMisconfigurations();
// We do not change database type for consistency issues, but we'll output a note in the logs // We do not change database type for consistency issues, but we'll output a note in the logs
@ -59,7 +62,7 @@ public class ReloadCommand implements ExecutableCommand {
commonService.send(sender, MessageKey.CONFIG_RELOAD_SUCCESS); commonService.send(sender, MessageKey.CONFIG_RELOAD_SUCCESS);
} catch (Exception e) { } catch (Exception e) {
sender.sendMessage("Error occurred during reload of AuthMe: aborting"); sender.sendMessage("Error occurred during reload of AuthMe: aborting");
ConsoleLogger.logException("Aborting! Encountered exception during reload of AuthMe:", e); logger.logException("Aborting! Encountered exception during reload of AuthMe:", e);
plugin.stopOrUnload(); plugin.stopOrUnload();
} }
} }

View File

@ -6,6 +6,7 @@ import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.message.Messages; import fr.xephi.authme.message.Messages;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.BukkitService;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -19,6 +20,8 @@ import java.util.List;
*/ */
public class TotpDisableAdminCommand implements ExecutableCommand { public class TotpDisableAdminCommand implements ExecutableCommand {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(TotpDisableAdminCommand.class);
@Inject @Inject
private DataSource dataSource; private DataSource dataSource;
@ -45,7 +48,7 @@ public class TotpDisableAdminCommand implements ExecutableCommand {
private void removeTotpKey(CommandSender sender, String player) { private void removeTotpKey(CommandSender sender, String player) {
if (dataSource.removeTotpKey(player)) { if (dataSource.removeTotpKey(player)) {
sender.sendMessage("Disabled two-factor authentication successfully for '" + player + "'"); sender.sendMessage("Disabled two-factor authentication successfully for '" + player + "'");
ConsoleLogger.info(sender.getName() + " disable two-factor authentication for '" + player + "'"); logger.info(sender.getName() + " disable two-factor authentication for '" + player + "'");
Player onlinePlayer = bukkitService.getPlayerExact(player); Player onlinePlayer = bukkitService.getPlayerExact(player);
if (onlinePlayer != null) { if (onlinePlayer != null) {

View File

@ -3,6 +3,7 @@ package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.command.help.HelpMessagesService; import fr.xephi.authme.command.help.HelpMessagesService;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.service.HelpTranslationGenerator; import fr.xephi.authme.service.HelpTranslationGenerator;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -17,6 +18,8 @@ import java.util.List;
*/ */
public class UpdateHelpMessagesCommand implements ExecutableCommand { public class UpdateHelpMessagesCommand implements ExecutableCommand {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(UpdateHelpMessagesCommand.class);
@Inject @Inject
private HelpTranslationGenerator helpTranslationGenerator; private HelpTranslationGenerator helpTranslationGenerator;
@Inject @Inject
@ -30,7 +33,7 @@ public class UpdateHelpMessagesCommand implements ExecutableCommand {
helpMessagesService.reloadMessagesFile(); helpMessagesService.reloadMessagesFile();
} catch (IOException e) { } catch (IOException e) {
sender.sendMessage("Could not update help file: " + e.getMessage()); sender.sendMessage("Could not update help file: " + e.getMessage());
ConsoleLogger.logException("Could not update help file:", e); logger.logException("Could not update help file:", e);
} }
} }
} }

View File

@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.limbo.LimboService; import fr.xephi.authme.data.limbo.LimboService;
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.output.ConsoleLoggerFactory;
import org.bukkit.Location; import org.bukkit.Location;
import java.lang.reflect.Field; import java.lang.reflect.Field;
@ -19,6 +20,7 @@ import java.util.function.Function;
*/ */
final class DebugSectionUtils { final class DebugSectionUtils {
private static ConsoleLogger logger = ConsoleLoggerFactory.get(DebugSectionUtils.class);
private static Field limboEntriesField; private static Field limboEntriesField;
private DebugSectionUtils() { private DebugSectionUtils() {
@ -72,7 +74,7 @@ final class DebugSectionUtils {
field.setAccessible(true); field.setAccessible(true);
limboEntriesField = field; limboEntriesField = field;
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.logException("Could not retrieve LimboService entries field:", e); logger.logException("Could not retrieve LimboService entries field:", e);
} }
} }
return limboEntriesField; return limboEntriesField;
@ -95,7 +97,7 @@ final class DebugSectionUtils {
try { try {
return function.apply((Map) limboEntriesField.get(limboService)); return function.apply((Map) limboEntriesField.get(limboService));
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.logException("Could not retrieve LimboService values:", e); logger.logException("Could not retrieve LimboService values:", e);
} }
} }
return null; return null;
@ -119,7 +121,7 @@ final class DebugSectionUtils {
source.setAccessible(true); source.setAccessible(true);
return (DataSource) source.get(dataSource); return (DataSource) source.get(dataSource);
} catch (NoSuchFieldException | IllegalAccessException e) { } catch (NoSuchFieldException | IllegalAccessException e) {
ConsoleLogger.logException("Could not get source of CacheDataSource:", e); logger.logException("Could not get source of CacheDataSource:", e);
return null; return null;
} }
} }

View File

@ -5,6 +5,7 @@ import com.google.common.annotations.VisibleForTesting;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.datasource.MySQL; import fr.xephi.authme.datasource.MySQL;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.permission.DebugSectionPermissions; import fr.xephi.authme.permission.DebugSectionPermissions;
import fr.xephi.authme.permission.PermissionNode; import fr.xephi.authme.permission.PermissionNode;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
@ -43,6 +44,8 @@ class MySqlDefaultChanger implements DebugSection {
private static final String NOT_NULL_SUFFIX = ChatColor.DARK_AQUA + "@" + ChatColor.RESET; private static final String NOT_NULL_SUFFIX = ChatColor.DARK_AQUA + "@" + ChatColor.RESET;
private static final String DEFAULT_VALUE_SUFFIX = ChatColor.GOLD + "#" + ChatColor.RESET; private static final String DEFAULT_VALUE_SUFFIX = ChatColor.GOLD + "#" + ChatColor.RESET;
private ConsoleLogger logger = ConsoleLoggerFactory.get(MySqlDefaultChanger.class);
@Inject @Inject
private Settings settings; private Settings settings;
@ -98,7 +101,7 @@ class MySqlDefaultChanger implements DebugSection {
throw new IllegalStateException("Unknown operation '" + operation + "'"); throw new IllegalStateException("Unknown operation '" + operation + "'");
} }
} catch (SQLException | IllegalStateException e) { } catch (SQLException | IllegalStateException e) {
ConsoleLogger.logException("Failed to perform MySQL default altering operation:", e); logger.logException("Failed to perform MySQL default altering operation:", e);
} }
} }
} }
@ -134,7 +137,7 @@ class MySqlDefaultChanger implements DebugSection {
} }
// Log success message // Log success message
ConsoleLogger.info("Changed MySQL column '" + columnName + "' to be NOT NULL, as initiated by '" logger.info("Changed MySQL column '" + columnName + "' to be NOT NULL, as initiated by '"
+ sender.getName() + "'"); + sender.getName() + "'");
} }
@ -168,7 +171,7 @@ class MySqlDefaultChanger implements DebugSection {
+ "') to be NULL, modifying " + updatedRows + " entries"); + "') to be NULL, modifying " + updatedRows + " entries");
// Log success message // Log success message
ConsoleLogger.info("Changed MySQL column '" + columnName + "' to allow NULL, as initiated by '" logger.info("Changed MySQL column '" + columnName + "' to allow NULL, as initiated by '"
+ sender.getName() + "'"); + sender.getName() + "'");
} }
@ -191,7 +194,7 @@ class MySqlDefaultChanger implements DebugSection {
+ " (" + columnName + "): " + isNullText + ", " + defaultText); + " (" + columnName + "): " + isNullText + ", " + defaultText);
} }
} catch (SQLException e) { } catch (SQLException e) {
ConsoleLogger.logException("Failed while showing column details:", e); logger.logException("Failed while showing column details:", e);
sender.sendMessage("Failed while showing column details. See log for info"); sender.sendMessage("Failed while showing column details. See log for info");
} }
@ -228,7 +231,7 @@ class MySqlDefaultChanger implements DebugSection {
} }
return String.join(ChatColor.RESET + ", ", formattedColumns); return String.join(ChatColor.RESET + ", ", formattedColumns);
} catch (SQLException e) { } catch (SQLException e) {
ConsoleLogger.logException("Failed to construct column list:", e); logger.logException("Failed to construct column list:", e);
return ChatColor.RED + "An error occurred! Please see the console for details."; return ChatColor.RED + "An error occurred! Please see the console for details.";
} }
} }

View File

@ -3,6 +3,7 @@ package fr.xephi.authme.command.executable.authme.debug;
import ch.jalu.datasourcecolumns.data.DataSourceValue; import ch.jalu.datasourcecolumns.data.DataSourceValue;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.mail.SendMailSsl; import fr.xephi.authme.mail.SendMailSsl;
import fr.xephi.authme.permission.DebugSectionPermissions; import fr.xephi.authme.permission.DebugSectionPermissions;
import fr.xephi.authme.permission.PermissionNode; import fr.xephi.authme.permission.PermissionNode;
@ -22,6 +23,8 @@ import java.util.List;
*/ */
class TestEmailSender implements DebugSection { class TestEmailSender implements DebugSection {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(TestEmailSender.class);
@Inject @Inject
private DataSource dataSource; private DataSource dataSource;
@ -110,7 +113,7 @@ class TestEmailSender implements DebugSection {
try { try {
htmlEmail = sendMailSsl.initializeMail(email); htmlEmail = sendMailSsl.initializeMail(email);
} catch (EmailException e) { } catch (EmailException e) {
ConsoleLogger.logException("Failed to create email for sample email:", e); logger.logException("Failed to create email for sample email:", e);
return false; return false;
} }

View File

@ -3,6 +3,7 @@ package fr.xephi.authme.command.executable.email;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.security.crypts.HashedPassword; import fr.xephi.authme.security.crypts.HashedPassword;
@ -20,6 +21,8 @@ import java.util.List;
*/ */
public class EmailSetPasswordCommand extends PlayerCommand { public class EmailSetPasswordCommand extends PlayerCommand {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(EmailSetPasswordCommand.class);
@Inject @Inject
private DataSource dataSource; private DataSource dataSource;
@ -46,7 +49,7 @@ public class EmailSetPasswordCommand extends PlayerCommand {
HashedPassword hashedPassword = passwordSecurity.computeHash(password, name); HashedPassword hashedPassword = passwordSecurity.computeHash(password, name);
dataSource.updatePassword(name, hashedPassword); dataSource.updatePassword(name, hashedPassword);
recoveryService.removeFromSuccessfulRecovery(player); recoveryService.removeFromSuccessfulRecovery(player);
ConsoleLogger.info("Player '" + name + "' has changed their password from recovery"); logger.info("Player '" + name + "' has changed their password from recovery");
commonService.send(player, MessageKey.PASSWORD_CHANGED_SUCCESS); commonService.send(player, MessageKey.PASSWORD_CHANGED_SUCCESS);
} else { } else {
commonService.send(player, result.getMessageKey(), result.getArgs()); commonService.send(player, result.getMessageKey(), result.getArgs());

View File

@ -5,6 +5,7 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.mail.EmailService; import fr.xephi.authme.mail.EmailService;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.BukkitService;
@ -22,6 +23,8 @@ import java.util.List;
*/ */
public class RecoverEmailCommand extends PlayerCommand { public class RecoverEmailCommand extends PlayerCommand {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(RecoverEmailCommand.class);
@Inject @Inject
private CommonService commonService; private CommonService commonService;
@ -49,7 +52,7 @@ public class RecoverEmailCommand extends PlayerCommand {
final String playerName = player.getName(); final String playerName = player.getName();
if (!emailService.hasAllInformation()) { if (!emailService.hasAllInformation()) {
ConsoleLogger.warning("Mail API is not set"); logger.warning("Mail API is not set");
commonService.send(player, MessageKey.INCOMPLETE_EMAIL_SETTINGS); commonService.send(player, MessageKey.INCOMPLETE_EMAIL_SETTINGS);
return; return;
} }

View File

@ -3,6 +3,7 @@ package fr.xephi.authme.command.executable.register;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.data.captcha.RegistrationCaptchaManager; import fr.xephi.authme.data.captcha.RegistrationCaptchaManager;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.mail.EmailService; import fr.xephi.authme.mail.EmailService;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.process.Management; import fr.xephi.authme.process.Management;
@ -34,6 +35,8 @@ import static fr.xephi.authme.settings.properties.RegistrationSettings.REGISTER_
*/ */
public class RegisterCommand extends PlayerCommand { public class RegisterCommand extends PlayerCommand {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(RegisterCommand.class);
@Inject @Inject
private Management management; private Management management;
@ -155,7 +158,7 @@ public class RegisterCommand extends PlayerCommand {
private void handleEmailRegistration(Player player, List<String> arguments) { private void handleEmailRegistration(Player player, List<String> arguments) {
if (!emailService.hasAllInformation()) { if (!emailService.hasAllInformation()) {
commonService.send(player, MessageKey.INCOMPLETE_EMAIL_SETTINGS); commonService.send(player, MessageKey.INCOMPLETE_EMAIL_SETTINGS);
ConsoleLogger.warning("Cannot register player '" + player.getName() + "': no email or password is set " logger.warning("Cannot register player '" + player.getName() + "': no email or password is set "
+ "to send emails from. Please adjust your config at " + EmailSettings.MAIL_ACCOUNT.getPath()); + "to send emails from. Please adjust your config at " + EmailSettings.MAIL_ACCOUNT.getPath());
return; return;
} }

View File

@ -5,6 +5,7 @@ import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.message.Messages; import fr.xephi.authme.message.Messages;
import fr.xephi.authme.security.totp.GenerateTotpService; import fr.xephi.authme.security.totp.GenerateTotpService;
@ -19,6 +20,8 @@ import java.util.List;
*/ */
public class ConfirmTotpCommand extends PlayerCommand { public class ConfirmTotpCommand extends PlayerCommand {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(ConfirmTotpCommand.class);
@Inject @Inject
private GenerateTotpService generateTotpService; private GenerateTotpService generateTotpService;
@ -63,7 +66,7 @@ public class ConfirmTotpCommand extends PlayerCommand {
messages.send(player, MessageKey.TWO_FACTOR_ENABLE_SUCCESS); messages.send(player, MessageKey.TWO_FACTOR_ENABLE_SUCCESS);
auth.setTotpKey(totpDetails.getTotpKey()); auth.setTotpKey(totpDetails.getTotpKey());
playerCache.updatePlayer(auth); playerCache.updatePlayer(auth);
ConsoleLogger.info("Player '" + player.getName() + "' has successfully added a TOTP key to their account"); logger.info("Player '" + player.getName() + "' has successfully added a TOTP key to their account");
} else { } else {
messages.send(player, MessageKey.ERROR); messages.send(player, MessageKey.ERROR);
} }

View File

@ -5,6 +5,7 @@ import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.message.Messages; import fr.xephi.authme.message.Messages;
import fr.xephi.authme.security.totp.TotpAuthenticator; import fr.xephi.authme.security.totp.TotpAuthenticator;
@ -18,6 +19,8 @@ import java.util.List;
*/ */
public class RemoveTotpCommand extends PlayerCommand { public class RemoveTotpCommand extends PlayerCommand {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(RemoveTotpCommand.class);
@Inject @Inject
private DataSource dataSource; private DataSource dataSource;
@ -51,7 +54,7 @@ public class RemoveTotpCommand extends PlayerCommand {
auth.setTotpKey(null); auth.setTotpKey(null);
playerCache.updatePlayer(auth); playerCache.updatePlayer(auth);
messages.send(player, MessageKey.TWO_FACTOR_REMOVED_SUCCESS); messages.send(player, MessageKey.TWO_FACTOR_REMOVED_SUCCESS);
ConsoleLogger.info("Player '" + player.getName() + "' removed their TOTP key"); logger.info("Player '" + player.getName() + "' removed their TOTP key");
} else { } else {
messages.send(player, MessageKey.ERROR); messages.send(player, MessageKey.ERROR);
} }

View File

@ -8,6 +8,7 @@ import fr.xephi.authme.data.limbo.LimboPlayer;
import fr.xephi.authme.data.limbo.LimboPlayerState; import fr.xephi.authme.data.limbo.LimboPlayerState;
import fr.xephi.authme.data.limbo.LimboService; import fr.xephi.authme.data.limbo.LimboService;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.message.Messages; import fr.xephi.authme.message.Messages;
import fr.xephi.authme.process.login.AsynchronousLogin; import fr.xephi.authme.process.login.AsynchronousLogin;
@ -22,6 +23,8 @@ import java.util.List;
*/ */
public class TotpCodeCommand extends PlayerCommand { public class TotpCodeCommand extends PlayerCommand {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(TotpCodeCommand.class);
@Inject @Inject
private LimboService limboService; private LimboService limboService;
@ -57,7 +60,7 @@ public class TotpCodeCommand extends PlayerCommand {
if (limbo != null && limbo.getState() == LimboPlayerState.TOTP_REQUIRED) { if (limbo != null && limbo.getState() == LimboPlayerState.TOTP_REQUIRED) {
processCode(player, auth, arguments.get(0)); processCode(player, auth, arguments.get(0));
} else { } else {
ConsoleLogger.debug(() -> "Aborting TOTP check for player '" + player.getName() logger.debug(() -> "Aborting TOTP check for player '" + player.getName()
+ "'. Invalid limbo state: " + (limbo == null ? "no limbo" : limbo.getState())); + "'. Invalid limbo state: " + (limbo == null ? "no limbo" : limbo.getState()));
messages.send(player, MessageKey.LOGIN_MESSAGE); messages.send(player, MessageKey.LOGIN_MESSAGE);
} }
@ -66,10 +69,10 @@ public class TotpCodeCommand extends PlayerCommand {
private void processCode(Player player, PlayerAuth auth, String inputCode) { private void processCode(Player player, PlayerAuth auth, String inputCode) {
boolean isCodeValid = totpAuthenticator.checkCode(auth, inputCode); boolean isCodeValid = totpAuthenticator.checkCode(auth, inputCode);
if (isCodeValid) { if (isCodeValid) {
ConsoleLogger.debug("Successfully checked TOTP code for `{0}`", player.getName()); logger.debug("Successfully checked TOTP code for `{0}`", player.getName());
asynchronousLogin.performLogin(player, auth); asynchronousLogin.performLogin(player, auth);
} else { } else {
ConsoleLogger.debug("Input TOTP code was invalid for player `{0}`", player.getName()); logger.debug("Input TOTP code was invalid for player `{0}`", player.getName());
messages.send(player, MessageKey.TWO_FACTOR_INVALID_CODE); messages.send(player, MessageKey.TWO_FACTOR_INVALID_CODE);
} }
} }

View File

@ -3,6 +3,7 @@ package fr.xephi.authme.command.executable.verification;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.data.VerificationCodeManager; import fr.xephi.authme.data.VerificationCodeManager;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.CommonService;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -15,6 +16,8 @@ import java.util.List;
*/ */
public class VerificationCommand extends PlayerCommand { public class VerificationCommand extends PlayerCommand {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(VerificationCommand.class);
@Inject @Inject
private CommonService commonService; private CommonService commonService;
@ -26,7 +29,7 @@ public class VerificationCommand extends PlayerCommand {
final String playerName = player.getName(); final String playerName = player.getName();
if (!codeManager.canSendMail()) { if (!codeManager.canSendMail()) {
ConsoleLogger.warning("Mail API is not set"); logger.warning("Mail API is not set");
commonService.send(player, MessageKey.INCOMPLETE_EMAIL_SETTINGS); commonService.send(player, MessageKey.INCOMPLETE_EMAIL_SETTINGS);
return; return;
} }

View File

@ -5,6 +5,7 @@ import org.bukkit.Location;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.UUID;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
@ -40,6 +41,7 @@ public class PlayerAuth {
private String world; private String world;
private float yaw; private float yaw;
private float pitch; private float pitch;
private UUID uuid;
/** /**
* Hidden constructor. * Hidden constructor.
@ -169,6 +171,14 @@ public class PlayerAuth {
this.totpKey = totpKey; this.totpKey = totpKey;
} }
public UUID getUuid() {
return uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (!(obj instanceof PlayerAuth)) { if (!(obj instanceof PlayerAuth)) {
@ -193,7 +203,8 @@ public class PlayerAuth {
+ " ! LastLogin : " + lastLogin + " ! LastLogin : " + lastLogin
+ " ! LastPosition : " + x + "," + y + "," + z + "," + world + " ! LastPosition : " + x + "," + y + "," + z + "," + world
+ " ! Email : " + email + " ! Email : " + email
+ " ! Password : {" + password.getHash() + ", " + password.getSalt() + "}"; + " ! Password : {" + password.getHash() + ", " + password.getSalt() + "}"
+ " ! UUID : " + uuid;
} }
public static Builder builder() { public static Builder builder() {
@ -218,6 +229,7 @@ public class PlayerAuth {
private String world; private String world;
private float yaw; private float yaw;
private float pitch; private float pitch;
private UUID uuid;
/** /**
* Creates a PlayerAuth object. * Creates a PlayerAuth object.
@ -243,6 +255,7 @@ public class PlayerAuth {
auth.world = Optional.ofNullable(world).orElse("world"); auth.world = Optional.ofNullable(world).orElse("world");
auth.yaw = yaw; auth.yaw = yaw;
auth.pitch = pitch; auth.pitch = pitch;
auth.uuid = uuid;
return auth; return auth;
} }
@ -349,5 +362,10 @@ public class PlayerAuth {
this.registrationDate = date; this.registrationDate = date;
return this; return this;
} }
public Builder uuid(UUID uuid) {
this.uuid = uuid;
return this;
}
} }
} }

View File

@ -2,6 +2,7 @@ package fr.xephi.authme.data.limbo;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.initialization.Reloadable; import fr.xephi.authme.initialization.Reloadable;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.PluginSettings;
@ -26,6 +27,8 @@ import java.util.Collections;
*/ */
class AuthGroupHandler implements Reloadable { class AuthGroupHandler implements Reloadable {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(AuthGroupHandler.class);
@Inject @Inject
private PermissionsManager permissionsManager; private PermissionsManager permissionsManager;
@ -78,7 +81,7 @@ class AuthGroupHandler implements Reloadable {
throw new IllegalStateException("Encountered unhandled auth group type '" + groupType + "'"); throw new IllegalStateException("Encountered unhandled auth group type '" + groupType + "'");
} }
ConsoleLogger.debug(() -> player.getName() + " changed to " logger.debug(() -> player.getName() + " changed to "
+ groupType + ": has groups " + permissionsManager.getGroups(player)); + groupType + ": has groups " + permissionsManager.getGroups(player));
} }
@ -95,7 +98,7 @@ class AuthGroupHandler implements Reloadable {
// Make sure group support is available // Make sure group support is available
if (!permissionsManager.hasGroupSupport()) { if (!permissionsManager.hasGroupSupport()) {
ConsoleLogger.warning("The current permissions system doesn't have group support, unable to set group!"); logger.warning("The current permissions system doesn't have group support, unable to set group!");
return false; return false;
} }
return true; return true;

View File

@ -2,6 +2,7 @@ package fr.xephi.authme.data.limbo;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.limbo.persistence.LimboPersistence; import fr.xephi.authme.data.limbo.persistence.LimboPersistence;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.SpawnLoader; import fr.xephi.authme.settings.SpawnLoader;
import org.bukkit.Location; import org.bukkit.Location;
@ -20,6 +21,8 @@ import static fr.xephi.authme.settings.properties.LimboSettings.RESTORE_ALLOW_FL
*/ */
public class LimboService { public class LimboService {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(LimboService.class);
private final Map<String, LimboPlayer> entries = new ConcurrentHashMap<>(); private final Map<String, LimboPlayer> entries = new ConcurrentHashMap<>();
@Inject @Inject
@ -54,13 +57,13 @@ public class LimboService {
LimboPlayer limboFromDisk = persistence.getLimboPlayer(player); LimboPlayer limboFromDisk = persistence.getLimboPlayer(player);
if (limboFromDisk != null) { if (limboFromDisk != null) {
ConsoleLogger.debug("LimboPlayer for `{0}` already exists on disk", name); logger.debug("LimboPlayer for `{0}` already exists on disk", name);
} }
LimboPlayer existingLimbo = entries.remove(name); LimboPlayer existingLimbo = entries.remove(name);
if (existingLimbo != null) { if (existingLimbo != null) {
existingLimbo.clearTasks(); existingLimbo.clearTasks();
ConsoleLogger.debug("LimboPlayer for `{0}` already present in memory", name); logger.debug("LimboPlayer for `{0}` already present in memory", name);
} }
Location location = spawnLoader.getPlayerLocationOrSpawn(player); Location location = spawnLoader.getPlayerLocationOrSpawn(player);
@ -110,12 +113,12 @@ public class LimboService {
LimboPlayer limbo = entries.remove(lowerName); LimboPlayer limbo = entries.remove(lowerName);
if (limbo == null) { if (limbo == null) {
ConsoleLogger.debug("No LimboPlayer found for `{0}` - cannot restore", lowerName); logger.debug("No LimboPlayer found for `{0}` - cannot restore", lowerName);
} else { } else {
player.setOp(limbo.isOperator()); player.setOp(limbo.isOperator());
settings.getProperty(RESTORE_ALLOW_FLIGHT).restoreAllowFlight(player, limbo); settings.getProperty(RESTORE_ALLOW_FLIGHT).restoreAllowFlight(player, limbo);
limbo.clearTasks(); limbo.clearTasks();
ConsoleLogger.debug("Restored LimboPlayer stats for `{0}`", lowerName); logger.debug("Restored LimboPlayer stats for `{0}`", lowerName);
persistence.removeLimboPlayer(player); persistence.removeLimboPlayer(player);
} }
authGroupHandler.setGroup(player, limbo, AuthGroupType.LOGGED_IN); authGroupHandler.setGroup(player, limbo, AuthGroupType.LOGGED_IN);
@ -173,7 +176,7 @@ public class LimboService {
private Optional<LimboPlayer> getLimboOrLogError(Player player, String context) { private Optional<LimboPlayer> getLimboOrLogError(Player player, String context) {
LimboPlayer limbo = entries.get(player.getName().toLowerCase()); LimboPlayer limbo = entries.get(player.getName().toLowerCase());
if (limbo == null) { if (limbo == null) {
ConsoleLogger.debug("No LimboPlayer found for `{0}`. Action: {1}", player.getName(), context); logger.debug("No LimboPlayer found for `{0}`. Action: {1}", player.getName(), context);
} }
return Optional.ofNullable(limbo); return Optional.ofNullable(limbo);
} }

View File

@ -1,6 +1,7 @@
package fr.xephi.authme.data.limbo; package fr.xephi.authme.data.limbo;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.LimboSettings; import fr.xephi.authme.settings.properties.LimboSettings;
@ -18,6 +19,8 @@ import static fr.xephi.authme.util.Utils.isCollectionEmpty;
*/ */
class LimboServiceHelper { class LimboServiceHelper {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(LimboServiceHelper.class);
@Inject @Inject
private PermissionsManager permissionsManager; private PermissionsManager permissionsManager;
@ -38,7 +41,7 @@ class LimboServiceHelper {
boolean flyEnabled = player.getAllowFlight(); boolean flyEnabled = player.getAllowFlight();
Collection<String> playerGroups = permissionsManager.hasGroupSupport() Collection<String> playerGroups = permissionsManager.hasGroupSupport()
? permissionsManager.getGroups(player) : Collections.emptyList(); ? permissionsManager.getGroups(player) : Collections.emptyList();
ConsoleLogger.debug("Player `{0}` has groups `{1}`", player.getName(), String.join(", ", playerGroups)); logger.debug("Player `{0}` has groups `{1}`", player.getName(), String.join(", ", playerGroups));
return new LimboPlayer(location, isOperator, playerGroups, flyEnabled); return new LimboPlayer(location, isOperator, playerGroups, flyEnabled);
} }
@ -87,9 +90,8 @@ class LimboServiceHelper {
return first == null ? second : first; return first == null ? second : first;
} }
private static Collection<String> getLimboGroups(Collection<String> oldLimboGroups, private Collection<String> getLimboGroups(Collection<String> oldLimboGroups, Collection<String> newLimboGroups) {
Collection<String> newLimboGroups) { logger.debug("Limbo merge: new and old groups are `{0}` and `{1}`", newLimboGroups, oldLimboGroups);
ConsoleLogger.debug("Limbo merge: new and old groups are `{0}` and `{1}`", newLimboGroups, oldLimboGroups);
return isCollectionEmpty(oldLimboGroups) ? newLimboGroups : oldLimboGroups; return isCollectionEmpty(oldLimboGroups) ? newLimboGroups : oldLimboGroups;
} }
} }

View File

@ -7,6 +7,7 @@ import com.google.gson.GsonBuilder;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.limbo.LimboPlayer; import fr.xephi.authme.data.limbo.LimboPlayer;
import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.initialization.DataFolder;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.LimboSettings; import fr.xephi.authme.settings.properties.LimboSettings;
@ -33,6 +34,7 @@ class DistributedFilesPersistenceHandler implements LimboPersistenceHandler {
private static final Type LIMBO_MAP_TYPE = new TypeToken<Map<String, LimboPlayer>>(){}.getType(); private static final Type LIMBO_MAP_TYPE = new TypeToken<Map<String, LimboPlayer>>(){}.getType();
private final ConsoleLogger logger = ConsoleLoggerFactory.get(DistributedFilesPersistenceHandler.class);
private final File cacheFolder; private final File cacheFolder;
private final Gson gson; private final Gson gson;
private final SegmentNameBuilder segmentNameBuilder; private final SegmentNameBuilder segmentNameBuilder;
@ -103,7 +105,7 @@ class DistributedFilesPersistenceHandler implements LimboPersistenceHandler {
try (FileWriter fw = new FileWriter(file)) { try (FileWriter fw = new FileWriter(file)) {
gson.toJson(entries, fw); gson.toJson(entries, fw);
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.logException("Could not write to '" + file + "':", e); logger.logException("Could not write to '" + file + "':", e);
} }
} }
@ -115,7 +117,7 @@ class DistributedFilesPersistenceHandler implements LimboPersistenceHandler {
try { try {
return gson.fromJson(Files.asCharSource(file, StandardCharsets.UTF_8).read(), LIMBO_MAP_TYPE); return gson.fromJson(Files.asCharSource(file, StandardCharsets.UTF_8).read(), LIMBO_MAP_TYPE);
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.logException("Failed reading '" + file + "':", e); logger.logException("Failed reading '" + file + "':", e);
} }
return null; return null;
} }
@ -164,7 +166,7 @@ class DistributedFilesPersistenceHandler implements LimboPersistenceHandler {
private void saveToNewSegments(Map<String, LimboPlayer> limbosFromOldSegments) { private void saveToNewSegments(Map<String, LimboPlayer> limbosFromOldSegments) {
Map<String, Map<String, LimboPlayer>> limboBySegment = groupBySegment(limbosFromOldSegments); Map<String, Map<String, LimboPlayer>> limboBySegment = groupBySegment(limbosFromOldSegments);
ConsoleLogger.info("Saving " + limbosFromOldSegments.size() + " LimboPlayers from old segments into " logger.info("Saving " + limbosFromOldSegments.size() + " LimboPlayers from old segments into "
+ limboBySegment.size() + " current segments"); + limboBySegment.size() + " current segments");
for (Map.Entry<String, Map<String, LimboPlayer>> entry : limboBySegment.entrySet()) { for (Map.Entry<String, Map<String, LimboPlayer>> entry : limboBySegment.entrySet()) {
File file = getSegmentFile(entry.getKey()); File file = getSegmentFile(entry.getKey());
@ -203,7 +205,7 @@ class DistributedFilesPersistenceHandler implements LimboPersistenceHandler {
.filter(f -> isLimboJsonFile(f) && f.length() < 3) .filter(f -> isLimboJsonFile(f) && f.length() < 3)
.peek(FileUtils::delete) .peek(FileUtils::delete)
.count(); .count();
ConsoleLogger.debug("Limbo: Deleted {0} empty segment files", deletedFiles); logger.debug("Limbo: Deleted {0} empty segment files", deletedFiles);
} }
/** /**
@ -215,10 +217,10 @@ class DistributedFilesPersistenceHandler implements LimboPersistenceHandler {
return name.startsWith("seg") && name.endsWith("-limbo.json"); return name.startsWith("seg") && name.endsWith("-limbo.json");
} }
private static File[] listFiles(File folder) { private File[] listFiles(File folder) {
File[] files = folder.listFiles(); File[] files = folder.listFiles();
if (files == null) { if (files == null) {
ConsoleLogger.warning("Could not get files of '" + folder + "'"); logger.warning("Could not get files of '" + folder + "'");
return new File[0]; return new File[0];
} }
return files; return files;

View File

@ -6,6 +6,7 @@ import com.google.gson.GsonBuilder;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.limbo.LimboPlayer; import fr.xephi.authme.data.limbo.LimboPlayer;
import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.initialization.DataFolder;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.util.FileUtils; import fr.xephi.authme.util.FileUtils;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -20,6 +21,8 @@ import java.nio.charset.StandardCharsets;
*/ */
class IndividualFilesPersistenceHandler implements LimboPersistenceHandler { class IndividualFilesPersistenceHandler implements LimboPersistenceHandler {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(IndividualFilesPersistenceHandler.class);
private final Gson gson; private final Gson gson;
private final File cacheDir; private final File cacheDir;
@ -27,7 +30,7 @@ class IndividualFilesPersistenceHandler implements LimboPersistenceHandler {
IndividualFilesPersistenceHandler(@DataFolder File dataFolder, BukkitService bukkitService) { IndividualFilesPersistenceHandler(@DataFolder File dataFolder, BukkitService bukkitService) {
cacheDir = new File(dataFolder, "playerdata"); cacheDir = new File(dataFolder, "playerdata");
if (!cacheDir.exists() && !cacheDir.isDirectory() && !cacheDir.mkdir()) { if (!cacheDir.exists() && !cacheDir.isDirectory() && !cacheDir.mkdir()) {
ConsoleLogger.warning("Failed to create playerdata directory '" + cacheDir + "'"); logger.warning("Failed to create playerdata directory '" + cacheDir + "'");
} }
gson = new GsonBuilder() gson = new GsonBuilder()
.registerTypeAdapter(LimboPlayer.class, new LimboPlayerSerializer()) .registerTypeAdapter(LimboPlayer.class, new LimboPlayerSerializer())
@ -48,7 +51,7 @@ class IndividualFilesPersistenceHandler implements LimboPersistenceHandler {
String str = Files.asCharSource(file, StandardCharsets.UTF_8).read(); String str = Files.asCharSource(file, StandardCharsets.UTF_8).read();
return gson.fromJson(str, LimboPlayer.class); return gson.fromJson(str, LimboPlayer.class);
} catch (IOException e) { } catch (IOException e) {
ConsoleLogger.logException("Could not read player data on disk for '" + player.getName() + "'", e); logger.logException("Could not read player data on disk for '" + player.getName() + "'", e);
return null; return null;
} }
} }
@ -62,7 +65,7 @@ class IndividualFilesPersistenceHandler implements LimboPersistenceHandler {
Files.touch(file); Files.touch(file);
Files.write(gson.toJson(limboPlayer), file, StandardCharsets.UTF_8); Files.write(gson.toJson(limboPlayer), file, StandardCharsets.UTF_8);
} catch (IOException e) { } catch (IOException e) {
ConsoleLogger.logException("Failed to write " + player.getName() + " data:", e); logger.logException("Failed to write " + player.getName() + " data:", e);
} }
} }

View File

@ -4,6 +4,7 @@ import ch.jalu.injector.factory.Factory;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.limbo.LimboPlayer; import fr.xephi.authme.data.limbo.LimboPlayer;
import fr.xephi.authme.initialization.SettingsDependent; import fr.xephi.authme.initialization.SettingsDependent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.LimboSettings; import fr.xephi.authme.settings.properties.LimboSettings;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -15,6 +16,8 @@ import javax.inject.Inject;
*/ */
public class LimboPersistence implements SettingsDependent { public class LimboPersistence implements SettingsDependent {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(LimboPersistence.class);
private final Factory<LimboPersistenceHandler> handlerFactory; private final Factory<LimboPersistenceHandler> handlerFactory;
private LimboPersistenceHandler handler; private LimboPersistenceHandler handler;
@ -35,7 +38,7 @@ public class LimboPersistence implements SettingsDependent {
try { try {
return handler.getLimboPlayer(player); return handler.getLimboPlayer(player);
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.logException("Could not get LimboPlayer for '" + player.getName() + "'", e); logger.logException("Could not get LimboPlayer for '" + player.getName() + "'", e);
} }
return null; return null;
} }
@ -50,7 +53,7 @@ public class LimboPersistence implements SettingsDependent {
try { try {
handler.saveLimboPlayer(player, limbo); handler.saveLimboPlayer(player, limbo);
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.logException("Could not save LimboPlayer for '" + player.getName() + "'", e); logger.logException("Could not save LimboPlayer for '" + player.getName() + "'", e);
} }
} }
@ -63,7 +66,7 @@ public class LimboPersistence implements SettingsDependent {
try { try {
handler.removeLimboPlayer(player); handler.removeLimboPlayer(player);
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.logException("Could not remove LimboPlayer for '" + player.getName() + "'", e); logger.logException("Could not remove LimboPlayer for '" + player.getName() + "'", e);
} }
} }
@ -72,7 +75,7 @@ public class LimboPersistence implements SettingsDependent {
LimboPersistenceType persistenceType = settings.getProperty(LimboSettings.LIMBO_PERSISTENCE_TYPE); LimboPersistenceType persistenceType = settings.getProperty(LimboSettings.LIMBO_PERSISTENCE_TYPE);
// If we're changing from an existing handler, output a quick hint that nothing is converted. // If we're changing from an existing handler, output a quick hint that nothing is converted.
if (handler != null && handler.getType() != persistenceType) { if (handler != null && handler.getType() != persistenceType) {
ConsoleLogger.info("Limbo persistence type has changed! Note that the data is not converted."); logger.info("Limbo persistence type has changed! Note that the data is not converted.");
} }
handler = handlerFactory.newInstance(persistenceType.getImplementationClass()); handler = handlerFactory.newInstance(persistenceType.getImplementationClass());
} }

View File

@ -53,7 +53,8 @@ public abstract class AbstractSqlDataSource implements DataSource {
public boolean saveAuth(PlayerAuth auth) { public boolean saveAuth(PlayerAuth auth) {
return columnsHandler.insert(auth, return columnsHandler.insert(auth,
AuthMeColumns.NAME, AuthMeColumns.NICK_NAME, AuthMeColumns.PASSWORD, AuthMeColumns.SALT, AuthMeColumns.NAME, AuthMeColumns.NICK_NAME, AuthMeColumns.PASSWORD, AuthMeColumns.SALT,
AuthMeColumns.EMAIL, AuthMeColumns.REGISTRATION_DATE, AuthMeColumns.REGISTRATION_IP); AuthMeColumns.EMAIL, AuthMeColumns.REGISTRATION_DATE, AuthMeColumns.REGISTRATION_IP,
AuthMeColumns.UUID);
} }
@Override @Override

View File

@ -12,6 +12,7 @@ import com.google.common.util.concurrent.ThreadFactoryBuilder;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.security.crypts.HashedPassword; import fr.xephi.authme.security.crypts.HashedPassword;
import fr.xephi.authme.util.Utils; import fr.xephi.authme.util.Utils;
@ -25,6 +26,8 @@ import java.util.stream.Collectors;
public class CacheDataSource implements DataSource { public class CacheDataSource implements DataSource {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(CacheDataSource.class);
private final DataSource source; private final DataSource source;
private final PlayerCache playerCache; private final PlayerCache playerCache;
private final LoadingCache<String, Optional<PlayerAuth>> cachedAuths; private final LoadingCache<String, Optional<PlayerAuth>> cachedAuths;
@ -164,7 +167,7 @@ public class CacheDataSource implements DataSource {
try { try {
executorService.awaitTermination(5, TimeUnit.SECONDS); executorService.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) { } catch (InterruptedException e) {
ConsoleLogger.logException("Could not close executor service:", e); logger.logException("Could not close executor service:", e);
} }
cachedAuths.invalidateAll(); cachedAuths.invalidateAll();
source.closeConnection(); source.closeConnection();

View File

@ -30,6 +30,7 @@ public final class Columns {
public final String HAS_SESSION; public final String HAS_SESSION;
public final String REGISTRATION_DATE; public final String REGISTRATION_DATE;
public final String REGISTRATION_IP; public final String REGISTRATION_IP;
public final String PLAYER_UUID;
public Columns(Settings settings) { public Columns(Settings settings) {
NAME = settings.getProperty(DatabaseSettings.MYSQL_COL_NAME); NAME = settings.getProperty(DatabaseSettings.MYSQL_COL_NAME);
@ -52,6 +53,7 @@ public final class Columns {
HAS_SESSION = settings.getProperty(DatabaseSettings.MYSQL_COL_HASSESSION); HAS_SESSION = settings.getProperty(DatabaseSettings.MYSQL_COL_HASSESSION);
REGISTRATION_DATE = settings.getProperty(DatabaseSettings.MYSQL_COL_REGISTER_DATE); REGISTRATION_DATE = settings.getProperty(DatabaseSettings.MYSQL_COL_REGISTER_DATE);
REGISTRATION_IP = settings.getProperty(DatabaseSettings.MYSQL_COL_REGISTER_IP); REGISTRATION_IP = settings.getProperty(DatabaseSettings.MYSQL_COL_REGISTER_IP);
PLAYER_UUID = settings.getProperty(DatabaseSettings.MYSQL_COL_PLAYER_UUID);
} }
} }

View File

@ -8,9 +8,11 @@ import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.datasource.columnshandler.AuthMeColumnsHandler; import fr.xephi.authme.datasource.columnshandler.AuthMeColumnsHandler;
import fr.xephi.authme.datasource.mysqlextensions.MySqlExtension; import fr.xephi.authme.datasource.mysqlextensions.MySqlExtension;
import fr.xephi.authme.datasource.mysqlextensions.MySqlExtensionsFactory; import fr.xephi.authme.datasource.mysqlextensions.MySqlExtensionsFactory;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.DatabaseSettings; import fr.xephi.authme.settings.properties.DatabaseSettings;
import fr.xephi.authme.settings.properties.HooksSettings; import fr.xephi.authme.settings.properties.HooksSettings;
import fr.xephi.authme.util.UuidUtils;
import java.sql.Connection; import java.sql.Connection;
import java.sql.DatabaseMetaData; import java.sql.DatabaseMetaData;
@ -23,6 +25,7 @@ import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.UUID;
import static fr.xephi.authme.datasource.SqlDataSourceUtils.getNullableLong; import static fr.xephi.authme.datasource.SqlDataSourceUtils.getNullableLong;
import static fr.xephi.authme.datasource.SqlDataSourceUtils.logSqlException; import static fr.xephi.authme.datasource.SqlDataSourceUtils.logSqlException;
@ -32,6 +35,7 @@ import static fr.xephi.authme.datasource.SqlDataSourceUtils.logSqlException;
*/ */
@SuppressWarnings({"checkstyle:AbbreviationAsWordInName"}) // Justification: Class name cannot be changed anymore @SuppressWarnings({"checkstyle:AbbreviationAsWordInName"}) // Justification: Class name cannot be changed anymore
public class MySQL extends AbstractSqlDataSource { public class MySQL extends AbstractSqlDataSource {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(MySQL.class);
private boolean useSsl; private boolean useSsl;
private boolean serverCertificateVerification; private boolean serverCertificateVerification;
@ -56,14 +60,14 @@ public class MySQL extends AbstractSqlDataSource {
this.setConnectionArguments(); this.setConnectionArguments();
} catch (RuntimeException e) { } catch (RuntimeException e) {
if (e instanceof IllegalArgumentException) { if (e instanceof IllegalArgumentException) {
ConsoleLogger.warning("Invalid database arguments! Please check your configuration!"); logger.warning("Invalid database arguments! Please check your configuration!");
ConsoleLogger.warning("If this error persists, please report it to the developer!"); logger.warning("If this error persists, please report it to the developer!");
} }
if (e instanceof PoolInitializationException) { if (e instanceof PoolInitializationException) {
ConsoleLogger.warning("Can't initialize database connection! Please check your configuration!"); logger.warning("Can't initialize database connection! Please check your configuration!");
ConsoleLogger.warning("If this error persists, please report it to the developer!"); logger.warning("If this error persists, please report it to the developer!");
} }
ConsoleLogger.warning("Can't use the Hikari Connection Pool! Please, report this error to the developer!"); logger.warning("Can't use the Hikari Connection Pool! Please, report this error to the developer!");
throw e; throw e;
} }
@ -72,8 +76,8 @@ public class MySQL extends AbstractSqlDataSource {
checkTablesAndColumns(); checkTablesAndColumns();
} catch (SQLException e) { } catch (SQLException e) {
closeConnection(); closeConnection();
ConsoleLogger.logException("Can't initialize the MySQL database:", e); logger.logException("Can't initialize the MySQL database:", e);
ConsoleLogger.warning("Please check your database settings in the config.yml file!"); logger.warning("Please check your database settings in the config.yml file!");
throw e; throw e;
} }
} }
@ -147,7 +151,7 @@ public class MySQL extends AbstractSqlDataSource {
ds.addDataSourceProperty("prepStmtCacheSize", "275"); ds.addDataSourceProperty("prepStmtCacheSize", "275");
ds.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); ds.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
ConsoleLogger.info("Connection arguments loaded, Hikari ConnectionPool ready!"); logger.info("Connection arguments loaded, Hikari ConnectionPool ready!");
} }
@Override @Override
@ -156,7 +160,7 @@ public class MySQL extends AbstractSqlDataSource {
ds.close(); ds.close();
} }
setConnectionArguments(); setConnectionArguments();
ConsoleLogger.info("Hikari ConnectionPool arguments reloaded!"); logger.info("Hikari ConnectionPool arguments reloaded!");
} }
private Connection getConnection() throws SQLException { private Connection getConnection() throws SQLException {
@ -264,8 +268,13 @@ public class MySQL extends AbstractSqlDataSource {
st.executeUpdate("ALTER TABLE " + tableName st.executeUpdate("ALTER TABLE " + tableName
+ " ADD COLUMN " + col.TOTP_KEY + " VARCHAR(16);"); + " ADD COLUMN " + col.TOTP_KEY + " VARCHAR(16);");
} }
if (!col.PLAYER_UUID.isEmpty() && isColumnMissing(md, col.PLAYER_UUID)) {
st.executeUpdate("ALTER TABLE " + tableName
+ " ADD COLUMN " + col.PLAYER_UUID + " VARCHAR(36)");
}
} }
ConsoleLogger.info("MySQL setup finished"); logger.info("MySQL setup finished");
} }
private boolean isColumnMissing(DatabaseMetaData metaData, String columnName) throws SQLException { private boolean isColumnMissing(DatabaseMetaData metaData, String columnName) throws SQLException {
@ -454,6 +463,8 @@ public class MySQL extends AbstractSqlDataSource {
private PlayerAuth buildAuthFromResultSet(ResultSet row) throws SQLException { private PlayerAuth buildAuthFromResultSet(ResultSet row) throws SQLException {
String salt = col.SALT.isEmpty() ? null : row.getString(col.SALT); String salt = col.SALT.isEmpty() ? null : row.getString(col.SALT);
int group = col.GROUP.isEmpty() ? -1 : row.getInt(col.GROUP); int group = col.GROUP.isEmpty() ? -1 : row.getInt(col.GROUP);
UUID uuid = col.PLAYER_UUID.isEmpty()
? null : UuidUtils.parseUuidSafely(row.getString(col.PLAYER_UUID));
return PlayerAuth.builder() return PlayerAuth.builder()
.name(row.getString(col.NAME)) .name(row.getString(col.NAME))
.realName(row.getString(col.REAL_NAME)) .realName(row.getString(col.REAL_NAME))
@ -471,6 +482,7 @@ public class MySQL extends AbstractSqlDataSource {
.locZ(row.getDouble(col.LASTLOC_Z)) .locZ(row.getDouble(col.LASTLOC_Z))
.locYaw(row.getFloat(col.LASTLOC_YAW)) .locYaw(row.getFloat(col.LASTLOC_YAW))
.locPitch(row.getFloat(col.LASTLOC_PITCH)) .locPitch(row.getFloat(col.LASTLOC_PITCH))
.uuid(uuid)
.build(); .build();
} }
} }

View File

@ -1,6 +1,7 @@
package fr.xephi.authme.datasource; package fr.xephi.authme.datasource;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import java.sql.DatabaseMetaData; import java.sql.DatabaseMetaData;
import java.sql.ResultSet; import java.sql.ResultSet;
@ -12,6 +13,8 @@ import java.sql.Types;
* Performs migrations on the MySQL data source if necessary. * Performs migrations on the MySQL data source if necessary.
*/ */
final class MySqlMigrater { final class MySqlMigrater {
private static ConsoleLogger logger = ConsoleLoggerFactory.get(MySqlMigrater.class);
private MySqlMigrater() { private MySqlMigrater() {
} }
@ -35,7 +38,7 @@ final class MySqlMigrater {
String sql = String.format("ALTER TABLE %s MODIFY %s VARCHAR(40) CHARACTER SET ascii COLLATE ascii_bin", String sql = String.format("ALTER TABLE %s MODIFY %s VARCHAR(40) CHARACTER SET ascii COLLATE ascii_bin",
tableName, col.LAST_IP); tableName, col.LAST_IP);
st.execute(sql); st.execute(sql);
ConsoleLogger.info("Changed last login column to allow NULL values. Please verify the registration feature " logger.info("Changed last login column to allow NULL values. Please verify the registration feature "
+ "if you are hooking into a forum."); + "if you are hooking into a forum.");
} }
} }
@ -53,7 +56,7 @@ final class MySqlMigrater {
final int columnType; final int columnType;
try (ResultSet rs = metaData.getColumns(null, null, tableName, col.LAST_LOGIN)) { try (ResultSet rs = metaData.getColumns(null, null, tableName, col.LAST_LOGIN)) {
if (!rs.next()) { if (!rs.next()) {
ConsoleLogger.warning("Could not get LAST_LOGIN meta data. This should never happen!"); logger.warning("Could not get LAST_LOGIN meta data. This should never happen!");
return; return;
} }
columnType = rs.getInt("DATA_TYPE"); columnType = rs.getInt("DATA_TYPE");
@ -75,7 +78,7 @@ final class MySqlMigrater {
*/ */
private static void migrateLastLoginColumnFromInt(Statement st, String tableName, Columns col) throws SQLException { private static void migrateLastLoginColumnFromInt(Statement st, String tableName, Columns col) throws SQLException {
// Change from int to bigint // Change from int to bigint
ConsoleLogger.info("Migrating lastlogin column from int to bigint"); logger.info("Migrating lastlogin column from int to bigint");
String sql = String.format("ALTER TABLE %s MODIFY %s BIGINT;", tableName, col.LAST_LOGIN); String sql = String.format("ALTER TABLE %s MODIFY %s BIGINT;", tableName, col.LAST_LOGIN);
st.execute(sql); st.execute(sql);
@ -86,7 +89,7 @@ final class MySqlMigrater {
tableName, col.LAST_LOGIN, col.LAST_LOGIN, col.LAST_LOGIN, rangeStart, col.LAST_LOGIN, rangeEnd); tableName, col.LAST_LOGIN, col.LAST_LOGIN, col.LAST_LOGIN, rangeStart, col.LAST_LOGIN, rangeEnd);
int changedRows = st.executeUpdate(sql); int changedRows = st.executeUpdate(sql);
ConsoleLogger.warning("You may have entries with invalid timestamps. Please check your data " logger.warning("You may have entries with invalid timestamps. Please check your data "
+ "before purging. " + changedRows + " rows were migrated from seconds to milliseconds."); + "before purging. " + changedRows + " rows were migrated from seconds to milliseconds.");
} }
@ -107,7 +110,7 @@ final class MySqlMigrater {
long currentTimestamp = System.currentTimeMillis(); long currentTimestamp = System.currentTimeMillis();
int updatedRows = st.executeUpdate(String.format("UPDATE %s SET %s = %d;", int updatedRows = st.executeUpdate(String.format("UPDATE %s SET %s = %d;",
tableName, col.REGISTRATION_DATE, currentTimestamp)); tableName, col.REGISTRATION_DATE, currentTimestamp));
ConsoleLogger.info("Created column '" + col.REGISTRATION_DATE + "' and set the current timestamp, " logger.info("Created column '" + col.REGISTRATION_DATE + "' and set the current timestamp, "
+ currentTimestamp + ", to all " + updatedRows + " rows"); + currentTimestamp + ", to all " + updatedRows + " rows");
} }
} }

View File

@ -8,6 +8,7 @@ import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.datasource.columnshandler.AuthMeColumnsHandler; import fr.xephi.authme.datasource.columnshandler.AuthMeColumnsHandler;
import fr.xephi.authme.datasource.mysqlextensions.MySqlExtension; import fr.xephi.authme.datasource.mysqlextensions.MySqlExtension;
import fr.xephi.authme.datasource.mysqlextensions.MySqlExtensionsFactory; import fr.xephi.authme.datasource.mysqlextensions.MySqlExtensionsFactory;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.DatabaseSettings; import fr.xephi.authme.settings.properties.DatabaseSettings;
import fr.xephi.authme.settings.properties.HooksSettings; import fr.xephi.authme.settings.properties.HooksSettings;
@ -32,6 +33,8 @@ import static fr.xephi.authme.datasource.SqlDataSourceUtils.logSqlException;
*/ */
public class PostgreSqlDataSource extends AbstractSqlDataSource { public class PostgreSqlDataSource extends AbstractSqlDataSource {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(PostgreSqlDataSource.class);
private String host; private String host;
private String port; private String port;
private String username; private String username;
@ -53,14 +56,14 @@ public class PostgreSqlDataSource extends AbstractSqlDataSource {
this.setConnectionArguments(); this.setConnectionArguments();
} catch (RuntimeException e) { } catch (RuntimeException e) {
if (e instanceof IllegalArgumentException) { if (e instanceof IllegalArgumentException) {
ConsoleLogger.warning("Invalid database arguments! Please check your configuration!"); logger.warning("Invalid database arguments! Please check your configuration!");
ConsoleLogger.warning("If this error persists, please report it to the developer!"); logger.warning("If this error persists, please report it to the developer!");
} }
if (e instanceof PoolInitializationException) { if (e instanceof PoolInitializationException) {
ConsoleLogger.warning("Can't initialize database connection! Please check your configuration!"); logger.warning("Can't initialize database connection! Please check your configuration!");
ConsoleLogger.warning("If this error persists, please report it to the developer!"); logger.warning("If this error persists, please report it to the developer!");
} }
ConsoleLogger.warning("Can't use the Hikari Connection Pool! Please, report this error to the developer!"); logger.warning("Can't use the Hikari Connection Pool! Please, report this error to the developer!");
throw e; throw e;
} }
@ -69,8 +72,8 @@ public class PostgreSqlDataSource extends AbstractSqlDataSource {
checkTablesAndColumns(); checkTablesAndColumns();
} catch (SQLException e) { } catch (SQLException e) {
closeConnection(); closeConnection();
ConsoleLogger.logException("Can't initialize the PostgreSQL database:", e); logger.logException("Can't initialize the PostgreSQL database:", e);
ConsoleLogger.warning("Please check your database settings in the config.yml file!"); logger.warning("Please check your database settings in the config.yml file!");
throw e; throw e;
} }
} }
@ -129,7 +132,7 @@ public class PostgreSqlDataSource extends AbstractSqlDataSource {
ds.addDataSourceProperty("cachePrepStmts", "true"); ds.addDataSourceProperty("cachePrepStmts", "true");
ds.addDataSourceProperty("preparedStatementCacheQueries", "275"); ds.addDataSourceProperty("preparedStatementCacheQueries", "275");
ConsoleLogger.info("Connection arguments loaded, Hikari ConnectionPool ready!"); logger.info("Connection arguments loaded, Hikari ConnectionPool ready!");
} }
@Override @Override
@ -138,7 +141,7 @@ public class PostgreSqlDataSource extends AbstractSqlDataSource {
ds.close(); ds.close();
} }
setConnectionArguments(); setConnectionArguments();
ConsoleLogger.info("Hikari ConnectionPool arguments reloaded!"); logger.info("Hikari ConnectionPool arguments reloaded!");
} }
private Connection getConnection() throws SQLException { private Connection getConnection() throws SQLException {
@ -241,8 +244,13 @@ public class PostgreSqlDataSource extends AbstractSqlDataSource {
st.executeUpdate("ALTER TABLE " + tableName st.executeUpdate("ALTER TABLE " + tableName
+ " ADD COLUMN " + col.TOTP_KEY + " VARCHAR(16);"); + " ADD COLUMN " + col.TOTP_KEY + " VARCHAR(16);");
} }
if (!col.PLAYER_UUID.isEmpty() && isColumnMissing(md, col.PLAYER_UUID)) {
st.executeUpdate("ALTER TABLE " + tableName
+ " ADD COLUMN " + col.PLAYER_UUID + " VARCHAR(36)");
}
} }
ConsoleLogger.info("PostgreSQL setup finished"); logger.info("PostgreSQL setup finished");
} }
private boolean isColumnMissing(DatabaseMetaData metaData, String columnName) throws SQLException { private boolean isColumnMissing(DatabaseMetaData metaData, String columnName) throws SQLException {

View File

@ -4,6 +4,7 @@ import com.google.common.annotations.VisibleForTesting;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.datasource.columnshandler.AuthMeColumnsHandler; import fr.xephi.authme.datasource.columnshandler.AuthMeColumnsHandler;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.DatabaseSettings; import fr.xephi.authme.settings.properties.DatabaseSettings;
@ -30,6 +31,7 @@ import static fr.xephi.authme.datasource.SqlDataSourceUtils.logSqlException;
@SuppressWarnings({"checkstyle:AbbreviationAsWordInName"}) // Justification: Class name cannot be changed anymore @SuppressWarnings({"checkstyle:AbbreviationAsWordInName"}) // Justification: Class name cannot be changed anymore
public class SQLite extends AbstractSqlDataSource { public class SQLite extends AbstractSqlDataSource {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(SQLite.class);
private final Settings settings; private final Settings settings;
private final File dataFolder; private final File dataFolder;
private final String database; private final String database;
@ -57,7 +59,7 @@ public class SQLite extends AbstractSqlDataSource {
this.setup(); this.setup();
this.migrateIfNeeded(); this.migrateIfNeeded();
} catch (Exception ex) { } catch (Exception ex) {
ConsoleLogger.logException("Error during SQLite initialization:", ex); logger.logException("Error during SQLite initialization:", ex);
throw ex; throw ex;
} }
} }
@ -85,7 +87,7 @@ public class SQLite extends AbstractSqlDataSource {
throw new IllegalStateException("Failed to load SQLite JDBC class", e); throw new IllegalStateException("Failed to load SQLite JDBC class", e);
} }
ConsoleLogger.debug("SQLite driver loaded"); logger.debug("SQLite driver loaded");
this.con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/" + database + ".db"); this.con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/" + database + ".db");
this.columnsHandler = AuthMeColumnsHandler.createForSqlite(con, settings); this.columnsHandler = AuthMeColumnsHandler.createForSqlite(con, settings);
} }
@ -182,8 +184,13 @@ public class SQLite extends AbstractSqlDataSource {
st.executeUpdate("ALTER TABLE " + tableName st.executeUpdate("ALTER TABLE " + tableName
+ " ADD COLUMN " + col.TOTP_KEY + " VARCHAR(16);"); + " ADD COLUMN " + col.TOTP_KEY + " VARCHAR(16);");
} }
if (!col.PLAYER_UUID.isEmpty() && isColumnMissing(md, col.PLAYER_UUID)) {
st.executeUpdate("ALTER TABLE " + tableName
+ " ADD COLUMN " + col.PLAYER_UUID + " VARCHAR(36)");
}
} }
ConsoleLogger.info("SQLite Setup finished"); logger.info("SQLite Setup finished");
} }
/** /**
@ -214,7 +221,7 @@ public class SQLite extends AbstractSqlDataSource {
this.setup(); this.setup();
this.migrateIfNeeded(); this.migrateIfNeeded();
} catch (SQLException ex) { } catch (SQLException ex) {
ConsoleLogger.logException("Error while reloading SQLite:", ex); logger.logException("Error while reloading SQLite:", ex);
} }
} }
@ -393,7 +400,7 @@ public class SQLite extends AbstractSqlDataSource {
long currentTimestamp = System.currentTimeMillis(); long currentTimestamp = System.currentTimeMillis();
int updatedRows = st.executeUpdate(String.format("UPDATE %s SET %s = %d;", int updatedRows = st.executeUpdate(String.format("UPDATE %s SET %s = %d;",
tableName, col.REGISTRATION_DATE, currentTimestamp)); tableName, col.REGISTRATION_DATE, currentTimestamp));
ConsoleLogger.info("Created column '" + col.REGISTRATION_DATE + "' and set the current timestamp, " logger.info("Created column '" + col.REGISTRATION_DATE + "' and set the current timestamp, "
+ currentTimestamp + ", to all " + updatedRows + " rows"); + currentTimestamp + ", to all " + updatedRows + " rows");
} }

View File

@ -2,6 +2,7 @@ package fr.xephi.authme.datasource;
import com.google.common.io.Files; import com.google.common.io.Files;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.DatabaseSettings; import fr.xephi.authme.settings.properties.DatabaseSettings;
import fr.xephi.authme.util.FileUtils; import fr.xephi.authme.util.FileUtils;
@ -19,6 +20,7 @@ import java.sql.Statement;
*/ */
class SqLiteMigrater { class SqLiteMigrater {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(SqLiteMigrater.class);
private final File dataFolder; private final File dataFolder;
private final String databaseName; private final String databaseName;
private final String tableName; private final String tableName;
@ -53,13 +55,13 @@ class SqLiteMigrater {
* @param sqLite the instance to migrate * @param sqLite the instance to migrate
*/ */
void performMigration(SQLite sqLite) throws SQLException { void performMigration(SQLite sqLite) throws SQLException {
ConsoleLogger.warning("YOUR SQLITE DATABASE NEEDS MIGRATING! DO NOT TURN OFF YOUR SERVER"); logger.warning("YOUR SQLITE DATABASE NEEDS MIGRATING! DO NOT TURN OFF YOUR SERVER");
String backupName = createBackup(); String backupName = createBackup();
ConsoleLogger.info("Made a backup of your database at 'backups/" + backupName + "'"); logger.info("Made a backup of your database at 'backups/" + backupName + "'");
recreateDatabaseWithNewDefinitions(sqLite); recreateDatabaseWithNewDefinitions(sqLite);
ConsoleLogger.info("SQLite database migrated successfully"); logger.info("SQLite database migrated successfully");
} }
private String createBackup() { private String createBackup() {
@ -104,7 +106,7 @@ class SqLiteMigrater {
+ " CASE WHEN $email = 'your@email.com' THEN NULL ELSE $email END, $isLogged" + " CASE WHEN $email = 'your@email.com' THEN NULL ELSE $email END, $isLogged"
+ " FROM " + tempTable + ";"; + " FROM " + tempTable + ";";
int insertedEntries = st.executeUpdate(replaceColumnVariables(copySql)); int insertedEntries = st.executeUpdate(replaceColumnVariables(copySql));
ConsoleLogger.info("Copied over " + insertedEntries + " from the old table to the new one"); logger.info("Copied over " + insertedEntries + " from the old table to the new one");
st.execute("DROP TABLE " + tempTable + ";"); st.execute("DROP TABLE " + tempTable + ";");
} }

View File

@ -1,6 +1,7 @@
package fr.xephi.authme.datasource; package fr.xephi.authme.datasource;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import java.sql.DatabaseMetaData; import java.sql.DatabaseMetaData;
import java.sql.ResultSet; import java.sql.ResultSet;
@ -11,6 +12,8 @@ import java.sql.SQLException;
*/ */
public final class SqlDataSourceUtils { public final class SqlDataSourceUtils {
private static final ConsoleLogger logger = ConsoleLoggerFactory.get(SqlDataSourceUtils.class);
private SqlDataSourceUtils() { private SqlDataSourceUtils() {
} }
@ -20,7 +23,7 @@ public final class SqlDataSourceUtils {
* @param e the exception to log * @param e the exception to log
*/ */
public static void logSqlException(SQLException e) { public static void logSqlException(SQLException e) {
ConsoleLogger.logException("Error during SQL operation:", e); logger.logException("Error during SQL operation:", e);
} }
/** /**
@ -58,7 +61,7 @@ public final class SqlDataSourceUtils {
if (nullableCode == DatabaseMetaData.columnNoNulls) { if (nullableCode == DatabaseMetaData.columnNoNulls) {
return true; return true;
} else if (nullableCode == DatabaseMetaData.columnNullableUnknown) { } else if (nullableCode == DatabaseMetaData.columnNullableUnknown) {
ConsoleLogger.warning("Unknown nullable status for column '" + columnName + "'"); logger.warning("Unknown nullable status for column '" + columnName + "'");
} }
} }
return false; return false;

View File

@ -3,6 +3,8 @@ package fr.xephi.authme.datasource.columnshandler;
import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.settings.properties.DatabaseSettings; import fr.xephi.authme.settings.properties.DatabaseSettings;
import java.util.UUID;
import static fr.xephi.authme.datasource.columnshandler.AuthMeColumnsFactory.ColumnOptions.DEFAULT_FOR_NULL; import static fr.xephi.authme.datasource.columnshandler.AuthMeColumnsFactory.ColumnOptions.DEFAULT_FOR_NULL;
import static fr.xephi.authme.datasource.columnshandler.AuthMeColumnsFactory.ColumnOptions.OPTIONAL; import static fr.xephi.authme.datasource.columnshandler.AuthMeColumnsFactory.ColumnOptions.OPTIONAL;
import static fr.xephi.authme.datasource.columnshandler.AuthMeColumnsFactory.createDouble; import static fr.xephi.authme.datasource.columnshandler.AuthMeColumnsFactory.createDouble;
@ -46,6 +48,11 @@ public final class AuthMeColumns {
public static final PlayerAuthColumn<Long> REGISTRATION_DATE = createLong( public static final PlayerAuthColumn<Long> REGISTRATION_DATE = createLong(
DatabaseSettings.MYSQL_COL_REGISTER_DATE, PlayerAuth::getRegistrationDate); DatabaseSettings.MYSQL_COL_REGISTER_DATE, PlayerAuth::getRegistrationDate);
public static final PlayerAuthColumn<String> UUID = createString(
DatabaseSettings.MYSQL_COL_PLAYER_UUID,
auth -> ( auth.getUuid() == null ? null : auth.getUuid().toString()),
OPTIONAL);
// -------- // --------
// Location columns // Location columns
// -------- // --------
@ -76,7 +83,6 @@ public final class AuthMeColumns {
public static final DataSourceColumn<Integer> HAS_SESSION = createInteger( public static final DataSourceColumn<Integer> HAS_SESSION = createInteger(
DatabaseSettings.MYSQL_COL_HASSESSION); DatabaseSettings.MYSQL_COL_HASSESSION);
private AuthMeColumns() { private AuthMeColumns() {
} }
} }

View File

@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.datasource.DataSourceType; import fr.xephi.authme.datasource.DataSourceType;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import java.util.ArrayList; import java.util.ArrayList;
@ -18,8 +19,10 @@ import static fr.xephi.authme.util.Utils.logAndSendMessage;
*/ */
public abstract class AbstractDataSourceConverter<S extends DataSource> implements Converter { public abstract class AbstractDataSourceConverter<S extends DataSource> implements Converter {
private DataSource destination; private final ConsoleLogger logger = ConsoleLoggerFactory.get(MySqlToSqlite.class);
private DataSourceType destinationType;
private final DataSource destination;
private final DataSourceType destinationType;
/** /**
* Constructor. * Constructor.
@ -51,7 +54,7 @@ public abstract class AbstractDataSourceConverter<S extends DataSource> implemen
source = getSource(); source = getSource();
} catch (Exception e) { } catch (Exception e) {
logAndSendMessage(sender, "The data source to convert from could not be initialized"); logAndSendMessage(sender, "The data source to convert from could not be initialized");
ConsoleLogger.logException("Could not initialize source:", e); logger.logException("Could not initialize source:", e);
return; return;
} }
@ -60,7 +63,6 @@ public abstract class AbstractDataSourceConverter<S extends DataSource> implemen
if (destination.isAuthAvailable(auth.getNickname())) { if (destination.isAuthAvailable(auth.getNickname())) {
skippedPlayers.add(auth.getNickname()); skippedPlayers.add(auth.getNickname());
} else { } else {
adaptPlayerAuth(auth);
destination.saveAuth(auth); destination.saveAuth(auth);
destination.updateSession(auth); destination.updateSession(auth);
destination.updateQuitLoc(auth); destination.updateQuitLoc(auth);
@ -75,15 +77,6 @@ public abstract class AbstractDataSourceConverter<S extends DataSource> implemen
+ " to " + destinationType); + " to " + destinationType);
} }
/**
* Adapts the PlayerAuth from the source before it is saved in the destination.
*
* @param auth the auth from the source
*/
protected void adaptPlayerAuth(PlayerAuth auth) {
// noop
}
/** /**
* @return the data source to convert from * @return the data source to convert from
* @throws Exception during initialization of source * @throws Exception during initialization of source

View File

@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.initialization.DataFolder;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.ConverterSettings; import fr.xephi.authme.settings.properties.ConverterSettings;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -19,6 +20,8 @@ import java.io.IOException;
*/ */
public class CrazyLoginConverter implements Converter { public class CrazyLoginConverter implements Converter {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(CrazyLoginConverter.class);
private final DataSource database; private final DataSource database;
private final Settings settings; private final Settings settings;
private final File dataFolder; private final File dataFolder;
@ -46,10 +49,10 @@ public class CrazyLoginConverter implements Converter {
migrateAccount(line); migrateAccount(line);
} }
} }
ConsoleLogger.info("CrazyLogin database has been imported correctly"); logger.info("CrazyLogin database has been imported correctly");
} catch (IOException ex) { } catch (IOException ex) {
ConsoleLogger.warning("Can't open the crazylogin database file! Does it exist?"); logger.warning("Can't open the crazylogin database file! Does it exist?");
ConsoleLogger.logException("Encountered", ex); logger.logException("Encountered", ex);
} }
} }

View File

@ -5,8 +5,10 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.initialization.DataFolder;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.ConverterSettings; import fr.xephi.authme.settings.properties.ConverterSettings;
import fr.xephi.authme.util.UuidUtils;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import javax.inject.Inject; import javax.inject.Inject;
@ -21,6 +23,7 @@ import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.UUID;
import static fr.xephi.authme.util.Utils.logAndSendMessage; import static fr.xephi.authme.util.Utils.logAndSendMessage;
@ -29,6 +32,7 @@ import static fr.xephi.authme.util.Utils.logAndSendMessage;
*/ */
public class LoginSecurityConverter implements Converter { public class LoginSecurityConverter implements Converter {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(LoginSecurityConverter.class);
private final File dataFolder; private final File dataFolder;
private final DataSource dataSource; private final DataSource dataSource;
@ -58,7 +62,7 @@ public class LoginSecurityConverter implements Converter {
} }
} catch (SQLException e) { } catch (SQLException e) {
sender.sendMessage("Failed to convert from SQLite. Please see the log for more info"); sender.sendMessage("Failed to convert from SQLite. Please see the log for more info");
ConsoleLogger.logException("Could not fetch or migrate data:", e); logger.logException("Could not fetch or migrate data:", e);
} }
} }
@ -119,6 +123,7 @@ public class LoginSecurityConverter implements Converter {
.map(Timestamp::getTime).orElse(null); .map(Timestamp::getTime).orElse(null);
long regDate = Optional.ofNullable(resultSet.getDate("registration_date")) long regDate = Optional.ofNullable(resultSet.getDate("registration_date"))
.map(Date::getTime).orElse(System.currentTimeMillis()); .map(Date::getTime).orElse(System.currentTimeMillis());
UUID uuid = UuidUtils.parseUuidSafely(resultSet.getString("unique_user_id"));
return PlayerAuth.builder() return PlayerAuth.builder()
.name(name) .name(name)
.realName(name) .realName(name)
@ -132,6 +137,7 @@ public class LoginSecurityConverter implements Converter {
.locWorld(resultSet.getString("world")) .locWorld(resultSet.getString("world"))
.locYaw(resultSet.getFloat("yaw")) .locYaw(resultSet.getFloat("yaw"))
.locPitch(resultSet.getFloat("pitch")) .locPitch(resultSet.getFloat("pitch"))
.uuid(uuid)
.build(); .build();
} }
@ -185,7 +191,7 @@ public class LoginSecurityConverter implements Converter {
return DriverManager.getConnection( return DriverManager.getConnection(
"jdbc:sqlite:" + path, "trump", "donald"); "jdbc:sqlite:" + path, "trump", "donald");
} catch (SQLException e) { } catch (SQLException e) {
ConsoleLogger.logException("Could not connect to SQLite database", e); logger.logException("Could not connect to SQLite database", e);
return null; return null;
} }
} }
@ -195,7 +201,7 @@ public class LoginSecurityConverter implements Converter {
return DriverManager.getConnection( return DriverManager.getConnection(
"jdbc:mysql://" + mySqlHost + "/" + mySqlDatabase, mySqlUser, mySqlPassword); "jdbc:mysql://" + mySqlHost + "/" + mySqlDatabase, mySqlUser, mySqlPassword);
} catch (SQLException e) { } catch (SQLException e) {
ConsoleLogger.logException("Could not connect to SQLite database", e); logger.logException("Could not connect to SQLite database", e);
return null; return null;
} }
} }

View File

@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.initialization.DataFolder;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.security.crypts.HashedPassword; import fr.xephi.authme.security.crypts.HashedPassword;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
@ -25,6 +26,7 @@ import java.util.Map.Entry;
*/ */
public class RakamakConverter implements Converter { public class RakamakConverter implements Converter {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(RakamakConverter.class);
private final DataSource database; private final DataSource database;
private final Settings settings; private final Settings settings;
private final File pluginFolder; private final File pluginFolder;
@ -88,7 +90,7 @@ public class RakamakConverter implements Converter {
} }
Utils.logAndSendMessage(sender, "Rakamak database has been imported successfully"); Utils.logAndSendMessage(sender, "Rakamak database has been imported successfully");
} catch (IOException ex) { } catch (IOException ex) {
ConsoleLogger.logException("Can't open the rakamak database file! Does it exist?", ex); logger.logException("Can't open the rakamak database file! Does it exist?", ex);
} }
} }
} }

View File

@ -4,6 +4,7 @@ import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
@ -18,6 +19,9 @@ public class RoyalAuthConverter implements Converter {
private static final String LAST_LOGIN_PATH = "timestamps.quit"; private static final String LAST_LOGIN_PATH = "timestamps.quit";
private static final String PASSWORD_PATH = "login.password"; private static final String PASSWORD_PATH = "login.password";
private final ConsoleLogger logger = ConsoleLoggerFactory.get(RoyalAuthConverter.class);
private final AuthMe plugin; private final AuthMe plugin;
private final DataSource dataSource; private final DataSource dataSource;
@ -48,7 +52,7 @@ public class RoyalAuthConverter implements Converter {
dataSource.saveAuth(auth); dataSource.saveAuth(auth);
dataSource.updateSession(auth); dataSource.updateSession(auth);
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.logException("Error while trying to import " + player.getName() + " RoyalAuth data", e); logger.logException("Error while trying to import " + player.getName() + " RoyalAuth data", e);
} }
} }
} }

View File

@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.initialization.DataFolder;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -18,6 +19,7 @@ import static fr.xephi.authme.util.FileUtils.makePath;
public class VAuthConverter implements Converter { public class VAuthConverter implements Converter {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(VAuthConverter.class);
private final DataSource dataSource; private final DataSource dataSource;
private final File vAuthPasswordsFile; private final File vAuthPasswordsFile;
@ -58,7 +60,7 @@ public class VAuthConverter implements Converter {
dataSource.saveAuth(auth); dataSource.saveAuth(auth);
} }
} catch (IOException e) { } catch (IOException e) {
ConsoleLogger.logException("Error while trying to import some vAuth data", e); logger.logException("Error while trying to import some vAuth data", e);
} }
} }

View File

@ -9,6 +9,7 @@ import fr.xephi.authme.datasource.MySQL;
import fr.xephi.authme.datasource.PostgreSqlDataSource; import fr.xephi.authme.datasource.PostgreSqlDataSource;
import fr.xephi.authme.datasource.SQLite; import fr.xephi.authme.datasource.SQLite;
import fr.xephi.authme.datasource.mysqlextensions.MySqlExtensionsFactory; import fr.xephi.authme.datasource.mysqlextensions.MySqlExtensionsFactory;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.DatabaseSettings; import fr.xephi.authme.settings.properties.DatabaseSettings;
@ -16,7 +17,6 @@ import fr.xephi.authme.settings.properties.DatabaseSettings;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Provider; import javax.inject.Provider;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.sql.SQLException; import java.sql.SQLException;
/** /**
@ -26,6 +26,8 @@ public class DataSourceProvider implements Provider<DataSource> {
private static final int SQLITE_MAX_SIZE = 4000; private static final int SQLITE_MAX_SIZE = 4000;
private final ConsoleLogger logger = ConsoleLoggerFactory.get(DataSourceProvider.class);
@Inject @Inject
@DataFolder @DataFolder
private File dataFolder; private File dataFolder;
@ -46,7 +48,7 @@ public class DataSourceProvider implements Provider<DataSource> {
try { try {
return createDataSource(); return createDataSource();
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.logException("Could not create data source:", e); logger.logException("Could not create data source:", e);
throw new IllegalStateException("Error during initialization of data source", e); throw new IllegalStateException("Error during initialization of data source", e);
} }
} }
@ -54,11 +56,10 @@ public class DataSourceProvider implements Provider<DataSource> {
/** /**
* Sets up the data source. * Sets up the data source.
* *
* @return the constructed datasource * @return the constructed data source
* @throws SQLException when initialization of a SQL datasource failed * @throws SQLException when initialization of a SQL data source failed
* @throws IOException if flat file cannot be read
*/ */
private DataSource createDataSource() throws SQLException, IOException { private DataSource createDataSource() throws SQLException {
DataSourceType dataSourceType = settings.getProperty(DatabaseSettings.BACKEND); DataSourceType dataSourceType = settings.getProperty(DatabaseSettings.BACKEND);
DataSource dataSource; DataSource dataSource;
switch (dataSourceType) { switch (dataSourceType) {
@ -88,7 +89,7 @@ public class DataSourceProvider implements Provider<DataSource> {
bukkitService.runTaskAsynchronously(() -> { bukkitService.runTaskAsynchronously(() -> {
int accounts = dataSource.getAccountsRegistered(); int accounts = dataSource.getAccountsRegistered();
if (accounts >= SQLITE_MAX_SIZE) { if (accounts >= SQLITE_MAX_SIZE) {
ConsoleLogger.warning("YOU'RE USING THE SQLITE DATABASE WITH " logger.warning("YOU'RE USING THE SQLITE DATABASE WITH "
+ accounts + "+ ACCOUNTS; FOR BETTER PERFORMANCE, PLEASE UPGRADE TO MYSQL!!"); + accounts + "+ ACCOUNTS; FOR BETTER PERFORMANCE, PLEASE UPGRADE TO MYSQL!!");
} }
}); });

View File

@ -3,6 +3,7 @@ package fr.xephi.authme.initialization;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.message.Messages; import fr.xephi.authme.message.Messages;
import fr.xephi.authme.output.ConsoleFilter; import fr.xephi.authme.output.ConsoleFilter;
@ -28,6 +29,8 @@ import static fr.xephi.authme.settings.properties.EmailSettings.RECALL_PLAYERS;
*/ */
public class OnStartupTasks { public class OnStartupTasks {
private static ConsoleLogger consoleLogger = ConsoleLoggerFactory.get(OnStartupTasks.class);
@Inject @Inject
private DataSource dataSource; private DataSource dataSource;
@Inject @Inject
@ -58,17 +61,16 @@ public class OnStartupTasks {
/** /**
* Sets up the console filter if enabled. * Sets up the console filter if enabled.
* *
* @param settings the settings * @param logger the plugin logger
* @param logger the plugin logger
*/ */
public static void setupConsoleFilter(Settings settings, Logger logger) { public static void setupConsoleFilter(Logger logger) {
// Try to set the log4j filter // Try to set the log4j filter
try { try {
Class.forName("org.apache.logging.log4j.core.filter.AbstractFilter"); Class.forName("org.apache.logging.log4j.core.filter.AbstractFilter");
setLog4JFilter(); setLog4JFilter();
} catch (ClassNotFoundException | NoClassDefFoundError e) { } catch (ClassNotFoundException | NoClassDefFoundError e) {
// log4j is not available // log4j is not available
ConsoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support will be disabled"); consoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support will be disabled");
ConsoleFilter filter = new ConsoleFilter(); ConsoleFilter filter = new ConsoleFilter();
logger.setFilter(filter); logger.setFilter(filter);
Bukkit.getLogger().setFilter(filter); Bukkit.getLogger().setFilter(filter);

View File

@ -1,6 +1,7 @@
package fr.xephi.authme.listener; package fr.xephi.authme.listener;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import org.bukkit.entity.LivingEntity; import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile; import org.bukkit.entity.Projectile;
@ -22,18 +23,21 @@ import java.lang.reflect.Method;
public class EntityListener implements Listener { public class EntityListener implements Listener {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(EntityListener.class);
private final ListenerService listenerService; private final ListenerService listenerService;
private Method getShooter; private Method getShooter;
private boolean shooterIsLivingEntity; private boolean shooterIsLivingEntity;
@Inject @Inject
EntityListener(ListenerService listenerService) { EntityListener(ListenerService listenerService) {
this.listenerService = listenerService; this.listenerService = listenerService;
try { try {
getShooter = Projectile.class.getDeclaredMethod("getShooter"); getShooter = Projectile.class.getDeclaredMethod("getShooter");
shooterIsLivingEntity = getShooter.getReturnType() == LivingEntity.class; shooterIsLivingEntity = getShooter.getReturnType() == LivingEntity.class;
} catch (NoSuchMethodException | SecurityException e) { } catch (NoSuchMethodException | SecurityException e) {
ConsoleLogger.logException("Cannot load getShooter() method on Projectile class", e); logger.logException("Cannot load getShooter() method on Projectile class", e);
} }
} }
@ -107,7 +111,7 @@ public class EntityListener implements Listener {
} }
shooterRaw = getShooter.invoke(projectile); shooterRaw = getShooter.invoke(projectile);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
ConsoleLogger.logException("Error getting shooter", e); logger.logException("Error getting shooter", e);
} }
} else { } else {
shooterRaw = projectile.getShooter(); shooterRaw = projectile.getShooter();

View File

@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.initialization.Reloadable; import fr.xephi.authme.initialization.Reloadable;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.message.Messages; import fr.xephi.authme.message.Messages;
import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PermissionsManager;
@ -30,6 +31,8 @@ import java.util.regex.Pattern;
* Service for performing various verifications when a player joins. * Service for performing various verifications when a player joins.
*/ */
public class OnJoinVerifier implements Reloadable { public class OnJoinVerifier implements Reloadable {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(OnJoinVerifier.class);
@Inject @Inject
private Settings settings; private Settings settings;
@ -139,7 +142,7 @@ public class OnJoinVerifier implements Reloadable {
event.allow(); event.allow();
return false; return false;
} else { } else {
ConsoleLogger.info("VIP player " + player.getName() + " tried to join, but the server was full"); logger.info("VIP player " + player.getName() + " tried to join, but the server was full");
event.setKickMessage(messages.retrieveSingle(player, MessageKey.KICK_FULL_SERVER)); event.setKickMessage(messages.retrieveSingle(player, MessageKey.KICK_FULL_SERVER));
return true; return true;
} }

View File

@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.QuickCommandsProtectionManager; import fr.xephi.authme.data.QuickCommandsProtectionManager;
import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.message.Messages; import fr.xephi.authme.message.Messages;
import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PermissionsManager;
@ -69,6 +70,8 @@ import static fr.xephi.authme.settings.properties.RestrictionSettings.ALLOW_UNAU
*/ */
public class PlayerListener implements Listener { public class PlayerListener implements Listener {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(PlayerListener.class);
@Inject @Inject
private Settings settings; private Settings settings;
@Inject @Inject
@ -289,7 +292,7 @@ public class PlayerListener implements Listener {
try { try {
permissionsManager.loadUserData(event.getUniqueId()); permissionsManager.loadUserData(event.getUniqueId());
} catch (PermissionLoadUserException e) { } catch (PermissionLoadUserException e) {
ConsoleLogger.logException("Unable to load the permission data of user " + name, e); logger.logException("Unable to load the permission data of user " + name, e);
} }
// getAddress() sometimes returning null if not yet resolved // getAddress() sometimes returning null if not yet resolved

View File

@ -1,6 +1,7 @@
package fr.xephi.authme.listener; package fr.xephi.authme.listener;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.listener.protocollib.ProtocolLibService; import fr.xephi.authme.listener.protocollib.ProtocolLibService;
import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.service.PluginHookService; import fr.xephi.authme.service.PluginHookService;
@ -14,8 +15,11 @@ import org.bukkit.event.server.PluginEnableEvent;
import javax.inject.Inject; import javax.inject.Inject;
/** /**
* Listener for server events.
*/ */
public class ServerListener implements Listener { public class ServerListener implements Listener {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(ServerListener.class);
@Inject @Inject
private PluginHookService pluginHookService; private PluginHookService pluginHookService;
@ -40,20 +44,20 @@ public class ServerListener implements Listener {
if ("Essentials".equalsIgnoreCase(pluginName)) { if ("Essentials".equalsIgnoreCase(pluginName)) {
pluginHookService.unhookEssentials(); pluginHookService.unhookEssentials();
ConsoleLogger.info("Essentials has been disabled: unhooking"); logger.info("Essentials has been disabled: unhooking");
} else if ("CMI".equalsIgnoreCase(pluginName)) { } else if ("CMI".equalsIgnoreCase(pluginName)) {
pluginHookService.unhookCmi(); pluginHookService.unhookCmi();
spawnLoader.unloadCmiSpawn(); spawnLoader.unloadCmiSpawn();
ConsoleLogger.info("CMI has been disabled: unhooking"); logger.info("CMI has been disabled: unhooking");
} else if ("Multiverse-Core".equalsIgnoreCase(pluginName)) { } else if ("Multiverse-Core".equalsIgnoreCase(pluginName)) {
pluginHookService.unhookMultiverse(); pluginHookService.unhookMultiverse();
ConsoleLogger.info("Multiverse-Core has been disabled: unhooking"); logger.info("Multiverse-Core has been disabled: unhooking");
} else if ("EssentialsSpawn".equalsIgnoreCase(pluginName)) { } else if ("EssentialsSpawn".equalsIgnoreCase(pluginName)) {
spawnLoader.unloadEssentialsSpawn(); spawnLoader.unloadEssentialsSpawn();
ConsoleLogger.info("EssentialsSpawn has been disabled: unhooking"); logger.info("EssentialsSpawn has been disabled: unhooking");
} else if ("ProtocolLib".equalsIgnoreCase(pluginName)) { } else if ("ProtocolLib".equalsIgnoreCase(pluginName)) {
protocolLibService.disable(); protocolLibService.disable();
ConsoleLogger.warning("ProtocolLib has been disabled, unhooking packet adapters!"); logger.warning("ProtocolLib has been disabled, unhooking packet adapters!");
} }
} }

View File

@ -28,8 +28,8 @@ import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.BukkitService;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@ -48,6 +48,7 @@ class InventoryPacketAdapter extends PacketAdapter {
private static final int MAIN_SIZE = 27; private static final int MAIN_SIZE = 27;
private static final int HOTBAR_SIZE = 9; private static final int HOTBAR_SIZE = 9;
private final ConsoleLogger logger = ConsoleLoggerFactory.get(InventoryPacketAdapter.class);
private final PlayerCache playerCache; private final PlayerCache playerCache;
private final DataSource dataSource; private final DataSource dataSource;
@ -106,7 +107,7 @@ class InventoryPacketAdapter extends PacketAdapter {
try { try {
protocolManager.sendServerPacket(player, inventoryPacket, false); protocolManager.sendServerPacket(player, inventoryPacket, false);
} catch (InvocationTargetException invocationExc) { } catch (InvocationTargetException invocationExc) {
ConsoleLogger.logException("Error during sending blank inventory", invocationExc); logger.logException("Error during sending blank inventory", invocationExc);
} }
} }
} }

View File

@ -6,6 +6,7 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.initialization.SettingsDependent; import fr.xephi.authme.initialization.SettingsDependent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.RestrictionSettings; import fr.xephi.authme.settings.properties.RestrictionSettings;
@ -16,6 +17,8 @@ import javax.inject.Inject;
@NoFieldScan @NoFieldScan
public class ProtocolLibService implements SettingsDependent { public class ProtocolLibService implements SettingsDependent {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(ProtocolLibService.class);
/* Packet Adapters */ /* Packet Adapters */
private InventoryPacketAdapter inventoryPacketAdapter; private InventoryPacketAdapter inventoryPacketAdapter;
private TabCompletePacketAdapter tabCompletePacketAdapter; private TabCompletePacketAdapter tabCompletePacketAdapter;
@ -28,10 +31,10 @@ public class ProtocolLibService implements SettingsDependent {
/* Service */ /* Service */
private boolean isEnabled; private boolean isEnabled;
private AuthMe plugin; private final AuthMe plugin;
private BukkitService bukkitService; private final BukkitService bukkitService;
private PlayerCache playerCache; private final PlayerCache playerCache;
private DataSource dataSource; private final DataSource dataSource;
@Inject @Inject
ProtocolLibService(AuthMe plugin, Settings settings, BukkitService bukkitService, PlayerCache playerCache, ProtocolLibService(AuthMe plugin, Settings settings, BukkitService bukkitService, PlayerCache playerCache,
@ -50,11 +53,11 @@ public class ProtocolLibService implements SettingsDependent {
// Check if ProtocolLib is enabled on the server. // Check if ProtocolLib is enabled on the server.
if (!plugin.getServer().getPluginManager().isPluginEnabled("ProtocolLib")) { if (!plugin.getServer().getPluginManager().isPluginEnabled("ProtocolLib")) {
if (protectInvBeforeLogin) { if (protectInvBeforeLogin) {
ConsoleLogger.warning("WARNING! The protectInventory feature requires ProtocolLib! Disabling it..."); logger.warning("WARNING! The protectInventory feature requires ProtocolLib! Disabling it...");
} }
if (denyTabCompleteBeforeLogin) { if (denyTabCompleteBeforeLogin) {
ConsoleLogger.warning("WARNING! The denyTabComplete feature requires ProtocolLib! Disabling it..."); logger.warning("WARNING! The denyTabComplete feature requires ProtocolLib! Disabling it...");
} }
if (freezePlayerBeforeLogin) { if (freezePlayerBeforeLogin) {

View File

@ -9,9 +9,11 @@ import com.comphenix.protocol.reflect.FieldAccessException;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.output.ConsoleLoggerFactory;
class TabCompletePacketAdapter extends PacketAdapter { class TabCompletePacketAdapter extends PacketAdapter {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(TabCompletePacketAdapter.class);
private final PlayerCache playerCache; private final PlayerCache playerCache;
TabCompletePacketAdapter(AuthMe plugin, PlayerCache playerCache) { TabCompletePacketAdapter(AuthMe plugin, PlayerCache playerCache) {
@ -27,7 +29,7 @@ class TabCompletePacketAdapter extends PacketAdapter {
event.setCancelled(true); event.setCancelled(true);
} }
} catch (FieldAccessException e) { } catch (FieldAccessException e) {
ConsoleLogger.logException("Couldn't access field:", e); logger.logException("Couldn't access field:", e);
} }
} }
} }

View File

@ -2,6 +2,7 @@ package fr.xephi.authme.mail;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.initialization.DataFolder;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.EmailSettings; import fr.xephi.authme.settings.properties.EmailSettings;
import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.PluginSettings;
@ -22,6 +23,8 @@ import java.io.IOException;
*/ */
public class EmailService { public class EmailService {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(EmailService.class);
private final File dataFolder; private final File dataFolder;
private final Settings settings; private final Settings settings;
private final SendMailSsl sendMailSsl; private final SendMailSsl sendMailSsl;
@ -48,7 +51,7 @@ public class EmailService {
*/ */
public boolean sendPasswordMail(String name, String mailAddress, String newPass) { public boolean sendPasswordMail(String name, String mailAddress, String newPass) {
if (!hasAllInformation()) { if (!hasAllInformation()) {
ConsoleLogger.warning("Cannot perform email registration: not all email settings are complete"); logger.warning("Cannot perform email registration: not all email settings are complete");
return false; return false;
} }
@ -56,7 +59,7 @@ public class EmailService {
try { try {
email = sendMailSsl.initializeMail(mailAddress); email = sendMailSsl.initializeMail(mailAddress);
} catch (EmailException e) { } catch (EmailException e) {
ConsoleLogger.logException("Failed to create email with the given settings:", e); logger.logException("Failed to create email with the given settings:", e);
return false; return false;
} }
@ -68,7 +71,7 @@ public class EmailService {
file = generatePasswordImage(name, newPass); file = generatePasswordImage(name, newPass);
mailText = embedImageIntoEmailContent(file, email, mailText); mailText = embedImageIntoEmailContent(file, email, mailText);
} catch (IOException | EmailException e) { } catch (IOException | EmailException e) {
ConsoleLogger.logException( logger.logException(
"Unable to send new password as image for email " + mailAddress + ":", e); "Unable to send new password as image for email " + mailAddress + ":", e);
} }
} }
@ -88,7 +91,7 @@ public class EmailService {
*/ */
public boolean sendVerificationMail(String name, String mailAddress, String code) { public boolean sendVerificationMail(String name, String mailAddress, String code) {
if (!hasAllInformation()) { if (!hasAllInformation()) {
ConsoleLogger.warning("Cannot send verification email: not all email settings are complete"); logger.warning("Cannot send verification email: not all email settings are complete");
return false; return false;
} }
@ -96,7 +99,7 @@ public class EmailService {
try { try {
email = sendMailSsl.initializeMail(mailAddress); email = sendMailSsl.initializeMail(mailAddress);
} catch (EmailException e) { } catch (EmailException e) {
ConsoleLogger.logException("Failed to create verification email with the given settings:", e); logger.logException("Failed to create verification email with the given settings:", e);
return false; return false;
} }
@ -118,7 +121,7 @@ public class EmailService {
try { try {
htmlEmail = sendMailSsl.initializeMail(email); htmlEmail = sendMailSsl.initializeMail(email);
} catch (EmailException e) { } catch (EmailException e) {
ConsoleLogger.logException("Failed to create email for recovery code:", e); logger.logException("Failed to create email for recovery code:", e);
return false; return false;
} }

View File

@ -1,6 +1,7 @@
package fr.xephi.authme.mail; package fr.xephi.authme.mail;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.output.LogLevel; import fr.xephi.authme.output.LogLevel;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.EmailSettings; import fr.xephi.authme.settings.properties.EmailSettings;
@ -26,6 +27,8 @@ import static fr.xephi.authme.settings.properties.EmailSettings.MAIL_PASSWORD;
*/ */
public class SendMailSsl { public class SendMailSsl {
private ConsoleLogger logger = ConsoleLoggerFactory.get(SendMailSsl.class);
@Inject @Inject
private Settings settings; private Settings settings;
@ -96,14 +99,14 @@ public class SendMailSsl {
email.setHtmlMsg(content); email.setHtmlMsg(content);
email.setTextMsg(content); email.setTextMsg(content);
} catch (EmailException e) { } catch (EmailException e) {
ConsoleLogger.logException("Your email.html config contains an error and cannot be sent:", e); logger.logException("Your email.html config contains an error and cannot be sent:", e);
return false; return false;
} }
try { try {
email.send(); email.send();
return true; return true;
} catch (EmailException e) { } catch (EmailException e) {
ConsoleLogger.logException("Failed to send a mail to " + email.getToAddresses() + ":", e); logger.logException("Failed to send a mail to " + email.getToAddresses() + ":", e);
return false; return false;
} }
} }

View File

@ -4,6 +4,7 @@ import com.google.common.annotations.VisibleForTesting;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.initialization.DataFolder;
import fr.xephi.authme.initialization.Reloadable; import fr.xephi.authme.initialization.Reloadable;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.PluginSettings;
import fr.xephi.authme.util.FileUtils; import fr.xephi.authme.util.FileUtils;
@ -21,6 +22,8 @@ import static fr.xephi.authme.message.MessagePathHelper.DEFAULT_LANGUAGE;
*/ */
public abstract class AbstractMessageFileHandler implements Reloadable { public abstract class AbstractMessageFileHandler implements Reloadable {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(AbstractMessageFileHandler.class);
@DataFolder @DataFolder
@Inject @Inject
private File dataFolder; private File dataFolder;
@ -116,8 +119,7 @@ public abstract class AbstractMessageFileHandler implements Reloadable {
if (FileUtils.copyFileFromResource(file, defaultFile)) { if (FileUtils.copyFileFromResource(file, defaultFile)) {
return file; return file;
} else { } else {
ConsoleLogger.warning("Wanted to copy default messages file '" + defaultFile logger.warning("Wanted to copy default messages file '" + defaultFile + "' from JAR but it didn't exist");
+ "' from JAR but it didn't exist");
return null; return null;
} }
} }

View File

@ -1,6 +1,7 @@
package fr.xephi.authme.message; package fr.xephi.authme.message;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.util.FileUtils; import fr.xephi.authme.util.FileUtils;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
@ -16,6 +17,8 @@ import static fr.xephi.authme.message.MessagePathHelper.DEFAULT_LANGUAGE;
*/ */
public class HelpMessagesFileHandler extends AbstractMessageFileHandler { public class HelpMessagesFileHandler extends AbstractMessageFileHandler {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(HelpMessagesFileHandler.class);
private FileConfiguration defaultConfiguration; private FileConfiguration defaultConfiguration;
@Inject // Trigger injection in the superclass @Inject // Trigger injection in the superclass
@ -33,7 +36,7 @@ public class HelpMessagesFileHandler extends AbstractMessageFileHandler {
String message = getMessageIfExists(key); String message = getMessageIfExists(key);
if (message == null) { if (message == null) {
ConsoleLogger.warning("Error getting message with key '" + key + "'. " logger.warning("Error getting message with key '" + key + "'. "
+ "Please update your config file '" + getFilename() + "' or run /authme messages help"); + "Please update your config file '" + getFilename() + "' or run /authme messages help");
return getDefault(key); return getDefault(key);
} }

View File

@ -2,6 +2,8 @@ package fr.xephi.authme.message;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.mail.EmailService;
import fr.xephi.authme.util.expiring.Duration; import fr.xephi.authme.util.expiring.Duration;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -37,6 +39,8 @@ public class Messages {
.put(TimeUnit.HOURS, MessageKey.HOURS) .put(TimeUnit.HOURS, MessageKey.HOURS)
.put(TimeUnit.DAYS, MessageKey.DAYS).build(); .put(TimeUnit.DAYS, MessageKey.DAYS).build();
private final ConsoleLogger logger = ConsoleLoggerFactory.get(EmailService.class);
private MessagesFileHandler messagesFileHandler; private MessagesFileHandler messagesFileHandler;
/* /*
@ -162,7 +166,7 @@ public class Messages {
message = message.replace(tags[i], replacements[i]); message = message.replace(tags[i], replacements[i]);
} }
} else { } else {
ConsoleLogger.warning("Invalid number of replacements for message key '" + key + "'"); logger.warning("Invalid number of replacements for message key '" + key + "'");
} }
return message; return message;
} }
@ -185,7 +189,7 @@ public class Messages {
message = message.replace(tags[i], replacements[i]); message = message.replace(tags[i], replacements[i]);
} }
} else { } else {
ConsoleLogger.warning("Invalid number of replacements for message key '" + key + "'"); logger.warning("Invalid number of replacements for message key '" + key + "'");
} }
return message; return message;
} }

View File

@ -1,6 +1,7 @@
package fr.xephi.authme.message; package fr.xephi.authme.message;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.updater.MessageUpdater; import fr.xephi.authme.message.updater.MessageUpdater;
import javax.inject.Inject; import javax.inject.Inject;
@ -12,6 +13,8 @@ import static fr.xephi.authme.message.MessagePathHelper.DEFAULT_LANGUAGE;
*/ */
public class MessagesFileHandler extends AbstractMessageFileHandler { public class MessagesFileHandler extends AbstractMessageFileHandler {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(MessagesFileHandler.class);
@Inject @Inject
private MessageUpdater messageUpdater; private MessageUpdater messageUpdater;
@ -31,7 +34,7 @@ public class MessagesFileHandler extends AbstractMessageFileHandler {
getUserLanguageFile(), createFilePath(language), createFilePath(DEFAULT_LANGUAGE)); getUserLanguageFile(), createFilePath(language), createFilePath(DEFAULT_LANGUAGE));
if (hasChange) { if (hasChange) {
if (isFromReload) { if (isFromReload) {
ConsoleLogger.warning("Migration after reload attempt"); logger.warning("Migration after reload attempt");
} else { } else {
reloadInternal(true); reloadInternal(true);
} }

View File

@ -3,6 +3,7 @@ package fr.xephi.authme.message.updater;
import ch.jalu.configme.properties.Property; import ch.jalu.configme.properties.Property;
import ch.jalu.configme.resource.PropertyReader; import ch.jalu.configme.resource.PropertyReader;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.util.FileUtils; import fr.xephi.authme.util.FileUtils;
import java.io.IOException; import java.io.IOException;
@ -14,6 +15,7 @@ import java.io.InputStream;
*/ */
public class JarMessageSource { public class JarMessageSource {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(JarMessageSource.class);
private final PropertyReader localJarMessages; private final PropertyReader localJarMessages;
private final PropertyReader defaultJarMessages; private final PropertyReader defaultJarMessages;
@ -42,15 +44,15 @@ public class JarMessageSource {
return reader == null ? null : reader.getString(path); return reader == null ? null : reader.getString(path);
} }
private static MessageMigraterPropertyReader loadJarFile(String jarPath) { private MessageMigraterPropertyReader loadJarFile(String jarPath) {
try (InputStream stream = FileUtils.getResourceFromJar(jarPath)) { try (InputStream stream = FileUtils.getResourceFromJar(jarPath)) {
if (stream == null) { if (stream == null) {
ConsoleLogger.debug("Could not load '" + jarPath + "' from JAR"); logger.debug("Could not load '" + jarPath + "' from JAR");
return null; return null;
} }
return MessageMigraterPropertyReader.loadFromStream(stream); return MessageMigraterPropertyReader.loadFromStream(stream);
} catch (IOException e) { } catch (IOException e) {
ConsoleLogger.logException("Exception while handling JAR path '" + jarPath + "'", e); logger.logException("Exception while handling JAR path '" + jarPath + "'", e);
} }
return null; return null;
} }

View File

@ -9,6 +9,7 @@ import ch.jalu.configme.resource.PropertyResource;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.io.Files; import com.google.common.io.Files;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.util.FileUtils; import fr.xephi.authme.util.FileUtils;
@ -29,6 +30,8 @@ import static java.util.Collections.singletonList;
*/ */
public class MessageUpdater { public class MessageUpdater {
private ConsoleLogger logger = ConsoleLoggerFactory.get(MessageUpdater.class);
/** /**
* Applies any necessary migrations to the user's messages file and saves it if it has been modified. * Applies any necessary migrations to the user's messages file and saves it if it has been modified.
* *
@ -68,7 +71,7 @@ public class MessageUpdater {
backupMessagesFile(userFile); backupMessagesFile(userFile);
userResource.exportProperties(configurationData); userResource.exportProperties(configurationData);
ConsoleLogger.debug("Successfully saved {0}", userFile); logger.debug("Successfully saved {0}", userFile);
return true; return true;
} }
return false; return false;
@ -91,7 +94,7 @@ public class MessageUpdater {
private boolean migrateOldKeys(PropertyReader propertyReader, MessageKeyConfigurationData configurationData) { private boolean migrateOldKeys(PropertyReader propertyReader, MessageKeyConfigurationData configurationData) {
boolean hasChange = OldMessageKeysMigrater.migrateOldPaths(propertyReader, configurationData); boolean hasChange = OldMessageKeysMigrater.migrateOldPaths(propertyReader, configurationData);
if (hasChange) { if (hasChange) {
ConsoleLogger.info("Old keys have been moved to the new ones in your messages_xx.yml file"); logger.info("Old keys have been moved to the new ones in your messages_xx.yml file");
} }
return hasChange; return hasChange;
} }
@ -106,7 +109,7 @@ public class MessageUpdater {
} }
} }
if (!addedKeys.isEmpty()) { if (!addedKeys.isEmpty()) {
ConsoleLogger.info( logger.info(
"Added " + addedKeys.size() + " missing keys to your messages_xx.yml file: " + addedKeys); "Added " + addedKeys.size() + " missing keys to your messages_xx.yml file: " + addedKeys);
return true; return true;
} }

View File

@ -0,0 +1,51 @@
package fr.xephi.authme.output;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.settings.Settings;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Creates and keeps track of {@link ConsoleLogger} instances.
*/
public final class ConsoleLoggerFactory {
private static final Map<String, ConsoleLogger> consoleLoggers = new ConcurrentHashMap<>();
private static Settings settings;
private ConsoleLoggerFactory() {
}
/**
* Creates or returns the already existing logger associated with the given class.
*
* @param owningClass the class whose logger should be retrieved
* @return logger for the given class
*/
public static ConsoleLogger get(Class<?> owningClass) {
String name = owningClass.getCanonicalName();
return consoleLoggers.computeIfAbsent(name, ConsoleLoggerFactory::createLogger);
}
/**
* Sets up all loggers according to the properties returned by the settings instance.
*
* @param settings the settings instance
*/
public static void reloadSettings(Settings settings) {
ConsoleLoggerFactory.settings = settings;
ConsoleLogger.initializeSharedSettings(settings);
consoleLoggers.values()
.forEach(logger -> logger.initializeSettings(settings));
}
private static ConsoleLogger createLogger(String name) {
ConsoleLogger logger = new ConsoleLogger(name);
if (settings != null) {
logger.initializeSettings(settings);
}
return logger;
}
}

View File

@ -3,6 +3,7 @@ package fr.xephi.authme.permission;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.initialization.Reloadable; import fr.xephi.authme.initialization.Reloadable;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.listener.JoiningPlayer; import fr.xephi.authme.listener.JoiningPlayer;
import fr.xephi.authme.permission.handlers.LuckPermsHandler; import fr.xephi.authme.permission.handlers.LuckPermsHandler;
import fr.xephi.authme.permission.handlers.PermissionHandler; import fr.xephi.authme.permission.handlers.PermissionHandler;
@ -40,6 +41,7 @@ import java.util.UUID;
*/ */
public class PermissionsManager implements Reloadable { public class PermissionsManager implements Reloadable {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(PermissionsManager.class);
private final Server server; private final Server server;
private final PluginManager pluginManager; private final PluginManager pluginManager;
private final Settings settings; private final Settings settings;
@ -78,11 +80,11 @@ public class PermissionsManager implements Reloadable {
if (handler != null) { if (handler != null) {
// Show a success message and return // Show a success message and return
this.handler = handler; this.handler = handler;
ConsoleLogger.info("Hooked into " + PermissionsSystemType.VAULT.getDisplayName() + "!"); logger.info("Hooked into " + PermissionsSystemType.VAULT.getDisplayName() + "!");
return; return;
} }
} catch (PermissionHandlerException e) { } catch (PermissionHandlerException e) {
ConsoleLogger.logException("Failed to create Vault hook (forced):", e); logger.logException("Failed to create Vault hook (forced):", e);
} }
} else { } else {
// Loop through all the available permissions system types // Loop through all the available permissions system types
@ -92,18 +94,18 @@ public class PermissionsManager implements Reloadable {
if (handler != null) { if (handler != null) {
// Show a success message and return // Show a success message and return
this.handler = handler; this.handler = handler;
ConsoleLogger.info("Hooked into " + type.getDisplayName() + "!"); logger.info("Hooked into " + type.getDisplayName() + "!");
return; return;
} }
} catch (Exception ex) { } catch (Exception ex) {
// An error occurred, show a warning message // An error occurred, show a warning message
ConsoleLogger.logException("Error while hooking into " + type.getDisplayName(), ex); logger.logException("Error while hooking into " + type.getDisplayName(), ex);
} }
} }
} }
// No recognized permissions system found, show a message and return // No recognized permissions system found, show a message and return
ConsoleLogger.info("No supported permissions system found! Permissions are disabled!"); logger.info("No supported permissions system found! Permissions are disabled!");
} }
/** /**
@ -125,7 +127,7 @@ public class PermissionsManager implements Reloadable {
// Make sure the plugin is enabled before hooking // Make sure the plugin is enabled before hooking
if (!plugin.isEnabled()) { if (!plugin.isEnabled()) {
ConsoleLogger.info("Not hooking into " + type.getDisplayName() + " because it's disabled!"); logger.info("Not hooking into " + type.getDisplayName() + " because it's disabled!");
return null; return null;
} }
@ -151,7 +153,7 @@ public class PermissionsManager implements Reloadable {
this.handler = null; this.handler = null;
// Print a status message to the console // Print a status message to the console
ConsoleLogger.info("Unhooked from Permissions!"); logger.info("Unhooked from Permissions!");
} }
/** /**
@ -174,7 +176,7 @@ public class PermissionsManager implements Reloadable {
public void onPluginEnable(String pluginName) { public void onPluginEnable(String pluginName) {
// Check if any known permissions system is enabling // Check if any known permissions system is enabling
if (PermissionsSystemType.isPermissionSystem(pluginName)) { if (PermissionsSystemType.isPermissionSystem(pluginName)) {
ConsoleLogger.info(pluginName + " plugin enabled, dynamically updating permissions hooks!"); logger.info(pluginName + " plugin enabled, dynamically updating permissions hooks!");
setup(); setup();
} }
} }
@ -187,7 +189,7 @@ public class PermissionsManager implements Reloadable {
public void onPluginDisable(String pluginName) { public void onPluginDisable(String pluginName) {
// Check if any known permission system is being disabled // Check if any known permission system is being disabled
if (PermissionsSystemType.isPermissionSystem(pluginName)) { if (PermissionsSystemType.isPermissionSystem(pluginName)) {
ConsoleLogger.info(pluginName + " plugin disabled, updating hooks!"); logger.info(pluginName + " plugin disabled, updating hooks!");
setup(); setup();
} }
} }
@ -454,7 +456,7 @@ public class PermissionsManager implements Reloadable {
try { try {
loadUserData(offlinePlayer.getUniqueId()); loadUserData(offlinePlayer.getUniqueId());
} catch (PermissionLoadUserException e) { } catch (PermissionLoadUserException e) {
ConsoleLogger.logException("Unable to load the permission data of user " + offlinePlayer.getName(), e); logger.logException("Unable to load the permission data of user " + offlinePlayer.getName(), e);
return false; return false;
} }
return true; return true;

View File

@ -1,6 +1,7 @@
package fr.xephi.authme.permission.handlers; package fr.xephi.authme.permission.handlers;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.permission.PermissionNode; import fr.xephi.authme.permission.PermissionNode;
import fr.xephi.authme.permission.PermissionsSystemType; import fr.xephi.authme.permission.PermissionsSystemType;
import me.lucko.luckperms.LuckPerms; import me.lucko.luckperms.LuckPerms;
@ -31,6 +32,7 @@ import java.util.stream.Collectors;
*/ */
public class LuckPermsHandler implements PermissionHandler { public class LuckPermsHandler implements PermissionHandler {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(LuckPermsHandler.class);
private LuckPermsApi luckPermsApi; private LuckPermsApi luckPermsApi;
public LuckPermsHandler() throws PermissionHandlerException { public LuckPermsHandler() throws PermissionHandlerException {
@ -79,7 +81,7 @@ public class LuckPermsHandler implements PermissionHandler {
public boolean hasPermissionOffline(String name, PermissionNode node) { public boolean hasPermissionOffline(String name, PermissionNode node) {
User user = luckPermsApi.getUser(name); User user = luckPermsApi.getUser(name);
if (user == null) { if (user == null) {
ConsoleLogger.warning("LuckPermsHandler: tried to check permission for offline user " logger.warning("LuckPermsHandler: tried to check permission for offline user "
+ name + " but it isn't loaded!"); + name + " but it isn't loaded!");
return false; return false;
} }
@ -96,7 +98,7 @@ public class LuckPermsHandler implements PermissionHandler {
public boolean isInGroup(OfflinePlayer player, String group) { public boolean isInGroup(OfflinePlayer player, String group) {
User user = luckPermsApi.getUser(player.getName()); User user = luckPermsApi.getUser(player.getName());
if (user == null) { if (user == null) {
ConsoleLogger.warning("LuckPermsHandler: tried to check group for offline user " logger.warning("LuckPermsHandler: tried to check group for offline user "
+ player.getName() + " but it isn't loaded!"); + player.getName() + " but it isn't loaded!");
return false; return false;
} }
@ -112,7 +114,7 @@ public class LuckPermsHandler implements PermissionHandler {
public boolean removeFromGroup(OfflinePlayer player, String group) { public boolean removeFromGroup(OfflinePlayer player, String group) {
User user = luckPermsApi.getUser(player.getName()); User user = luckPermsApi.getUser(player.getName());
if (user == null) { if (user == null) {
ConsoleLogger.warning("LuckPermsHandler: tried to remove group for offline user " logger.warning("LuckPermsHandler: tried to remove group for offline user "
+ player.getName() + " but it isn't loaded!"); + player.getName() + " but it isn't loaded!");
return false; return false;
} }
@ -133,7 +135,7 @@ public class LuckPermsHandler implements PermissionHandler {
public boolean setGroup(OfflinePlayer player, String group) { public boolean setGroup(OfflinePlayer player, String group) {
User user = luckPermsApi.getUser(player.getName()); User user = luckPermsApi.getUser(player.getName());
if (user == null) { if (user == null) {
ConsoleLogger.warning("LuckPermsHandler: tried to set group for offline user " logger.warning("LuckPermsHandler: tried to set group for offline user "
+ player.getName() + " but it isn't loaded!"); + player.getName() + " but it isn't loaded!");
return false; return false;
} }
@ -157,7 +159,7 @@ public class LuckPermsHandler implements PermissionHandler {
public List<String> getGroups(OfflinePlayer player) { public List<String> getGroups(OfflinePlayer player) {
User user = luckPermsApi.getUser(player.getName()); User user = luckPermsApi.getUser(player.getName());
if (user == null) { if (user == null) {
ConsoleLogger.warning("LuckPermsHandler: tried to get groups for offline user " logger.warning("LuckPermsHandler: tried to get groups for offline user "
+ player.getName() + " but it isn't loaded!"); + player.getName() + " but it isn't loaded!");
return Collections.emptyList(); return Collections.emptyList();
} }

View File

@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.process.AsynchronousProcess; import fr.xephi.authme.process.AsynchronousProcess;
import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.security.PasswordSecurity;
@ -17,6 +18,8 @@ import org.bukkit.entity.Player;
import javax.inject.Inject; import javax.inject.Inject;
public class AsyncChangePassword implements AsynchronousProcess { public class AsyncChangePassword implements AsynchronousProcess {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(AsyncChangePassword.class);
@Inject @Inject
private DataSource dataSource; private DataSource dataSource;
@ -58,7 +61,7 @@ public class AsyncChangePassword implements AsynchronousProcess {
playerCache.updatePlayer(auth); playerCache.updatePlayer(auth);
commonService.send(player, MessageKey.PASSWORD_CHANGED_SUCCESS); commonService.send(player, MessageKey.PASSWORD_CHANGED_SUCCESS);
ConsoleLogger.info(player.getName() + " changed his password"); logger.info(player.getName() + " changed his password");
} else { } else {
commonService.send(player, MessageKey.WRONG_PASSWORD); commonService.send(player, MessageKey.WRONG_PASSWORD);
} }
@ -75,7 +78,7 @@ public class AsyncChangePassword implements AsynchronousProcess {
final String lowerCaseName = playerName.toLowerCase(); final String lowerCaseName = playerName.toLowerCase();
if (!(playerCache.isAuthenticated(lowerCaseName) || dataSource.isAuthAvailable(lowerCaseName))) { if (!(playerCache.isAuthenticated(lowerCaseName) || dataSource.isAuthAvailable(lowerCaseName))) {
if (sender == null) { if (sender == null) {
ConsoleLogger.warning("Tried to change password for user " + lowerCaseName + " but it doesn't exist!"); logger.warning("Tried to change password for user " + lowerCaseName + " but it doesn't exist!");
} else { } else {
commonService.send(sender, MessageKey.UNKNOWN_USER); commonService.send(sender, MessageKey.UNKNOWN_USER);
} }
@ -87,15 +90,15 @@ public class AsyncChangePassword implements AsynchronousProcess {
bungeeSender.sendAuthMeBungeecordMessage(MessageType.REFRESH_PASSWORD, lowerCaseName); bungeeSender.sendAuthMeBungeecordMessage(MessageType.REFRESH_PASSWORD, lowerCaseName);
if (sender != null) { if (sender != null) {
commonService.send(sender, MessageKey.PASSWORD_CHANGED_SUCCESS); commonService.send(sender, MessageKey.PASSWORD_CHANGED_SUCCESS);
ConsoleLogger.info(sender.getName() + " changed password of " + lowerCaseName); logger.info(sender.getName() + " changed password of " + lowerCaseName);
} else { } else {
ConsoleLogger.info("Changed password of " + lowerCaseName); logger.info("Changed password of " + lowerCaseName);
} }
} else { } else {
if (sender != null) { if (sender != null) {
commonService.send(sender, MessageKey.ERROR); commonService.send(sender, MessageKey.ERROR);
} }
ConsoleLogger.warning("An error occurred while changing password for user " + lowerCaseName + "!"); logger.warning("An error occurred while changing password for user " + lowerCaseName + "!");
} }
} }
} }

View File

@ -5,6 +5,7 @@ import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.EmailChangedEvent; import fr.xephi.authme.events.EmailChangedEvent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.process.AsynchronousProcess; import fr.xephi.authme.process.AsynchronousProcess;
import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.BukkitService;
@ -22,6 +23,8 @@ import javax.inject.Inject;
*/ */
public class AsyncAddEmail implements AsynchronousProcess { public class AsyncAddEmail implements AsynchronousProcess {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(AsyncAddEmail.class);
@Inject @Inject
private CommonService service; private CommonService service;
@ -65,7 +68,7 @@ public class AsyncAddEmail implements AsynchronousProcess {
EmailChangedEvent event = bukkitService.createAndCallEvent(isAsync EmailChangedEvent event = bukkitService.createAndCallEvent(isAsync
-> new EmailChangedEvent(player, null, email, isAsync)); -> new EmailChangedEvent(player, null, email, isAsync));
if (event.isCancelled()) { if (event.isCancelled()) {
ConsoleLogger.info("Could not add email to player '" + player + "' event was cancelled"); logger.info("Could not add email to player '" + player + "' event was cancelled");
service.send(player, MessageKey.EMAIL_ADD_NOT_ALLOWED); service.send(player, MessageKey.EMAIL_ADD_NOT_ALLOWED);
return; return;
} }
@ -75,7 +78,7 @@ public class AsyncAddEmail implements AsynchronousProcess {
bungeeSender.sendAuthMeBungeecordMessage(MessageType.REFRESH_EMAIL, playerName); bungeeSender.sendAuthMeBungeecordMessage(MessageType.REFRESH_EMAIL, playerName);
service.send(player, MessageKey.EMAIL_ADDED_SUCCESS); service.send(player, MessageKey.EMAIL_ADDED_SUCCESS);
} else { } else {
ConsoleLogger.warning("Could not save email for player '" + player + "'"); logger.warning("Could not save email for player '" + player + "'");
service.send(player, MessageKey.ERROR); service.send(player, MessageKey.ERROR);
} }
} }

View File

@ -5,6 +5,7 @@ import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.EmailChangedEvent; import fr.xephi.authme.events.EmailChangedEvent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.process.AsynchronousProcess; import fr.xephi.authme.process.AsynchronousProcess;
import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.BukkitService;
@ -20,6 +21,8 @@ import javax.inject.Inject;
* Async task for changing the email. * Async task for changing the email.
*/ */
public class AsyncChangeEmail implements AsynchronousProcess { public class AsyncChangeEmail implements AsynchronousProcess {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(AsyncChangeEmail.class);
@Inject @Inject
private CommonService service; private CommonService service;
@ -83,7 +86,7 @@ public class AsyncChangeEmail implements AsynchronousProcess {
EmailChangedEvent event = bukkitService.createAndCallEvent(isAsync EmailChangedEvent event = bukkitService.createAndCallEvent(isAsync
-> new EmailChangedEvent(player, oldEmail, newEmail, isAsync)); -> new EmailChangedEvent(player, oldEmail, newEmail, isAsync));
if (event.isCancelled()) { if (event.isCancelled()) {
ConsoleLogger.info("Could not change email for player '" + player + "' event was cancelled"); logger.info("Could not change email for player '" + player + "' event was cancelled");
service.send(player, MessageKey.EMAIL_CHANGE_NOT_ALLOWED); service.send(player, MessageKey.EMAIL_CHANGE_NOT_ALLOWED);
return; return;
} }

View File

@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.limbo.LimboService; import fr.xephi.authme.data.limbo.LimboService;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.ProtectInventoryEvent; import fr.xephi.authme.events.ProtectInventoryEvent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.permission.PlayerStatePermission; import fr.xephi.authme.permission.PlayerStatePermission;
import fr.xephi.authme.process.AsynchronousProcess; import fr.xephi.authme.process.AsynchronousProcess;
@ -35,6 +36,8 @@ import static fr.xephi.authme.settings.properties.RestrictionSettings.PROTECT_IN
* Asynchronous process for when a player joins. * Asynchronous process for when a player joins.
*/ */
public class AsynchronousJoin implements AsynchronousProcess { public class AsynchronousJoin implements AsynchronousProcess {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(AsynchronousJoin.class);
@Inject @Inject
private Server server; private Server server;
@ -112,7 +115,7 @@ public class AsynchronousJoin implements AsynchronousProcess {
isAsync -> new ProtectInventoryEvent(player, isAsync)); isAsync -> new ProtectInventoryEvent(player, isAsync));
if (ev.isCancelled()) { if (ev.isCancelled()) {
player.updateInventory(); player.updateInventory();
ConsoleLogger.fine("ProtectInventoryEvent has been cancelled for " + player.getName() + "..."); logger.fine("ProtectInventoryEvent has been cancelled for " + player.getName() + "...");
} }
} }

View File

@ -12,6 +12,7 @@ import fr.xephi.authme.data.limbo.LimboService;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.AuthMeAsyncPreLoginEvent; import fr.xephi.authme.events.AuthMeAsyncPreLoginEvent;
import fr.xephi.authme.events.FailedLoginEvent; import fr.xephi.authme.events.FailedLoginEvent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.mail.EmailService; import fr.xephi.authme.mail.EmailService;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.permission.AdminPermission; import fr.xephi.authme.permission.AdminPermission;
@ -44,6 +45,8 @@ import java.util.List;
* Asynchronous task for a player login. * Asynchronous task for a player login.
*/ */
public class AsynchronousLogin implements AsynchronousProcess { public class AsynchronousLogin implements AsynchronousProcess {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(AsynchronousLogin.class);
@Inject @Inject
private DataSource dataSource; private DataSource dataSource;
@ -199,7 +202,7 @@ public class AsynchronousLogin implements AsynchronousProcess {
* @param ip the ip address of the player * @param ip the ip address of the player
*/ */
private void handleWrongPassword(Player player, PlayerAuth auth, String ip) { private void handleWrongPassword(Player player, PlayerAuth auth, String ip) {
ConsoleLogger.fine(player.getName() + " used the wrong password"); logger.fine(player.getName() + " used the wrong password");
bukkitService.createAndCallEvent(isAsync -> new FailedLoginEvent(player, isAsync)); bukkitService.createAndCallEvent(isAsync -> new FailedLoginEvent(player, isAsync));
if (tempbanManager.shouldTempban(ip)) { if (tempbanManager.shouldTempban(ip)) {
@ -256,7 +259,7 @@ public class AsynchronousLogin implements AsynchronousProcess {
service.send(player, MessageKey.ADD_EMAIL_MESSAGE); service.send(player, MessageKey.ADD_EMAIL_MESSAGE);
} }
ConsoleLogger.fine(player.getName() + " logged in!"); logger.fine(player.getName() + " logged in!");
// makes player loggedin // makes player loggedin
playerCache.updatePlayer(auth); playerCache.updatePlayer(auth);
@ -270,7 +273,7 @@ public class AsynchronousLogin implements AsynchronousProcess {
// processed in other order. // processed in other order.
syncProcessManager.processSyncPlayerLogin(player, isFirstLogin, auths); syncProcessManager.processSyncPlayerLogin(player, isFirstLogin, auths);
} else { } else {
ConsoleLogger.warning("Player '" + player.getName() + "' wasn't online during login process, aborted..."); logger.warning("Player '" + player.getName() + "' wasn't online during login process, aborted...");
} }
} }
@ -297,8 +300,8 @@ public class AsynchronousLogin implements AsynchronousProcess {
String message = ChatColor.GRAY + String.join(", ", formattedNames) + "."; String message = ChatColor.GRAY + String.join(", ", formattedNames) + ".";
ConsoleLogger.fine("The user " + player.getName() + " has " + auths.size() + " accounts:"); logger.fine("The user " + player.getName() + " has " + auths.size() + " accounts:");
ConsoleLogger.fine(message); logger.fine(message);
for (Player onlinePlayer : bukkitService.getOnlinePlayers()) { for (Player onlinePlayer : bukkitService.getOnlinePlayers()) {
if (onlinePlayer.getName().equalsIgnoreCase(player.getName()) if (onlinePlayer.getName().equalsIgnoreCase(player.getName())

View File

@ -3,6 +3,7 @@ package fr.xephi.authme.process.logout;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.limbo.LimboService; import fr.xephi.authme.data.limbo.LimboService;
import fr.xephi.authme.events.LogoutEvent; import fr.xephi.authme.events.LogoutEvent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.listener.protocollib.ProtocolLibService; import fr.xephi.authme.listener.protocollib.ProtocolLibService;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.process.SynchronousProcess; import fr.xephi.authme.process.SynchronousProcess;
@ -23,6 +24,8 @@ import static fr.xephi.authme.service.BukkitService.TICKS_PER_SECOND;
public class ProcessSyncPlayerLogout implements SynchronousProcess { public class ProcessSyncPlayerLogout implements SynchronousProcess {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(ProcessSyncPlayerLogout.class);
@Inject @Inject
private CommonService service; private CommonService service;
@ -64,7 +67,7 @@ public class ProcessSyncPlayerLogout implements SynchronousProcess {
bukkitService.callEvent(new LogoutEvent(player)); bukkitService.callEvent(new LogoutEvent(player));
service.send(player, MessageKey.LOGOUT_SUCCESS); service.send(player, MessageKey.LOGOUT_SUCCESS);
ConsoleLogger.info(player.getName() + " logged out"); logger.info(player.getName() + " logged out");
} }
private void applyLogoutEffect(Player player) { private void applyLogoutEffect(Player player) {

View File

@ -3,6 +3,7 @@ package fr.xephi.authme.process.register;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.limbo.LimboService; import fr.xephi.authme.data.limbo.LimboService;
import fr.xephi.authme.events.RegisterEvent; import fr.xephi.authme.events.RegisterEvent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.process.SynchronousProcess; import fr.xephi.authme.process.SynchronousProcess;
import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.BukkitService;
@ -16,6 +17,8 @@ import javax.inject.Inject;
* Performs synchronous tasks after a successful {@link RegistrationType#EMAIL email registration}. * Performs synchronous tasks after a successful {@link RegistrationType#EMAIL email registration}.
*/ */
public class ProcessSyncEmailRegister implements SynchronousProcess { public class ProcessSyncEmailRegister implements SynchronousProcess {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(ProcessSyncEmailRegister.class);
@Inject @Inject
private BukkitService bukkitService; private BukkitService bukkitService;
@ -40,7 +43,7 @@ public class ProcessSyncEmailRegister implements SynchronousProcess {
player.saveData(); player.saveData();
bukkitService.callEvent(new RegisterEvent(player)); bukkitService.callEvent(new RegisterEvent(player));
ConsoleLogger.fine(player.getName() + " registered " + PlayerUtils.getPlayerIp(player)); logger.fine(player.getName() + " registered " + PlayerUtils.getPlayerIp(player));
} }
} }

View File

@ -3,6 +3,7 @@ package fr.xephi.authme.process.register;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.limbo.LimboService; import fr.xephi.authme.data.limbo.LimboService;
import fr.xephi.authme.events.RegisterEvent; import fr.xephi.authme.events.RegisterEvent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.process.SynchronousProcess; import fr.xephi.authme.process.SynchronousProcess;
import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.BukkitService;
@ -21,6 +22,8 @@ import javax.inject.Inject;
*/ */
public class ProcessSyncPasswordRegister implements SynchronousProcess { public class ProcessSyncPasswordRegister implements SynchronousProcess {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(ProcessSyncPasswordRegister.class);
@Inject @Inject
private BungeeSender bungeeSender; private BungeeSender bungeeSender;
@ -66,7 +69,7 @@ public class ProcessSyncPasswordRegister implements SynchronousProcess {
player.saveData(); player.saveData();
bukkitService.callEvent(new RegisterEvent(player)); bukkitService.callEvent(new RegisterEvent(player));
ConsoleLogger.fine(player.getName() + " registered " + PlayerUtils.getPlayerIp(player)); logger.fine(player.getName() + " registered " + PlayerUtils.getPlayerIp(player));
// Kick Player after Registration is enabled, kick the player // Kick Player after Registration is enabled, kick the player
if (service.getProperty(RegistrationSettings.FORCE_KICK_AFTER_REGISTER)) { if (service.getProperty(RegistrationSettings.FORCE_KICK_AFTER_REGISTER)) {

View File

@ -29,6 +29,7 @@ final class PlayerAuthBuilderHelper {
.email(email) .email(email)
.registrationIp(PlayerUtils.getPlayerIp(player)) .registrationIp(PlayerUtils.getPlayerIp(player))
.registrationDate(System.currentTimeMillis()) .registrationDate(System.currentTimeMillis())
.uuid(player.getUniqueId())
.build(); .build();
} }
} }

View File

@ -7,6 +7,7 @@ import fr.xephi.authme.data.limbo.LimboService;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.UnregisterByAdminEvent; import fr.xephi.authme.events.UnregisterByAdminEvent;
import fr.xephi.authme.events.UnregisterByPlayerEvent; import fr.xephi.authme.events.UnregisterByPlayerEvent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.process.AsynchronousProcess; import fr.xephi.authme.process.AsynchronousProcess;
import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.security.PasswordSecurity;
@ -28,6 +29,8 @@ import javax.inject.Inject;
import static fr.xephi.authme.service.BukkitService.TICKS_PER_SECOND; import static fr.xephi.authme.service.BukkitService.TICKS_PER_SECOND;
public class AsynchronousUnregister implements AsynchronousProcess { public class AsynchronousUnregister implements AsynchronousProcess {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(AsynchronousUnregister.class);
@Inject @Inject
private DataSource dataSource; private DataSource dataSource;
@ -72,7 +75,7 @@ public class AsynchronousUnregister implements AsynchronousProcess {
if (passwordSecurity.comparePassword(password, cachedAuth.getPassword(), name)) { if (passwordSecurity.comparePassword(password, cachedAuth.getPassword(), name)) {
if (dataSource.removeAuth(name)) { if (dataSource.removeAuth(name)) {
performPostUnregisterActions(name, player); performPostUnregisterActions(name, player);
ConsoleLogger.info(name + " unregistered himself"); logger.info(name + " unregistered himself");
bukkitService.createAndCallEvent(isAsync -> new UnregisterByPlayerEvent(player, isAsync)); bukkitService.createAndCallEvent(isAsync -> new UnregisterByPlayerEvent(player, isAsync));
} else { } else {
service.send(player, MessageKey.ERROR); service.send(player, MessageKey.ERROR);
@ -97,9 +100,9 @@ public class AsynchronousUnregister implements AsynchronousProcess {
bukkitService.createAndCallEvent(isAsync -> new UnregisterByAdminEvent(player, name, isAsync, initiator)); bukkitService.createAndCallEvent(isAsync -> new UnregisterByAdminEvent(player, name, isAsync, initiator));
if (initiator == null) { if (initiator == null) {
ConsoleLogger.info(name + " was unregistered"); logger.info(name + " was unregistered");
} else { } else {
ConsoleLogger.info(name + " was unregistered by " + initiator.getName()); logger.info(name + " was unregistered by " + initiator.getName());
service.send(initiator, MessageKey.UNREGISTERED_SUCCESS); service.send(initiator, MessageKey.UNREGISTERED_SUCCESS);
} }
} else if (initiator != null) { } else if (initiator != null) {

View File

@ -3,6 +3,7 @@ package fr.xephi.authme.security.crypts;
import de.mkammerer.argon2.Argon2Constants; import de.mkammerer.argon2.Argon2Constants;
import de.mkammerer.argon2.Argon2Factory; import de.mkammerer.argon2.Argon2Factory;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.security.crypts.description.HasSalt; import fr.xephi.authme.security.crypts.description.HasSalt;
import fr.xephi.authme.security.crypts.description.Recommendation; import fr.xephi.authme.security.crypts.description.Recommendation;
import fr.xephi.authme.security.crypts.description.SaltType; import fr.xephi.authme.security.crypts.description.SaltType;
@ -14,6 +15,8 @@ import fr.xephi.authme.security.crypts.description.Usage;
// and isn't exposed to the outside, so we treat it as an unsalted implementation // and isn't exposed to the outside, so we treat it as an unsalted implementation
public class Argon2 extends UnsaltedMethod { public class Argon2 extends UnsaltedMethod {
private static ConsoleLogger logger = ConsoleLoggerFactory.get(Argon2.class);
private de.mkammerer.argon2.Argon2 argon2; private de.mkammerer.argon2.Argon2 argon2;
public Argon2() { public Argon2() {
@ -30,7 +33,7 @@ public class Argon2 extends UnsaltedMethod {
System.loadLibrary("argon2"); System.loadLibrary("argon2");
return true; return true;
} catch (UnsatisfiedLinkError e) { } catch (UnsatisfiedLinkError e) {
ConsoleLogger.logException( logger.logException(
"Cannot find argon2 library: https://github.com/AuthMe/AuthMeReloaded/wiki/Argon2-as-Password-Hash", e); "Cannot find argon2 library: https://github.com/AuthMe/AuthMeReloaded/wiki/Argon2-as-Password-Hash", e);
} }
return false; return false;

View File

@ -5,6 +5,7 @@ import de.rtner.misc.BinTools;
import de.rtner.security.auth.spi.PBKDF2Engine; import de.rtner.security.auth.spi.PBKDF2Engine;
import de.rtner.security.auth.spi.PBKDF2Parameters; import de.rtner.security.auth.spi.PBKDF2Parameters;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.security.crypts.description.Recommendation; import fr.xephi.authme.security.crypts.description.Recommendation;
import fr.xephi.authme.security.crypts.description.Usage; import fr.xephi.authme.security.crypts.description.Usage;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
@ -16,6 +17,7 @@ import javax.inject.Inject;
public class Pbkdf2 extends HexSaltedMethod { public class Pbkdf2 extends HexSaltedMethod {
private static final int DEFAULT_ROUNDS = 10_000; private static final int DEFAULT_ROUNDS = 10_000;
private final ConsoleLogger logger = ConsoleLoggerFactory.get(Pbkdf2.class);
private int numberOfRounds; private int numberOfRounds;
@Inject @Inject
@ -41,7 +43,7 @@ public class Pbkdf2 extends HexSaltedMethod {
} }
Integer iterations = Ints.tryParse(line[1]); Integer iterations = Ints.tryParse(line[1]);
if (iterations == null) { if (iterations == null) {
ConsoleLogger.warning("Cannot read number of rounds for Pbkdf2: '" + line[1] + "'"); logger.warning("Cannot read number of rounds for Pbkdf2: '" + line[1] + "'");
return false; return false;
} }

View File

@ -4,6 +4,7 @@ import com.google.common.primitives.Ints;
import de.rtner.security.auth.spi.PBKDF2Engine; import de.rtner.security.auth.spi.PBKDF2Engine;
import de.rtner.security.auth.spi.PBKDF2Parameters; import de.rtner.security.auth.spi.PBKDF2Parameters;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.security.crypts.description.AsciiRestricted; import fr.xephi.authme.security.crypts.description.AsciiRestricted;
import java.util.Base64; import java.util.Base64;
@ -12,6 +13,7 @@ import java.util.Base64;
public class Pbkdf2Django extends HexSaltedMethod { public class Pbkdf2Django extends HexSaltedMethod {
private static final int DEFAULT_ITERATIONS = 24000; private static final int DEFAULT_ITERATIONS = 24000;
private final ConsoleLogger logger = ConsoleLoggerFactory.get(Pbkdf2Django.class);
@Override @Override
public String computeHash(String password, String salt, String name) { public String computeHash(String password, String salt, String name) {
@ -30,7 +32,7 @@ public class Pbkdf2Django extends HexSaltedMethod {
} }
Integer iterations = Ints.tryParse(line[1]); Integer iterations = Ints.tryParse(line[1]);
if (iterations == null) { if (iterations == null) {
ConsoleLogger.warning("Cannot read number of rounds for Pbkdf2Django: '" + line[1] + "'"); logger.warning("Cannot read number of rounds for Pbkdf2Django: '" + line[1] + "'");
return false; return false;
} }

View File

@ -5,6 +5,7 @@ import com.google.common.io.BaseEncoding;
import com.google.common.net.UrlEscapers; import com.google.common.net.UrlEscapers;
import com.google.common.primitives.Ints; import com.google.common.primitives.Ints;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.security.crypts.description.HasSalt; import fr.xephi.authme.security.crypts.description.HasSalt;
import fr.xephi.authme.security.crypts.description.Recommendation; import fr.xephi.authme.security.crypts.description.Recommendation;
import fr.xephi.authme.security.crypts.description.SaltType; import fr.xephi.authme.security.crypts.description.SaltType;
@ -34,6 +35,8 @@ public class TwoFactor extends UnsaltedMethod {
private static final int TIME_PRECISION = 3; private static final int TIME_PRECISION = 3;
private static final String CRYPTO_ALGO = "HmacSHA1"; private static final String CRYPTO_ALGO = "HmacSHA1";
private final ConsoleLogger logger = ConsoleLoggerFactory.get(TwoFactor.class);
/** /**
* Creates a link to a QR barcode with the provided secret. * Creates a link to a QR barcode with the provided secret.
@ -71,7 +74,7 @@ public class TwoFactor extends UnsaltedMethod {
try { try {
return checkPassword(hashedPassword.getHash(), password); return checkPassword(hashedPassword.getHash(), password);
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.logException("Failed to verify two auth code:", e); logger.logException("Failed to verify two auth code:", e);
return false; return false;
} }
} }

View File

@ -3,6 +3,7 @@ package fr.xephi.authme.security.crypts;
import at.favre.lib.crypto.bcrypt.BCrypt; import at.favre.lib.crypto.bcrypt.BCrypt;
import at.favre.lib.crypto.bcrypt.IllegalBCryptFormatException; import at.favre.lib.crypto.bcrypt.IllegalBCryptFormatException;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.security.crypts.description.HasSalt; import fr.xephi.authme.security.crypts.description.HasSalt;
import fr.xephi.authme.security.crypts.description.Recommendation; import fr.xephi.authme.security.crypts.description.Recommendation;
import fr.xephi.authme.security.crypts.description.SaltType; import fr.xephi.authme.security.crypts.description.SaltType;
@ -19,6 +20,7 @@ import static java.nio.charset.StandardCharsets.UTF_8;
@HasSalt(value = SaltType.TEXT, length = SALT_LENGTH_ENCODED) @HasSalt(value = SaltType.TEXT, length = SALT_LENGTH_ENCODED)
public class Wbb4 implements EncryptionMethod { public class Wbb4 implements EncryptionMethod {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(Wbb4.class);
private BCryptHasher bCryptHasher = new BCryptHasher(BCrypt.Version.VERSION_2A, 8); private BCryptHasher bCryptHasher = new BCryptHasher(BCrypt.Version.VERSION_2A, 8);
private SecureRandom random = new SecureRandom(); private SecureRandom random = new SecureRandom();
@ -44,7 +46,7 @@ public class Wbb4 implements EncryptionMethod {
String computedHash = hashInternal(password, salt); String computedHash = hashInternal(password, salt);
return isEqual(hashedPassword.getHash(), computedHash); return isEqual(hashedPassword.getHash(), computedHash);
} catch (IllegalBCryptFormatException | IllegalArgumentException e) { } catch (IllegalBCryptFormatException | IllegalArgumentException e) {
ConsoleLogger.logException("Invalid WBB4 hash:", e); logger.logException("Invalid WBB4 hash:", e);
} }
return false; return false;
} }

View File

@ -3,6 +3,8 @@ package fr.xephi.authme.service;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.datasource.DataSourceType; import fr.xephi.authme.datasource.DataSourceType;
import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.initialization.DataFolder;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.mail.EmailService;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.BackupSettings; import fr.xephi.authme.settings.properties.BackupSettings;
import fr.xephi.authme.settings.properties.DatabaseSettings; import fr.xephi.authme.settings.properties.DatabaseSettings;
@ -25,10 +27,13 @@ import static fr.xephi.authme.util.Utils.logAndSendWarning;
*/ */
public class BackupService { public class BackupService {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(EmailService.class);
private final File dataFolder; private final File dataFolder;
private final File backupFolder; private final File backupFolder;
private final Settings settings; private final Settings settings;
/** /**
* Constructor. * Constructor.
* *
@ -89,7 +94,7 @@ public class BackupService {
String dbName = settings.getProperty(DatabaseSettings.MYSQL_DATABASE); String dbName = settings.getProperty(DatabaseSettings.MYSQL_DATABASE);
return performFileBackup(dbName + ".db"); return performFileBackup(dbName + ".db");
default: default:
ConsoleLogger.warning("Unknown data source type '" + dataSourceType + "' for backup"); logger.warning("Unknown data source type '" + dataSourceType + "' for backup");
} }
return false; return false;
@ -114,13 +119,13 @@ public class BackupService {
Process runtimeProcess = Runtime.getRuntime().exec(backupCommand); Process runtimeProcess = Runtime.getRuntime().exec(backupCommand);
int processComplete = runtimeProcess.waitFor(); int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) { if (processComplete == 0) {
ConsoleLogger.info("Backup created successfully. (Using Windows = " + isUsingWindows + ")"); logger.info("Backup created successfully. (Using Windows = " + isUsingWindows + ")");
return true; return true;
} else { } else {
ConsoleLogger.warning("Could not create the backup! (Using Windows = " + isUsingWindows + ")"); logger.warning("Could not create the backup! (Using Windows = " + isUsingWindows + ")");
} }
} catch (IOException | InterruptedException e) { } catch (IOException | InterruptedException e) {
ConsoleLogger.logException("Error during backup (using Windows = " + isUsingWindows + "):", e); logger.logException("Error during backup (using Windows = " + isUsingWindows + "):", e);
} }
return false; return false;
} }
@ -133,7 +138,7 @@ public class BackupService {
copy(new File(dataFolder, filename), backupFile); copy(new File(dataFolder, filename), backupFile);
return true; return true;
} catch (IOException ex) { } catch (IOException ex) {
ConsoleLogger.logException("Encountered an error during file backup:", ex); logger.logException("Encountered an error during file backup:", ex);
} }
return false; return false;
} }
@ -145,13 +150,13 @@ public class BackupService {
* @param windowsPath The path to check * @param windowsPath The path to check
* @return True if the path is correct, false if it is incorrect or the OS is not Windows * @return True if the path is correct, false if it is incorrect or the OS is not Windows
*/ */
private static boolean useWindowsCommand(String windowsPath) { private boolean useWindowsCommand(String windowsPath) {
String isWin = System.getProperty("os.name").toLowerCase(); String isWin = System.getProperty("os.name").toLowerCase();
if (isWin.contains("win")) { if (isWin.contains("win")) {
if (new File(windowsPath + "\\bin\\mysqldump.exe").exists()) { if (new File(windowsPath + "\\bin\\mysqldump.exe").exists()) {
return true; return true;
} else { } else {
ConsoleLogger.warning("Mysql Windows Path is incorrect. Please check it"); logger.warning("Mysql Windows Path is incorrect. Please check it");
return false; return false;
} }
} }

View File

@ -15,6 +15,7 @@ import com.maxmind.db.model.Country;
import com.maxmind.db.model.CountryResponse; import com.maxmind.db.model.CountryResponse;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.initialization.DataFolder;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.util.FileUtils; import fr.xephi.authme.util.FileUtils;
import fr.xephi.authme.util.InternetProtocolUtils; import fr.xephi.authme.util.InternetProtocolUtils;
@ -61,6 +62,7 @@ public class GeoIpService {
// but every HTTP implementation have to support RFC 1023 // but every HTTP implementation have to support RFC 1023
private static final String TIME_RFC_1023 = "EEE, dd-MMM-yy HH:mm:ss zzz"; private static final String TIME_RFC_1023 = "EEE, dd-MMM-yy HH:mm:ss zzz";
private final ConsoleLogger logger = ConsoleLoggerFactory.get(GeoIpService.class);
private final Path dataFile; private final Path dataFile;
private final BukkitService bukkitService; private final BukkitService bukkitService;
@ -109,10 +111,10 @@ public class GeoIpService {
// don't fire the update task - we are up to date // don't fire the update task - we are up to date
return true; return true;
} else { } else {
ConsoleLogger.debug("GEO IP database is older than " + UPDATE_INTERVAL_DAYS + " Days"); logger.debug("GEO IP database is older than " + UPDATE_INTERVAL_DAYS + " Days");
} }
} catch (IOException ioEx) { } catch (IOException ioEx) {
ConsoleLogger.logException("Failed to load GeoLiteAPI database", ioEx); logger.logException("Failed to load GeoLiteAPI database", ioEx);
return false; return false;
} }
} }
@ -130,7 +132,7 @@ public class GeoIpService {
* Tries to update the database by downloading a new version from the website. * Tries to update the database by downloading a new version from the website.
*/ */
private void updateDatabase() { private void updateDatabase() {
ConsoleLogger.info("Downloading GEO IP database, because the old database is older than " logger.info("Downloading GEO IP database, because the old database is older than "
+ UPDATE_INTERVAL_DAYS + " days or doesn't exist"); + UPDATE_INTERVAL_DAYS + " days or doesn't exist");
Path tempFile = null; Path tempFile = null;
@ -138,7 +140,7 @@ public class GeoIpService {
// download database to temporarily location // download database to temporarily location
tempFile = Files.createTempFile(ARCHIVE_FILE, null); tempFile = Files.createTempFile(ARCHIVE_FILE, null);
if (!downloadDatabaseArchive(tempFile)) { if (!downloadDatabaseArchive(tempFile)) {
ConsoleLogger.info("There is no newer GEO IP database uploaded to MaxMind. Using the old one for now."); logger.info("There is no newer GEO IP database uploaded to MaxMind. Using the old one for now.");
startReading(); startReading();
return; return;
} }
@ -151,10 +153,10 @@ public class GeoIpService {
extractDatabase(tempFile, dataFile); extractDatabase(tempFile, dataFile);
//only set this value to false on success otherwise errors could lead to endless download triggers //only set this value to false on success otherwise errors could lead to endless download triggers
ConsoleLogger.info("Successfully downloaded new GEO IP database to " + dataFile); logger.info("Successfully downloaded new GEO IP database to " + dataFile);
startReading(); startReading();
} catch (IOException ioEx) { } catch (IOException ioEx) {
ConsoleLogger.logException("Could not download GeoLiteAPI database", ioEx); logger.logException("Could not download GeoLiteAPI database", ioEx);
} finally { } finally {
// clean up // clean up
if (tempFile != null) { if (tempFile != null) {
@ -165,7 +167,7 @@ public class GeoIpService {
private void startReading() throws IOException { private void startReading() throws IOException {
databaseReader = new Reader(dataFile.toFile(), FileMode.MEMORY, new CHMCache()); databaseReader = new Reader(dataFile.toFile(), FileMode.MEMORY, new CHMCache());
ConsoleLogger.info(LICENSE); logger.info(LICENSE);
// clear downloading flag, because we now have working reader instance // clear downloading flag, because we now have working reader instance
downloading = false; downloading = false;
@ -315,7 +317,7 @@ public class GeoIpService {
// Ignore invalid ip addresses // Ignore invalid ip addresses
// Legacy GEO IP Database returned a unknown country object with Country-Code: '--' and Country-Name: 'N/A' // Legacy GEO IP Database returned a unknown country object with Country-Code: '--' and Country-Name: 'N/A'
} catch (IOException ioEx) { } catch (IOException ioEx) {
ConsoleLogger.logException("Cannot lookup country for " + ip + " at GEO IP database", ioEx); logger.logException("Cannot lookup country for " + ip + " at GEO IP database", ioEx);
} }
return Optional.empty(); return Optional.empty();

View File

@ -3,6 +3,7 @@ package fr.xephi.authme.service;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.security.HashAlgorithm; import fr.xephi.authme.security.HashAlgorithm;
import fr.xephi.authme.security.crypts.HashedPassword; import fr.xephi.authme.security.crypts.HashedPassword;
import fr.xephi.authme.security.crypts.Sha256; import fr.xephi.authme.security.crypts.Sha256;
@ -15,6 +16,8 @@ import java.util.List;
* Migrations to perform during the initialization of AuthMe. * Migrations to perform during the initialization of AuthMe.
*/ */
public final class MigrationService { public final class MigrationService {
private static ConsoleLogger logger = ConsoleLoggerFactory.get(MigrationService.class);
private MigrationService() { private MigrationService() {
} }
@ -29,14 +32,14 @@ public final class MigrationService {
public static void changePlainTextToSha256(Settings settings, DataSource dataSource, public static void changePlainTextToSha256(Settings settings, DataSource dataSource,
Sha256 authmeSha256) { Sha256 authmeSha256) {
if (HashAlgorithm.PLAINTEXT == settings.getProperty(SecuritySettings.PASSWORD_HASH)) { if (HashAlgorithm.PLAINTEXT == settings.getProperty(SecuritySettings.PASSWORD_HASH)) {
ConsoleLogger.warning("Your HashAlgorithm has been detected as plaintext and is now deprecated;" logger.warning("Your HashAlgorithm has been detected as plaintext and is now deprecated;"
+ " it will be changed and hashed now to the AuthMe default hashing method"); + " it will be changed and hashed now to the AuthMe default hashing method");
ConsoleLogger.warning("Don't stop your server; wait for the conversion to have been completed!"); logger.warning("Don't stop your server; wait for the conversion to have been completed!");
List<PlayerAuth> allAuths = dataSource.getAllAuths(); List<PlayerAuth> allAuths = dataSource.getAllAuths();
for (PlayerAuth auth : allAuths) { for (PlayerAuth auth : allAuths) {
String hash = auth.getPassword().getHash(); String hash = auth.getPassword().getHash();
if (hash.startsWith("$SHA$")) { if (hash.startsWith("$SHA$")) {
ConsoleLogger.warning("Skipping conversion for " + auth.getNickname() + "; detected SHA hash"); logger.warning("Skipping conversion for " + auth.getNickname() + "; detected SHA hash");
} else { } else {
HashedPassword hashedPassword = authmeSha256.computeHash(hash, auth.getNickname()); HashedPassword hashedPassword = authmeSha256.computeHash(hash, auth.getNickname());
auth.setPassword(hashedPassword); auth.setPassword(hashedPassword);
@ -45,7 +48,7 @@ public final class MigrationService {
} }
settings.setProperty(SecuritySettings.PASSWORD_HASH, HashAlgorithm.SHA256); settings.setProperty(SecuritySettings.PASSWORD_HASH, HashAlgorithm.SHA256);
settings.save(); settings.save();
ConsoleLogger.info("Migrated " + allAuths.size() + " accounts from plaintext to SHA256"); logger.info("Migrated " + allAuths.size() + " accounts from plaintext to SHA256");
} }
} }
} }

View File

@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.initialization.HasCleanup; import fr.xephi.authme.initialization.HasCleanup;
import fr.xephi.authme.initialization.Reloadable; import fr.xephi.authme.initialization.Reloadable;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.mail.EmailService; import fr.xephi.authme.mail.EmailService;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.message.Messages; import fr.xephi.authme.message.Messages;
@ -27,6 +28,8 @@ import static fr.xephi.authme.settings.properties.EmailSettings.RECOVERY_PASSWOR
* Manager for password recovery. * Manager for password recovery.
*/ */
public class PasswordRecoveryService implements Reloadable, HasCleanup { public class PasswordRecoveryService implements Reloadable, HasCleanup {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(PasswordRecoveryService.class);
@Inject @Inject
private CommonService commonService; private CommonService commonService;
@ -95,7 +98,7 @@ public class PasswordRecoveryService implements Reloadable, HasCleanup {
String thePass = RandomStringUtils.generate(commonService.getProperty(RECOVERY_PASSWORD_LENGTH)); String thePass = RandomStringUtils.generate(commonService.getProperty(RECOVERY_PASSWORD_LENGTH));
HashedPassword hashNew = passwordSecurity.computeHash(thePass, name); HashedPassword hashNew = passwordSecurity.computeHash(thePass, name);
ConsoleLogger.info("Generating new password for '" + name + "'"); logger.info("Generating new password for '" + name + "'");
dataSource.updatePassword(name, hashNew); dataSource.updatePassword(name, hashNew);
boolean couldSendMail = emailService.sendPasswordMail(name, email, thePass); boolean couldSendMail = emailService.sendPasswordMail(name, email, thePass);

View File

@ -5,6 +5,7 @@ import com.earth2me.essentials.Essentials;
import com.onarandombox.MultiverseCore.MultiverseCore; import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.MVWorldManager; import com.onarandombox.MultiverseCore.api.MVWorldManager;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -20,6 +21,7 @@ import java.io.File;
@NoFieldScan @NoFieldScan
public class PluginHookService { public class PluginHookService {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(PluginHookService.class);
private final PluginManager pluginManager; private final PluginManager pluginManager;
private Essentials essentials; private Essentials essentials;
private Plugin cmi; private Plugin cmi;
@ -182,11 +184,11 @@ public class PluginHookService {
// Helpers // Helpers
// ------ // ------
private static <T extends Plugin> T getPlugin(PluginManager pluginManager, String name, Class<T> clazz) private <T extends Plugin> T getPlugin(PluginManager pluginManager, String name, Class<T> clazz)
throws Exception, NoClassDefFoundError { throws Exception, NoClassDefFoundError {
if (pluginManager.isPluginEnabled(name)) { if (pluginManager.isPluginEnabled(name)) {
T plugin = clazz.cast(pluginManager.getPlugin(name)); T plugin = clazz.cast(pluginManager.getPlugin(name));
ConsoleLogger.info("Hooked successfully into " + name); logger.info("Hooked successfully into " + name);
return plugin; return plugin;
} }
return null; return null;

View File

@ -5,6 +5,7 @@ import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.RestoreSessionEvent; import fr.xephi.authme.events.RestoreSessionEvent;
import fr.xephi.authme.initialization.Reloadable; import fr.xephi.authme.initialization.Reloadable;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.PluginSettings;
import fr.xephi.authme.util.PlayerUtils; import fr.xephi.authme.util.PlayerUtils;
@ -19,6 +20,7 @@ import static fr.xephi.authme.util.Utils.MILLIS_PER_MINUTE;
*/ */
public class SessionService implements Reloadable { public class SessionService implements Reloadable {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(SessionService.class);
private final CommonService service; private final CommonService service;
private final BukkitService bukkitService; private final BukkitService bukkitService;
private final DataSource database; private final DataSource database;
@ -68,7 +70,7 @@ public class SessionService implements Reloadable {
*/ */
private SessionState fetchSessionStatus(PlayerAuth auth, Player player) { private SessionState fetchSessionStatus(PlayerAuth auth, Player player) {
if (auth == null) { if (auth == null) {
ConsoleLogger.warning("No PlayerAuth in database for '" + player.getName() + "' during session check"); logger.warning("No PlayerAuth in database for '" + player.getName() + "' during session check");
return SessionState.NOT_VALID; return SessionState.NOT_VALID;
} else if (auth.getLastLogin() == null) { } else if (auth.getLastLogin() == null) {
return SessionState.NOT_VALID; return SessionState.NOT_VALID;

View File

@ -10,6 +10,7 @@ import fr.xephi.authme.events.AuthMeTeleportEvent;
import fr.xephi.authme.events.FirstSpawnTeleportEvent; import fr.xephi.authme.events.FirstSpawnTeleportEvent;
import fr.xephi.authme.events.SpawnTeleportEvent; import fr.xephi.authme.events.SpawnTeleportEvent;
import fr.xephi.authme.initialization.Reloadable; import fr.xephi.authme.initialization.Reloadable;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.SpawnLoader; import fr.xephi.authme.settings.SpawnLoader;
import fr.xephi.authme.settings.properties.RestrictionSettings; import fr.xephi.authme.settings.properties.RestrictionSettings;
@ -28,6 +29,8 @@ import static fr.xephi.authme.settings.properties.RestrictionSettings.TELEPORT_U
* Handles teleportation (placement of player to spawn). * Handles teleportation (placement of player to spawn).
*/ */
public class TeleportationService implements Reloadable { public class TeleportationService implements Reloadable {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(TeleportationService.class);
@Inject @Inject
private Settings settings; private Settings settings;
@ -64,7 +67,7 @@ public class TeleportationService implements Reloadable {
public void teleportOnJoin(final Player player) { public void teleportOnJoin(final Player player) {
if (!settings.getProperty(RestrictionSettings.NO_TELEPORT) if (!settings.getProperty(RestrictionSettings.NO_TELEPORT)
&& settings.getProperty(TELEPORT_UNAUTHED_TO_SPAWN)) { && settings.getProperty(TELEPORT_UNAUTHED_TO_SPAWN)) {
ConsoleLogger.debug("Teleport on join for player `{0}`", player.getName()); logger.debug("Teleport on join for player `{0}`", player.getName());
teleportToSpawn(player, playerCache.isAuthenticated(player.getName())); teleportToSpawn(player, playerCache.isAuthenticated(player.getName()));
} }
} }
@ -88,7 +91,7 @@ public class TeleportationService implements Reloadable {
return null; return null;
} }
ConsoleLogger.debug("Returning custom location for >1.9 join event for player `{0}`", player.getName()); logger.debug("Returning custom location for >1.9 join event for player `{0}`", player.getName());
return location; return location;
} }
return null; return null;
@ -110,7 +113,7 @@ public class TeleportationService implements Reloadable {
} }
if (!player.hasPlayedBefore() || !dataSource.isAuthAvailable(player.getName())) { if (!player.hasPlayedBefore() || !dataSource.isAuthAvailable(player.getName())) {
ConsoleLogger.debug("Attempting to teleport player `{0}` to first spawn", player.getName()); logger.debug("Attempting to teleport player `{0}` to first spawn", player.getName());
performTeleportation(player, new FirstSpawnTeleportEvent(player, firstSpawn)); performTeleportation(player, new FirstSpawnTeleportEvent(player, firstSpawn));
} }
} }
@ -134,15 +137,15 @@ public class TeleportationService implements Reloadable {
// The world in LimboPlayer is from where the player comes, before any teleportation by AuthMe // The world in LimboPlayer is from where the player comes, before any teleportation by AuthMe
if (mustForceSpawnAfterLogin(worldName)) { if (mustForceSpawnAfterLogin(worldName)) {
ConsoleLogger.debug("Teleporting `{0}` to spawn because of 'force-spawn after login'", player.getName()); logger.debug("Teleporting `{0}` to spawn because of 'force-spawn after login'", player.getName());
teleportToSpawn(player, true); teleportToSpawn(player, true);
} else if (settings.getProperty(TELEPORT_UNAUTHED_TO_SPAWN)) { } else if (settings.getProperty(TELEPORT_UNAUTHED_TO_SPAWN)) {
if (settings.getProperty(RestrictionSettings.SAVE_QUIT_LOCATION) && auth.getQuitLocY() != 0) { if (settings.getProperty(RestrictionSettings.SAVE_QUIT_LOCATION) && auth.getQuitLocY() != 0) {
Location location = buildLocationFromAuth(player, auth); Location location = buildLocationFromAuth(player, auth);
ConsoleLogger.debug("Teleporting `{0}` after login, based on the player auth", player.getName()); logger.debug("Teleporting `{0}` after login, based on the player auth", player.getName());
teleportBackFromSpawn(player, location); teleportBackFromSpawn(player, location);
} else if (limbo != null && limbo.getLocation() != null) { } else if (limbo != null && limbo.getLocation() != null) {
ConsoleLogger.debug("Teleporting `{0}` after login, based on the limbo player", player.getName()); logger.debug("Teleporting `{0}` after login, based on the limbo player", player.getName());
teleportBackFromSpawn(player, limbo.getLocation()); teleportBackFromSpawn(player, limbo.getLocation());
} }
} }

View File

@ -6,6 +6,7 @@ import com.google.common.collect.Multimap;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.initialization.Reloadable; import fr.xephi.authme.initialization.Reloadable;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.permission.PlayerStatePermission; import fr.xephi.authme.permission.PlayerStatePermission;
@ -33,6 +34,8 @@ import static fr.xephi.authme.util.StringUtils.isInsideString;
* Validation service. * Validation service.
*/ */
public class ValidationService implements Reloadable { public class ValidationService implements Reloadable {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(ValidationService.class);
@Inject @Inject
private Settings settings; private Settings settings;
@ -125,7 +128,7 @@ public class ValidationService implements Reloadable {
String countryCode = geoIpService.getCountryCode(hostAddress); String countryCode = geoIpService.getCountryCode(hostAddress);
boolean isCountryAllowed = validateWhitelistAndBlacklist(countryCode, boolean isCountryAllowed = validateWhitelistAndBlacklist(countryCode,
ProtectionSettings.COUNTRIES_WHITELIST, ProtectionSettings.COUNTRIES_BLACKLIST); ProtectionSettings.COUNTRIES_WHITELIST, ProtectionSettings.COUNTRIES_BLACKLIST);
ConsoleLogger.debug("Country code `{0}` for `{1}` is allowed: {2}", countryCode, hostAddress, isCountryAllowed); logger.debug("Country code `{0}` for `{1}` is allowed: {2}", countryCode, hostAddress, isCountryAllowed);
return isCountryAllowed; return isCountryAllowed;
} }
@ -211,7 +214,7 @@ public class ValidationService implements Reloadable {
String[] data = restriction.split(";"); String[] data = restriction.split(";");
restrictions.put(data[0].toLowerCase(), data[1]); restrictions.put(data[0].toLowerCase(), data[1]);
} else { } else {
ConsoleLogger.warning("Restricted user rule must have a ';' separating name from restriction," logger.warning("Restricted user rule must have a ';' separating name from restriction,"
+ " but found: '" + restriction + "'"); + " but found: '" + restriction + "'");
} }
} }

View File

@ -6,6 +6,7 @@ import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.initialization.SettingsDependent; import fr.xephi.authme.initialization.SettingsDependent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.process.Management; import fr.xephi.authme.process.Management;
import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
@ -18,6 +19,8 @@ import javax.inject.Inject;
import java.util.Optional; import java.util.Optional;
public class BungeeReceiver implements PluginMessageListener, SettingsDependent { public class BungeeReceiver implements PluginMessageListener, SettingsDependent {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(BungeeReceiver.class);
private final AuthMe plugin; private final AuthMe plugin;
private final BukkitService bukkitService; private final BukkitService bukkitService;
@ -59,7 +62,7 @@ public class BungeeReceiver implements PluginMessageListener, SettingsDependent
final String typeId = dataIn.readUTF(); final String typeId = dataIn.readUTF();
final Optional<MessageType> type = MessageType.fromId(typeId); final Optional<MessageType> type = MessageType.fromId(typeId);
if (!type.isPresent()) { if (!type.isPresent()) {
ConsoleLogger.debug("Received unsupported forwarded bungeecord message type! ({0})", typeId); logger.debug("Received unsupported forwarded bungeecord message type! ({0})", typeId);
return; return;
} }
@ -68,7 +71,8 @@ public class BungeeReceiver implements PluginMessageListener, SettingsDependent
try { try {
argument = dataIn.readUTF(); argument = dataIn.readUTF();
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
ConsoleLogger.warning("Received invalid forwarded plugin message of type " + type.get().name() + ": argument is missing!"); logger.warning("Received invalid forwarded plugin message of type " + type.get().name()
+ ": argument is missing!");
return; return;
} }
@ -92,7 +96,7 @@ public class BungeeReceiver implements PluginMessageListener, SettingsDependent
final String typeId = in.readUTF(); final String typeId = in.readUTF();
final Optional<MessageType> type = MessageType.fromId(typeId); final Optional<MessageType> type = MessageType.fromId(typeId);
if (!type.isPresent()) { if (!type.isPresent()) {
ConsoleLogger.debug("Received unsupported bungeecord message type! ({0})", typeId); logger.debug("Received unsupported bungeecord message type! ({0})", typeId);
return; return;
} }
@ -101,7 +105,7 @@ public class BungeeReceiver implements PluginMessageListener, SettingsDependent
try { try {
argument = in.readUTF(); argument = in.readUTF();
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
ConsoleLogger.warning("Received invalid plugin message of type " + type.get().name() logger.warning("Received invalid plugin message of type " + type.get().name()
+ ": argument is missing!"); + ": argument is missing!");
return; return;
} }
@ -136,7 +140,7 @@ public class BungeeReceiver implements PluginMessageListener, SettingsDependent
Player player = bukkitService.getPlayerExact(name); Player player = bukkitService.getPlayerExact(name);
if (player != null && player.isOnline()) { if (player != null && player.isOnline()) {
management.forceLogin(player); management.forceLogin(player);
ConsoleLogger.info("The user " + player.getName() + " has been automatically logged in, " logger.info("The user " + player.getName() + " has been automatically logged in, "
+ "as requested via plugin messaging."); + "as requested via plugin messaging.");
} }
} }

View File

@ -6,6 +6,7 @@ import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.initialization.SettingsDependent; import fr.xephi.authme.initialization.SettingsDependent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.HooksSettings; import fr.xephi.authme.settings.properties.HooksSettings;
@ -16,6 +17,7 @@ import javax.inject.Inject;
public class BungeeSender implements SettingsDependent { public class BungeeSender implements SettingsDependent {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(BungeeSender.class);
private final AuthMe plugin; private final AuthMe plugin;
private final BukkitService bukkitService; private final BukkitService bukkitService;
private final DataSource dataSource; private final DataSource dataSource;
@ -97,7 +99,7 @@ public class BungeeSender implements SettingsDependent {
public void sendAuthMeBungeecordMessage(final MessageType type, final String playerName) { public void sendAuthMeBungeecordMessage(final MessageType type, final String playerName) {
if (isEnabled) { if (isEnabled) {
if (!plugin.isEnabled()) { if (!plugin.isEnabled()) {
ConsoleLogger.debug("Tried to send a " + type + " bungeecord message but the plugin was disabled!"); logger.debug("Tried to send a " + type + " bungeecord message but the plugin was disabled!");
return; return;
} }
if (type.isRequiresCaching() && !dataSource.isCached()) { if (type.isRequiresCaching() && !dataSource.isCached()) {

View File

@ -6,6 +6,7 @@ import ch.jalu.configme.migration.MigrationService;
import ch.jalu.configme.resource.PropertyResource; import ch.jalu.configme.resource.PropertyResource;
import com.google.common.io.Files; import com.google.common.io.Files;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -18,6 +19,7 @@ import static fr.xephi.authme.util.FileUtils.copyFileFromResource;
*/ */
public class Settings extends SettingsManagerImpl { public class Settings extends SettingsManagerImpl {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(Settings.class);
private final File pluginFolder; private final File pluginFolder;
private String passwordEmailMessage; private String passwordEmailMessage;
private String verificationEmailMessage; private String verificationEmailMessage;
@ -89,10 +91,10 @@ public class Settings extends SettingsManagerImpl {
try { try {
return Files.asCharSource(file, StandardCharsets.UTF_8).read(); return Files.asCharSource(file, StandardCharsets.UTF_8).read();
} catch (IOException e) { } catch (IOException e) {
ConsoleLogger.logException("Failed to read file '" + filename + "':", e); logger.logException("Failed to read file '" + filename + "':", e);
} }
} else { } else {
ConsoleLogger.warning("Failed to copy file '" + filename + "' from JAR"); logger.warning("Failed to copy file '" + filename + "' from JAR");
} }
return ""; return "";
} }

View File

@ -6,6 +6,7 @@ import ch.jalu.configme.properties.Property;
import ch.jalu.configme.resource.PropertyReader; import ch.jalu.configme.resource.PropertyReader;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.initialization.DataFolder;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.output.LogLevel; import fr.xephi.authme.output.LogLevel;
import fr.xephi.authme.process.register.RegisterSecondaryArgument; import fr.xephi.authme.process.register.RegisterSecondaryArgument;
import fr.xephi.authme.process.register.RegistrationType; import fr.xephi.authme.process.register.RegistrationType;
@ -38,7 +39,8 @@ import static fr.xephi.authme.settings.properties.RestrictionSettings.FORCE_SPAW
* Service for verifying that the configuration is up-to-date. * Service for verifying that the configuration is up-to-date.
*/ */
public class SettingsMigrationService extends PlainMigrationService { public class SettingsMigrationService extends PlainMigrationService {
private static ConsoleLogger logger = ConsoleLoggerFactory.get(SettingsMigrationService.class);
private final File pluginFolder; private final File pluginFolder;
// Stores old "other accounts command" config if present. // Stores old "other accounts command" config if present.
@ -141,7 +143,7 @@ public class SettingsMigrationService extends PlainMigrationService {
try (FileWriter fw = new FileWriter(emailFile)) { try (FileWriter fw = new FileWriter(emailFile)) {
fw.write(mailText); fw.write(mailText);
} catch (IOException e) { } catch (IOException e) {
ConsoleLogger.logException("Could not create email.html configuration file:", e); logger.logException("Could not create email.html configuration file:", e);
} }
} }
return true; return true;
@ -160,7 +162,7 @@ public class SettingsMigrationService extends PlainMigrationService {
boolean hasMigrated = moveProperty(oldDelayJoinProperty, DELAY_JOIN_MESSAGE, reader, configData); boolean hasMigrated = moveProperty(oldDelayJoinProperty, DELAY_JOIN_MESSAGE, reader, configData);
if (hasMigrated) { if (hasMigrated) {
ConsoleLogger.info(String.format("Note that we now also have the settings %s and %s", logger.info(String.format("Note that we now also have the settings %s and %s",
REMOVE_JOIN_MESSAGE.getPath(), REMOVE_LEAVE_MESSAGE.getPath())); REMOVE_JOIN_MESSAGE.getPath(), REMOVE_LEAVE_MESSAGE.getPath()));
} }
return hasMigrated; return hasMigrated;
@ -213,7 +215,7 @@ public class SettingsMigrationService extends PlainMigrationService {
final String oldPath = "Security.console.noConsoleSpam"; final String oldPath = "Security.console.noConsoleSpam";
final Property<LogLevel> newProperty = PluginSettings.LOG_LEVEL; final Property<LogLevel> newProperty = PluginSettings.LOG_LEVEL;
if (!newProperty.isPresent(reader) && reader.contains(oldPath)) { if (!newProperty.isPresent(reader) && reader.contains(oldPath)) {
ConsoleLogger.info("Moving '" + oldPath + "' to '" + newProperty.getPath() + "'"); logger.info("Moving '" + oldPath + "' to '" + newProperty.getPath() + "'");
boolean oldValue = Optional.ofNullable(reader.getBoolean(oldPath)).orElse(false); boolean oldValue = Optional.ofNullable(reader.getBoolean(oldPath)).orElse(false);
LogLevel level = oldValue ? LogLevel.INFO : LogLevel.FINE; LogLevel level = oldValue ? LogLevel.INFO : LogLevel.FINE;
configData.setValue(newProperty, level); configData.setValue(newProperty, level);
@ -224,7 +226,7 @@ public class SettingsMigrationService extends PlainMigrationService {
private static boolean hasOldHelpHeaderProperty(PropertyReader reader) { private static boolean hasOldHelpHeaderProperty(PropertyReader reader) {
if (reader.contains("settings.helpHeader")) { if (reader.contains("settings.helpHeader")) {
ConsoleLogger.warning("Help header setting is now in messages/help_xx.yml, " logger.warning("Help header setting is now in messages/help_xx.yml, "
+ "please check the file to set it again"); + "please check the file to set it again");
return true; return true;
} }
@ -234,7 +236,7 @@ public class SettingsMigrationService extends PlainMigrationService {
private static boolean hasSupportOldPasswordProperty(PropertyReader reader) { private static boolean hasSupportOldPasswordProperty(PropertyReader reader) {
String path = "settings.security.supportOldPasswordHash"; String path = "settings.security.supportOldPasswordHash";
if (reader.contains(path)) { if (reader.contains(path)) {
ConsoleLogger.warning("Property '" + path + "' is no longer supported. " logger.warning("Property '" + path + "' is no longer supported. "
+ "Use '" + SecuritySettings.LEGACY_HASHES.getPath() + "' instead."); + "Use '" + SecuritySettings.LEGACY_HASHES.getPath() + "' instead.");
return true; return true;
} }
@ -265,7 +267,7 @@ public class SettingsMigrationService extends PlainMigrationService {
? RegisterSecondaryArgument.CONFIRMATION ? RegisterSecondaryArgument.CONFIRMATION
: RegisterSecondaryArgument.NONE; : RegisterSecondaryArgument.NONE;
ConsoleLogger.warning("Merging old registration settings into '" logger.warning("Merging old registration settings into '"
+ RegistrationSettings.REGISTRATION_TYPE.getPath() + "'"); + RegistrationSettings.REGISTRATION_TYPE.getPath() + "'");
configData.setValue(RegistrationSettings.REGISTRATION_TYPE, registrationType); configData.setValue(RegistrationSettings.REGISTRATION_TYPE, registrationType);
configData.setValue(RegistrationSettings.REGISTER_SECOND_ARGUMENT, secondaryArgument); configData.setValue(RegistrationSettings.REGISTER_SECOND_ARGUMENT, secondaryArgument);
@ -318,7 +320,7 @@ public class SettingsMigrationService extends PlainMigrationService {
Set<HashAlgorithm> legacyHashes = SecuritySettings.LEGACY_HASHES.determineValue(reader); Set<HashAlgorithm> legacyHashes = SecuritySettings.LEGACY_HASHES.determineValue(reader);
legacyHashes.add(currentHash); legacyHashes.add(currentHash);
configData.setValue(SecuritySettings.LEGACY_HASHES, legacyHashes); configData.setValue(SecuritySettings.LEGACY_HASHES, legacyHashes);
ConsoleLogger.warning("The hash algorithm '" + currentHash logger.warning("The hash algorithm '" + currentHash
+ "' is no longer supported for active use. New hashes will be in SHA256."); + "' is no longer supported for active use. New hashes will be in SHA256.");
return true; return true;
} }
@ -372,9 +374,9 @@ public class SettingsMigrationService extends PlainMigrationService {
ConfigurationData configData) { ConfigurationData configData) {
if (reader.contains(oldProperty.getPath())) { if (reader.contains(oldProperty.getPath())) {
if (reader.contains(newProperty.getPath())) { if (reader.contains(newProperty.getPath())) {
ConsoleLogger.info("Detected deprecated property " + oldProperty.getPath()); logger.info("Detected deprecated property " + oldProperty.getPath());
} else { } else {
ConsoleLogger.info("Renaming " + oldProperty.getPath() + " to " + newProperty.getPath()); logger.info("Renaming " + oldProperty.getPath() + " to " + newProperty.getPath());
configData.setValue(newProperty, oldProperty.determineValue(reader)); configData.setValue(newProperty, oldProperty.determineValue(reader));
} }
return true; return true;

View File

@ -2,6 +2,7 @@ package fr.xephi.authme.settings;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.security.HashAlgorithm; import fr.xephi.authme.security.HashAlgorithm;
import fr.xephi.authme.security.crypts.Argon2; import fr.xephi.authme.security.crypts.Argon2;
import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.BukkitService;
@ -22,6 +23,8 @@ import java.util.Optional;
* see {@link SettingsMigrationService}. * see {@link SettingsMigrationService}.
*/ */
public class SettingsWarner { public class SettingsWarner {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(SettingsWarner.class);
@Inject @Inject
private Settings settings; private Settings settings;
@ -41,25 +44,25 @@ public class SettingsWarner {
public void logWarningsForMisconfigurations() { public void logWarningsForMisconfigurations() {
// Force single session disabled // Force single session disabled
if (!settings.getProperty(RestrictionSettings.FORCE_SINGLE_SESSION)) { if (!settings.getProperty(RestrictionSettings.FORCE_SINGLE_SESSION)) {
ConsoleLogger.warning("WARNING!!! By disabling ForceSingleSession, your server protection is inadequate!"); logger.warning("WARNING!!! By disabling ForceSingleSession, your server protection is inadequate!");
} }
// Use TLS property only affects port 25 // Use TLS property only affects port 25
if (!settings.getProperty(EmailSettings.PORT25_USE_TLS) if (!settings.getProperty(EmailSettings.PORT25_USE_TLS)
&& settings.getProperty(EmailSettings.SMTP_PORT) != 25) { && settings.getProperty(EmailSettings.SMTP_PORT) != 25) {
ConsoleLogger.warning("Note: You have set Email.useTls to false but this only affects mail over port 25"); logger.warning("Note: You have set Email.useTls to false but this only affects mail over port 25");
} }
// Output hint if sessions are enabled that the timeout must be positive // Output hint if sessions are enabled that the timeout must be positive
if (settings.getProperty(PluginSettings.SESSIONS_ENABLED) if (settings.getProperty(PluginSettings.SESSIONS_ENABLED)
&& settings.getProperty(PluginSettings.SESSIONS_TIMEOUT) <= 0) { && settings.getProperty(PluginSettings.SESSIONS_TIMEOUT) <= 0) {
ConsoleLogger.warning("Warning: Session timeout needs to be positive in order to work!"); logger.warning("Warning: Session timeout needs to be positive in order to work!");
} }
// Warn if spigot.yml has settings.bungeecord set to true but config.yml has Hooks.bungeecord set to false // Warn if spigot.yml has settings.bungeecord set to true but config.yml has Hooks.bungeecord set to false
if (isTrue(bukkitService.isBungeeCordConfiguredForSpigot()) if (isTrue(bukkitService.isBungeeCordConfiguredForSpigot())
&& !settings.getProperty(HooksSettings.BUNGEECORD)) { && !settings.getProperty(HooksSettings.BUNGEECORD)) {
ConsoleLogger.warning("Note: Hooks.bungeecord is set to false but your server appears to be running in" logger.warning("Note: Hooks.bungeecord is set to false but your server appears to be running in"
+ " bungeecord mode (see your spigot.yml). In order to allow the datasource caching and the" + " bungeecord mode (see your spigot.yml). In order to allow the datasource caching and the"
+ " AuthMeBungee add-on to work properly you have to enable this option!"); + " AuthMeBungee add-on to work properly you have to enable this option!");
} }
@ -67,7 +70,7 @@ public class SettingsWarner {
// Check if argon2 library is present and can be loaded // Check if argon2 library is present and can be loaded
if (settings.getProperty(SecuritySettings.PASSWORD_HASH).equals(HashAlgorithm.ARGON2) if (settings.getProperty(SecuritySettings.PASSWORD_HASH).equals(HashAlgorithm.ARGON2)
&& !Argon2.isLibraryLoaded()) { && !Argon2.isLibraryLoaded()) {
ConsoleLogger.warning("WARNING!!! You use Argon2 Hash Algorithm method but we can't find the Argon2 " logger.warning("WARNING!!! You use Argon2 Hash Algorithm method but we can't find the Argon2 "
+ "library on your system! See https://github.com/AuthMe/AuthMeReloaded/wiki/Argon2-as-Password-Hash"); + "library on your system! See https://github.com/AuthMe/AuthMeReloaded/wiki/Argon2-as-Password-Hash");
authMe.stopOrUnload(); authMe.stopOrUnload();
} }

View File

@ -3,6 +3,7 @@ package fr.xephi.authme.settings;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.initialization.DataFolder;
import fr.xephi.authme.initialization.Reloadable; import fr.xephi.authme.initialization.Reloadable;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.service.PluginHookService; import fr.xephi.authme.service.PluginHookService;
import fr.xephi.authme.settings.properties.HooksSettings; import fr.xephi.authme.settings.properties.HooksSettings;
import fr.xephi.authme.settings.properties.RestrictionSettings; import fr.xephi.authme.settings.properties.RestrictionSettings;
@ -29,6 +30,8 @@ import java.io.IOException;
*/ */
public class SpawnLoader implements Reloadable { public class SpawnLoader implements Reloadable {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(SpawnLoader.class);
private final File authMeConfigurationFile; private final File authMeConfigurationFile;
private final Settings settings; private final Settings settings;
private final PluginHookService pluginHookService; private final PluginHookService pluginHookService;
@ -120,7 +123,7 @@ public class SpawnLoader implements Reloadable {
YamlConfiguration.loadConfiguration(essentialsSpawnFile), "spawns.default"); YamlConfiguration.loadConfiguration(essentialsSpawnFile), "spawns.default");
} else { } else {
essentialsSpawn = null; essentialsSpawn = null;
ConsoleLogger.info("Essentials spawn file not found: '" + essentialsSpawnFile.getAbsolutePath() + "'"); logger.info("Essentials spawn file not found: '" + essentialsSpawnFile.getAbsolutePath() + "'");
} }
} }
@ -145,7 +148,7 @@ public class SpawnLoader implements Reloadable {
cmiSpawn = getLocationFromCmiConfiguration(YamlConfiguration.loadConfiguration(cmiConfig)); cmiSpawn = getLocationFromCmiConfiguration(YamlConfiguration.loadConfiguration(cmiConfig));
} else { } else {
cmiSpawn = null; cmiSpawn = null;
ConsoleLogger.info("CMI config file not found: '" + cmiConfig.getAbsolutePath() + "'"); logger.info("CMI config file not found: '" + cmiConfig.getAbsolutePath() + "'");
} }
} }
@ -198,11 +201,11 @@ public class SpawnLoader implements Reloadable {
// ignore // ignore
} }
if (spawnLoc != null) { if (spawnLoc != null) {
ConsoleLogger.debug("Spawn location determined as `{0}` for world `{1}`", spawnLoc, world.getName()); logger.debug("Spawn location determined as `{0}` for world `{1}`", spawnLoc, world.getName());
return spawnLoc; return spawnLoc;
} }
} }
ConsoleLogger.debug("Fall back to default world spawn location. World: `{0}`", world.getName()); logger.debug("Fall back to default world spawn location. World: `{0}`", world.getName());
return world.getSpawnLocation(); // return default location return world.getSpawnLocation(); // return default location
} }
@ -232,7 +235,7 @@ public class SpawnLoader implements Reloadable {
authMeConfiguration.save(authMeConfigurationFile); authMeConfiguration.save(authMeConfigurationFile);
return true; return true;
} catch (IOException e) { } catch (IOException e) {
ConsoleLogger.logException("Could not save spawn config (" + authMeConfigurationFile + ")", e); logger.logException("Could not save spawn config (" + authMeConfigurationFile + ")", e);
} }
return false; return false;
} }

View File

@ -4,6 +4,7 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.initialization.DataFolder;
import fr.xephi.authme.initialization.Reloadable; import fr.xephi.authme.initialization.Reloadable;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.CommonService;
import fr.xephi.authme.service.GeoIpService; import fr.xephi.authme.service.GeoIpService;
@ -35,6 +36,8 @@ import static fr.xephi.authme.util.lazytags.TagBuilder.createTag;
* Configuration for the welcome message (welcome.txt). * Configuration for the welcome message (welcome.txt).
*/ */
public class WelcomeMessageConfiguration implements Reloadable { public class WelcomeMessageConfiguration implements Reloadable {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(WelcomeMessageConfiguration.class);
@DataFolder @DataFolder
@Inject @Inject
@ -125,10 +128,10 @@ public class WelcomeMessageConfiguration implements Reloadable {
try { try {
return Files.readAllLines(welcomeFile.toPath(), StandardCharsets.UTF_8); return Files.readAllLines(welcomeFile.toPath(), StandardCharsets.UTF_8);
} catch (IOException e) { } catch (IOException e) {
ConsoleLogger.logException("Failed to read welcome.txt file:", e); logger.logException("Failed to read welcome.txt file:", e);
} }
} else { } else {
ConsoleLogger.warning("Failed to copy welcome.txt from JAR"); logger.warning("Failed to copy welcome.txt from JAR");
} }
return Collections.emptyList(); return Collections.emptyList();
} }

View File

@ -129,6 +129,10 @@ public final class DatabaseSettings implements SettingsHolder {
public static final Property<String> MYSQL_COL_LASTLOC_PITCH = public static final Property<String> MYSQL_COL_LASTLOC_PITCH =
newProperty("DataSource.mySQLlastlocPitch", "pitch"); newProperty("DataSource.mySQLlastlocPitch", "pitch");
@Comment("Column for storing players uuids (optional)")
public static final Property<String> MYSQL_COL_PLAYER_UUID =
newProperty( "DataSource.mySQLPlayerUUID", "" );
@Comment("Column for storing players groups") @Comment("Column for storing players groups")
public static final Property<String> MYSQL_COL_GROUP = public static final Property<String> MYSQL_COL_GROUP =
newProperty("ExternalBoardOptions.mySQLColumnGroup", ""); newProperty("ExternalBoardOptions.mySQLColumnGroup", "");

View File

@ -2,6 +2,7 @@ package fr.xephi.authme.task.purge;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.service.PluginHookService; import fr.xephi.authme.service.PluginHookService;
@ -21,6 +22,8 @@ import static fr.xephi.authme.util.FileUtils.makePath;
* Executes the purge operations. * Executes the purge operations.
*/ */
public class PurgeExecutor { public class PurgeExecutor {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(PurgeExecutor.class);
@Inject @Inject
private Settings settings; private Settings settings;
@ -85,7 +88,7 @@ public class PurgeExecutor {
} }
} }
ConsoleLogger.info("AutoPurge: Removed " + i + " AntiXRayData Files"); logger.info("AutoPurge: Removed " + i + " AntiXRayData Files");
} }
/** /**
@ -96,7 +99,7 @@ public class PurgeExecutor {
synchronized void purgeFromAuthMe(Collection<String> names) { synchronized void purgeFromAuthMe(Collection<String> names) {
dataSource.purgeRecords(names); dataSource.purgeRecords(names);
//TODO ljacqu 20160717: We shouldn't output namedBanned.size() but the actual total that was deleted //TODO ljacqu 20160717: We shouldn't output namedBanned.size() but the actual total that was deleted
ConsoleLogger.info(ChatColor.GOLD + "Deleted " + names.size() + " user accounts"); logger.info(ChatColor.GOLD + "Deleted " + names.size() + " user accounts");
} }
/** /**
@ -141,7 +144,7 @@ public class PurgeExecutor {
} }
} }
} }
ConsoleLogger.info("AutoPurge: Removed " + i + " LimitedCreative Survival, Creative and Adventure files"); logger.info("AutoPurge: Removed " + i + " LimitedCreative Survival, Creative and Adventure files");
} }
/** /**
@ -165,7 +168,7 @@ public class PurgeExecutor {
} }
} }
ConsoleLogger.info("AutoPurge: Removed " + i + " .dat Files"); logger.info("AutoPurge: Removed " + i + " .dat Files");
} }
/** /**
@ -180,7 +183,7 @@ public class PurgeExecutor {
File essentialsDataFolder = pluginHookService.getEssentialsDataFolder(); File essentialsDataFolder = pluginHookService.getEssentialsDataFolder();
if (essentialsDataFolder == null) { if (essentialsDataFolder == null) {
ConsoleLogger.info("Cannot purge Essentials: plugin is not loaded"); logger.info("Cannot purge Essentials: plugin is not loaded");
return; return;
} }
@ -197,7 +200,7 @@ public class PurgeExecutor {
} }
} }
ConsoleLogger.info("AutoPurge: Removed " + deletedFiles + " EssentialsFiles"); logger.info("AutoPurge: Removed " + deletedFiles + " EssentialsFiles");
} }
/** /**
@ -212,12 +215,12 @@ public class PurgeExecutor {
for (OfflinePlayer offlinePlayer : cleared) { for (OfflinePlayer offlinePlayer : cleared) {
if (!permissionsManager.loadUserData(offlinePlayer)) { if (!permissionsManager.loadUserData(offlinePlayer)) {
ConsoleLogger.warning("Unable to purge the permissions of user " + offlinePlayer + "!"); logger.warning("Unable to purge the permissions of user " + offlinePlayer + "!");
continue; continue;
} }
permissionsManager.removeAllGroups(offlinePlayer); permissionsManager.removeAllGroups(offlinePlayer);
} }
ConsoleLogger.info("AutoPurge: Removed permissions from " + cleared.size() + " player(s)."); logger.info("AutoPurge: Removed permissions from " + cleared.size() + " player(s).");
} }
} }

View File

@ -2,6 +2,7 @@ package fr.xephi.authme.task.purge;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
@ -21,6 +22,8 @@ import static fr.xephi.authme.util.Utils.logAndSendMessage;
* Initiates purge tasks. * Initiates purge tasks.
*/ */
public class PurgeService { public class PurgeService {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(PurgeService.class);
@Inject @Inject
private BukkitService bukkitService; private BukkitService bukkitService;
@ -51,11 +54,11 @@ public class PurgeService {
if (!settings.getProperty(PurgeSettings.USE_AUTO_PURGE)) { if (!settings.getProperty(PurgeSettings.USE_AUTO_PURGE)) {
return; return;
} else if (daysBeforePurge <= 0) { } else if (daysBeforePurge <= 0) {
ConsoleLogger.warning("Did not run auto purge: configured days before purging must be positive"); logger.warning("Did not run auto purge: configured days before purging must be positive");
return; return;
} }
ConsoleLogger.info("Automatically purging the database..."); logger.info("Automatically purging the database...");
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -daysBeforePurge); calendar.add(Calendar.DATE, -daysBeforePurge);
long until = calendar.getTimeInMillis(); long until = calendar.getTimeInMillis();

View File

@ -1,6 +1,7 @@
package fr.xephi.authme.task.purge; package fr.xephi.authme.task.purge;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.permission.PlayerStatePermission; import fr.xephi.authme.permission.PlayerStatePermission;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -19,6 +20,7 @@ class PurgeTask extends BukkitRunnable {
//how many players we should check for each tick //how many players we should check for each tick
private static final int INTERVAL_CHECK = 5; private static final int INTERVAL_CHECK = 5;
private final ConsoleLogger logger = ConsoleLoggerFactory.get(PurgeTask.class);
private final PurgeService purgeService; private final PurgeService purgeService;
private final PermissionsManager permissionsManager; private final PermissionsManager permissionsManager;
private final UUID sender; private final UUID sender;
@ -74,7 +76,7 @@ class PurgeTask extends BukkitRunnable {
OfflinePlayer offlinePlayer = offlinePlayers[nextPosition]; OfflinePlayer offlinePlayer = offlinePlayers[nextPosition];
if (offlinePlayer.getName() != null && toPurge.remove(offlinePlayer.getName().toLowerCase())) { if (offlinePlayer.getName() != null && toPurge.remove(offlinePlayer.getName().toLowerCase())) {
if (!permissionsManager.loadUserData(offlinePlayer)) { if (!permissionsManager.loadUserData(offlinePlayer)) {
ConsoleLogger.warning("Unable to check if the user " + offlinePlayer.getName() + " can be purged!"); logger.warning("Unable to check if the user " + offlinePlayer.getName() + " can be purged!");
continue; continue;
} }
if (!permissionsManager.hasPermissionOffline(offlinePlayer, PlayerStatePermission.BYPASS_PURGE)) { if (!permissionsManager.hasPermissionOffline(offlinePlayer, PlayerStatePermission.BYPASS_PURGE)) {
@ -85,7 +87,7 @@ class PurgeTask extends BukkitRunnable {
} }
if (!toPurge.isEmpty() && playerPortion.isEmpty()) { if (!toPurge.isEmpty() && playerPortion.isEmpty()) {
ConsoleLogger.info("Finished lookup of offlinePlayers. Begin looking purging player names only"); logger.info("Finished lookup of offlinePlayers. Begin looking purging player names only");
//we went through all offlineplayers but there are still names remaining //we went through all offlineplayers but there are still names remaining
for (String name : toPurge) { for (String name : toPurge) {
@ -110,7 +112,7 @@ class PurgeTask extends BukkitRunnable {
// Show a status message // Show a status message
sendMessage(ChatColor.GREEN + "[AuthMe] Database has been purged successfully"); sendMessage(ChatColor.GREEN + "[AuthMe] Database has been purged successfully");
ConsoleLogger.info("Purge finished!"); logger.info("Purge finished!");
purgeService.setPurging(false); purgeService.setPurging(false);
} }

View File

@ -3,6 +3,7 @@ package fr.xephi.authme.util;
import com.google.common.io.Files; import com.google.common.io.Files;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -20,6 +21,8 @@ public final class FileUtils {
private static final DateTimeFormatter CURRENT_DATE_STRING_FORMATTER = private static final DateTimeFormatter CURRENT_DATE_STRING_FORMATTER =
DateTimeFormatter.ofPattern("yyyyMMdd_HHmm"); DateTimeFormatter.ofPattern("yyyyMMdd_HHmm");
private static ConsoleLogger logger = ConsoleLoggerFactory.get(FileUtils.class);
// Utility class // Utility class
private FileUtils() { private FileUtils() {
} }
@ -36,20 +39,20 @@ public final class FileUtils {
if (destinationFile.exists()) { if (destinationFile.exists()) {
return true; return true;
} else if (!createDirectory(destinationFile.getParentFile())) { } else if (!createDirectory(destinationFile.getParentFile())) {
ConsoleLogger.warning("Cannot create parent directories for '" + destinationFile + "'"); logger.warning("Cannot create parent directories for '" + destinationFile + "'");
return false; return false;
} }
try (InputStream is = getResourceFromJar(resourcePath)) { try (InputStream is = getResourceFromJar(resourcePath)) {
if (is == null) { if (is == null) {
ConsoleLogger.warning(format("Cannot copy resource '%s' to file '%s': cannot load resource", logger.warning(format("Cannot copy resource '%s' to file '%s': cannot load resource",
resourcePath, destinationFile.getPath())); resourcePath, destinationFile.getPath()));
} else { } else {
java.nio.file.Files.copy(is, destinationFile.toPath()); java.nio.file.Files.copy(is, destinationFile.toPath());
return true; return true;
} }
} catch (IOException e) { } catch (IOException e) {
ConsoleLogger.logException(format("Cannot copy resource '%s' to file '%s':", logger.logException(format("Cannot copy resource '%s' to file '%s':",
resourcePath, destinationFile.getPath()), e); resourcePath, destinationFile.getPath()), e);
} }
return false; return false;
@ -63,7 +66,7 @@ public final class FileUtils {
*/ */
public static boolean createDirectory(File dir) { public static boolean createDirectory(File dir) {
if (!dir.exists() && !dir.mkdirs()) { if (!dir.exists() && !dir.mkdirs()) {
ConsoleLogger.warning("Could not create directory '" + dir + "'"); logger.warning("Could not create directory '" + dir + "'");
return false; return false;
} }
return dir.isDirectory(); return dir.isDirectory();
@ -112,7 +115,7 @@ public final class FileUtils {
if (file != null) { if (file != null) {
boolean result = file.delete(); boolean result = file.delete();
if (!result) { if (!result) {
ConsoleLogger.warning("Could not delete file '" + file + "'"); logger.warning("Could not delete file '" + file + "'");
} }
} }
} }

View File

@ -1,6 +1,7 @@
package fr.xephi.authme.util; package fr.xephi.authme.util;
import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender; import org.bukkit.command.ConsoleCommandSender;
@ -15,8 +16,8 @@ public final class Utils {
/** Number of milliseconds in a minute. */ /** Number of milliseconds in a minute. */
public static final long MILLIS_PER_MINUTE = 60_000L; public static final long MILLIS_PER_MINUTE = 60_000L;
/** Number of milliseconds in an hour. */
public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE; private static ConsoleLogger logger = ConsoleLoggerFactory.get(Utils.class);
// Utility class // Utility class
private Utils() { private Utils() {
@ -33,7 +34,7 @@ public final class Utils {
try { try {
return Pattern.compile(pattern); return Pattern.compile(pattern);
} catch (Exception e) { } catch (Exception e) {
ConsoleLogger.warning("Failed to compile pattern '" + pattern + "' - defaulting to allowing everything"); logger.warning("Failed to compile pattern '" + pattern + "' - defaulting to allowing everything");
return Pattern.compile(".*?"); return Pattern.compile(".*?");
} }
} }
@ -63,7 +64,7 @@ public final class Utils {
* @param message the message to log and send * @param message the message to log and send
*/ */
public static void logAndSendMessage(CommandSender sender, String message) { public static void logAndSendMessage(CommandSender sender, String message) {
ConsoleLogger.info(message); logger.info(message);
// Make sure sender is not console user, which will see the message from ConsoleLogger already // Make sure sender is not console user, which will see the message from ConsoleLogger already
if (sender != null && !(sender instanceof ConsoleCommandSender)) { if (sender != null && !(sender instanceof ConsoleCommandSender)) {
sender.sendMessage(message); sender.sendMessage(message);
@ -79,7 +80,7 @@ public final class Utils {
* @param message the warning to log and send * @param message the warning to log and send
*/ */
public static void logAndSendWarning(CommandSender sender, String message) { public static void logAndSendWarning(CommandSender sender, String message) {
ConsoleLogger.warning(message); logger.warning(message);
// Make sure sender is not console user, which will see the message from ConsoleLogger already // Make sure sender is not console user, which will see the message from ConsoleLogger already
if (sender != null && !(sender instanceof ConsoleCommandSender)) { if (sender != null && !(sender instanceof ConsoleCommandSender)) {
sender.sendMessage(ChatColor.RED + message); sender.sendMessage(ChatColor.RED + message);

View File

@ -0,0 +1,27 @@
package fr.xephi.authme.util;
import java.util.UUID;
/**
* Utility class for various operations on UUID.
*/
public final class UuidUtils {
// Utility class
private UuidUtils() {
}
/**
* Returns whether the given string as an UUID or null
*
* @param string the uuid to parse
* @return parsed UUID if succeed or null
*/
public static UUID parseUuidSafely(String string) {
try {
return UUID.fromString(string);
} catch (IllegalArgumentException | NullPointerException ex) {
return null;
}
}
}

View File

@ -15,6 +15,7 @@ import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import java.io.File; import java.io.File;
import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
@ -28,9 +29,11 @@ import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@ -42,6 +45,8 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class ConsoleLoggerTest { public class ConsoleLoggerTest {
private ConsoleLogger consoleLogger;
@Mock @Mock
private Logger logger; private Logger logger;
@ -52,19 +57,19 @@ public class ConsoleLoggerTest {
@Before @Before
public void setMockLogger() throws IOException { public void setMockLogger() throws IOException {
ConsoleLogger.setLogger(logger);
File folder = temporaryFolder.newFolder(); File folder = temporaryFolder.newFolder();
File logFile = new File(folder, "authme.log"); File logFile = new File(folder, "authme.log");
if (!logFile.createNewFile()) { if (!logFile.createNewFile()) {
throw new IOException("Could not create file '" + logFile.getPath() + "'"); throw new IOException("Could not create file '" + logFile.getPath() + "'");
} }
ConsoleLogger.setLogFile(logFile); ConsoleLogger.initialize(logger, logFile);
this.logFile = logFile; this.logFile = logFile;
this.consoleLogger = new ConsoleLogger("test");
} }
@After @After
public void closeFileHandlers() { public void closeFileHandlers() {
ConsoleLogger.close(); ConsoleLogger.closeFileWriter();
} }
/** /**
@ -74,18 +79,20 @@ public class ConsoleLoggerTest {
*/ */
@AfterClass @AfterClass
public static void resetConsoleToDefault() { public static void resetConsoleToDefault() {
ConsoleLogger.setLoggingOptions(newSettings(false, LogLevel.FINE)); ConsoleLogger.initializeSharedSettings(newSettings(false, LogLevel.INFO));
} }
@Test @Test
public void shouldLogToFile() throws IOException { public void shouldLogToFile() throws IOException {
// given // given
ConsoleLogger.setLoggingOptions(newSettings(true, LogLevel.FINE)); Settings settings = newSettings(true, LogLevel.FINE);
ConsoleLogger.initializeSharedSettings(settings);
consoleLogger.initializeSettings(settings);
// when // when
ConsoleLogger.fine("Logging a FINE message"); consoleLogger.fine("Logging a FINE message");
ConsoleLogger.debug("Logging a DEBUG message"); consoleLogger.debug("Logging a DEBUG message");
ConsoleLogger.info("This is an INFO message"); consoleLogger.info("This is an INFO message");
// then // then
verify(logger, times(2)).info(anyString()); verify(logger, times(2)).info(anyString());
@ -97,13 +104,15 @@ public class ConsoleLoggerTest {
} }
@Test @Test
public void shouldNotLogToFile() throws IOException { public void shouldNotLogToFile() {
// given // given
ConsoleLogger.setLoggingOptions(newSettings(false, LogLevel.DEBUG)); Settings settings = newSettings(false, LogLevel.DEBUG);
ConsoleLogger.initializeSharedSettings(settings);
consoleLogger.initializeSettings(settings);
// when // when
ConsoleLogger.debug("Created test"); consoleLogger.debug("Created test");
ConsoleLogger.warning("Encountered a warning"); consoleLogger.warning("Encountered a warning");
// then // then
verify(logger).info("[DEBUG] Created test"); verify(logger).info("[DEBUG] Created test");
@ -115,14 +124,15 @@ public class ConsoleLoggerTest {
@Test @Test
public void shouldLogStackTraceToFile() throws IOException { public void shouldLogStackTraceToFile() throws IOException {
// given // given
ConsoleLogger.setLoggingOptions(newSettings(true, LogLevel.INFO)); Settings settings = newSettings(true, LogLevel.INFO);
ConsoleLogger.initializeSharedSettings(settings);
Exception e = new IllegalStateException("Test exception message"); Exception e = new IllegalStateException("Test exception message");
// when // when
ConsoleLogger.info("Info text"); consoleLogger.info("Info text");
ConsoleLogger.debug("Debug message"); consoleLogger.debug("Debug message");
ConsoleLogger.fine("Fine-level message"); consoleLogger.fine("Fine-level message");
ConsoleLogger.logException("Exception occurred:", e); consoleLogger.logException("Exception occurred:", e);
// then // then
verify(logger).info("Info text"); verify(logger).info("Info text");
@ -140,13 +150,15 @@ public class ConsoleLoggerTest {
@Test @Test
public void shouldSupportVariousDebugMethods() throws IOException { public void shouldSupportVariousDebugMethods() throws IOException {
// given // given
ConsoleLogger.setLoggingOptions(newSettings(true, LogLevel.DEBUG)); Settings settings = newSettings(true, LogLevel.DEBUG);
ConsoleLogger.initializeSharedSettings(settings);
consoleLogger.initializeSettings(settings);
// when // when
ConsoleLogger.debug("Got {0} entries", 17); consoleLogger.debug("Got {0} entries", 17);
ConsoleLogger.debug("Player `{0}` is in world `{1}`", "Bobby", new World("world")); consoleLogger.debug("Player `{0}` is in world `{1}`", "Bobby", new World("world"));
ConsoleLogger.debug("{0} quick {1} jump over {2} lazy {3} (reason: {4})", 5, "foxes", 3, "dogs", null); consoleLogger.debug("{0} quick {1} jump over {2} lazy {3} (reason: {4})", 5, "foxes", 3, "dogs", null);
ConsoleLogger.debug(() -> "Too little too late"); consoleLogger.debug(() -> "Too little too late");
// then // then
verify(logger).log(Level.INFO, "[DEBUG] Got {0} entries", 17); verify(logger).log(Level.INFO, "[DEBUG] Got {0} entries", 17);
@ -164,8 +176,35 @@ public class ConsoleLoggerTest {
} }
@Test @Test
public void shouldHaveHiddenConstructor() { public void shouldCloseFileWriterDespiteExceptionOnFlush() throws IOException {
TestHelper.validateHasOnlyPrivateEmptyConstructor(ConsoleLogger.class); // given
FileWriter fileWriter = mock(FileWriter.class);
doThrow(new IOException("Error during flush")).when(fileWriter).flush();
ReflectionTestUtils.setField(ConsoleLogger.class, null, "fileWriter", fileWriter);
// when
ConsoleLogger.closeFileWriter();
// then
verify(fileWriter).flush();
verify(fileWriter).close();
assertThat(ReflectionTestUtils.getFieldValue(ConsoleLogger.class, null, "fileWriter"), nullValue());
}
@Test
public void shouldHandleExceptionOnFileWriterClose() throws IOException {
// given
FileWriter fileWriter = mock(FileWriter.class);
doThrow(new IOException("Cannot close")).when(fileWriter).close();
ReflectionTestUtils.setField(ConsoleLogger.class, null, "fileWriter", fileWriter);
// when
ConsoleLogger.closeFileWriter();
// then
verify(fileWriter).flush();
verify(fileWriter).close();
assertThat(ReflectionTestUtils.getFieldValue(ConsoleLogger.class, null, "fileWriter"), nullValue());
} }
private static Settings newSettings(boolean logToFile, LogLevel logLevel) { private static Settings newSettings(boolean logToFile, LogLevel logLevel) {

View File

@ -80,7 +80,7 @@ public final class TestHelper {
*/ */
public static Logger setupLogger() { public static Logger setupLogger() {
Logger logger = Mockito.mock(Logger.class); Logger logger = Mockito.mock(Logger.class);
ConsoleLogger.setLogger(logger); ConsoleLogger.initialize(logger, null);
return logger; return logger;
} }
@ -91,7 +91,7 @@ public final class TestHelper {
*/ */
public static Logger setRealLogger() { public static Logger setRealLogger() {
Logger logger = Logger.getAnonymousLogger(); Logger logger = Logger.getAnonymousLogger();
ConsoleLogger.setLogger(logger); ConsoleLogger.initialize(logger, null);
return logger; return logger;
} }

Some files were not shown because too many files have changed in this diff Show More