#449 Migrate some properties to new settings

- Use new settings class for retrieving help header & backup configs
- Delete migrated configs from old settings
This commit is contained in:
ljacqu 2016-01-30 13:19:05 +01:00
parent dedb3fce26
commit 724296e02b
7 changed files with 118 additions and 146 deletions

View File

@ -45,10 +45,12 @@ import fr.xephi.authme.process.Management;
import fr.xephi.authme.security.HashAlgorithm;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.security.crypts.HashedPassword;
import fr.xephi.authme.settings.NewSetting;
import fr.xephi.authme.settings.OtherAccounts;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.Spawn;
import fr.xephi.authme.settings.NewSetting;
import fr.xephi.authme.settings.properties.DatabaseSettings;
import fr.xephi.authme.util.CollectionUtils;
import fr.xephi.authme.util.GeoLiteAPI;
import fr.xephi.authme.util.StringUtils;
import fr.xephi.authme.util.Utils;
@ -81,6 +83,8 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import static fr.xephi.authme.settings.properties.PluginSettings.HELP_HEADER;
/**
* The AuthMe main class.
*/
@ -279,7 +283,7 @@ public class AuthMe extends JavaPlugin {
// End of Hooks
// Do a backup on start
new PerformBackup(plugin).doBackup(PerformBackup.BackupCause.START);
new PerformBackup(plugin, newSettings).doBackup(PerformBackup.BackupCause.START);
// Setup the inventory backup
@ -422,7 +426,7 @@ public class AuthMe extends JavaPlugin {
private CommandHandler initializeCommandHandler(PermissionsManager permissionsManager, Messages messages,
PasswordSecurity passwordSecurity, NewSetting settings) {
HelpProvider helpProvider = new HelpProvider(permissionsManager);
HelpProvider helpProvider = new HelpProvider(permissionsManager, settings.getProperty(HELP_HEADER));
Set<CommandDescription> baseCommands = CommandInitializer.buildCommands();
CommandMapper mapper = new CommandMapper(baseCommands, permissionsManager);
CommandService commandService = new CommandService(
@ -530,7 +534,7 @@ public class AuthMe extends JavaPlugin {
}
// Do backup on stop if enabled
new PerformBackup(plugin).doBackup(PerformBackup.BackupCause.STOP);
new PerformBackup(plugin, newSettings).doBackup(PerformBackup.BackupCause.STOP);
// Unload modules
if (moduleManager != null) {
@ -595,7 +599,7 @@ public class AuthMe extends JavaPlugin {
database.close();
// Backend MYSQL - FILE - SQLITE - SQLITEHIKARI
boolean isSQLite = false;
switch (Settings.getDataSource) {
switch (newSettings.getProperty(DatabaseSettings.BACKEND)) {
case FILE:
database = new FlatFile();
break;
@ -788,16 +792,14 @@ public class AuthMe extends JavaPlugin {
PlayerCache.getInstance().removePlayer(name);
}
// Select the player to kick when a vip player join the server when full
// Select the player to kick when a vip player joins the server when full
public Player generateKickPlayer(Collection<? extends Player> collection) {
Player player = null;
for (Player p : collection) {
if (!getPermissionsManager().hasPermission(p, PlayerPermission.IS_VIP)) {
player = p;
break;
for (Player player : collection) {
if (!getPermissionsManager().hasPermission(player, PlayerPermission.IS_VIP)) {
return player;
}
}
return player;
return null;
}
// Purge inactive players from the database, as defined in the configuration
@ -809,10 +811,7 @@ public class AuthMe extends JavaPlugin {
calendar.add(Calendar.DATE, -(Settings.purgeDelay));
long until = calendar.getTimeInMillis();
List<String> cleared = database.autoPurgeDatabase(until);
if (cleared == null) {
return;
}
if (cleared.isEmpty()) {
if (CollectionUtils.isEmpty(cleared)) {
return;
}
ConsoleLogger.info("AutoPurging the Database: " + cleared.size() + " accounts removed!");

View File

@ -1,8 +1,17 @@
package fr.xephi.authme;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.settings.NewSetting;
import fr.xephi.authme.settings.properties.BackupSettings;
import fr.xephi.authme.settings.properties.DatabaseSettings;
import fr.xephi.authme.util.StringUtils;
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
@ -10,47 +19,51 @@ import java.util.Date;
* The backup management class
*
* @author stefano
* @version $Revision: 1.0 $
*/
public class PerformBackup {
final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm");
final String dateString = format.format(new Date());
private final String dbName = Settings.getMySQLDatabase;
private final String dbUserName = Settings.getMySQLUsername;
private final String dbPassword = Settings.getMySQLPassword;
private final String tblname = Settings.getMySQLTablename;
private final String path = AuthMe.getInstance().getDataFolder() + File.separator + "backups" + File.separator + "backup" + dateString;
private AuthMe instance;
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd_HH-mm");
private final String dbName;
private final String dbUserName;
private final String dbPassword;
private final String tblname;
private final String path;
private final File dataFolder;
private final NewSetting settings;
/**
* Constructor for PerformBackup.
*
* @param instance AuthMe
*/
public PerformBackup(AuthMe instance) {
this.setInstance(instance);
public PerformBackup(AuthMe instance, NewSetting settings) {
this.dataFolder = instance.getDataFolder();
this.settings = settings;
this.dbName = settings.getProperty(DatabaseSettings.MYSQL_DATABASE);
this.dbUserName = settings.getProperty(DatabaseSettings.MYSQL_USERNAME);
this.dbPassword = settings.getProperty(DatabaseSettings.MYSQL_PASSWORD);
this.tblname = settings.getProperty(DatabaseSettings.MYSQL_TABLE);
String dateString = DATE_FORMAT.format(new Date());
this.path = StringUtils.join(File.separator,
instance.getDataFolder().getPath(), "backups", "backup" + dateString);
}
/**
* Perform a backup with the given reason.
*
* @param cause BackupCause The cause of the backup.
* @param cause The cause of the backup.
*/
public void doBackup(BackupCause cause) {
if (!Settings.isBackupActivated) {
ConsoleLogger.showError("Can't perform a Backup: disabled in configuration. Cause of the Backup: " + cause.name());
if (!settings.getProperty(BackupSettings.ENABLED)) {
ConsoleLogger.showError("Can't perform a Backup: disabled in configuration. Cause of the Backup: "
+ cause.name());
}
// Check whether a backup should be made at the specified point in time
switch (cause) {
case START:
if (!Settings.isBackupOnStart)
return;
case STOP:
if (!Settings.isBackupOnStop)
return;
case COMMAND:
case OTHER:
if (BackupCause.START.equals(cause) && !settings.getProperty(BackupSettings.ON_SERVER_START)
|| BackupCause.STOP.equals(cause) && !settings.getProperty(BackupSettings.ON_SERVER_STOP)) {
return;
}
// Do backup and check return value!
@ -61,37 +74,31 @@ public class PerformBackup {
}
}
/**
* Method doBackup.
*
* @return boolean
*/
public boolean doBackup() {
switch (Settings.getDataSource) {
DataSource.DataSourceType dataSourceType = settings.getProperty(DatabaseSettings.BACKEND);
switch (dataSourceType) {
case FILE:
return FileBackup("auths.db");
return fileBackup("auths.db");
case MYSQL:
return MySqlBackup();
return mySqlBackup();
case SQLITE:
return FileBackup(Settings.getMySQLDatabase + ".db");
return fileBackup(dbName + ".db");
default:
ConsoleLogger.showError("Unknown data source type '" + dataSourceType + "' for backup");
}
return false;
}
/**
* Method MySqlBackup.
*
* @return boolean
*/
private boolean MySqlBackup() {
File dirBackup = new File(AuthMe.getInstance().getDataFolder() + "/backups");
private boolean mySqlBackup() {
File dirBackup = new File(dataFolder + File.separator + "backups");
if (!dirBackup.exists())
if (!dirBackup.exists()) {
dirBackup.mkdir();
if (checkWindows(Settings.backupWindowsPath)) {
String executeCmd = Settings.backupWindowsPath + "\\bin\\mysqldump.exe -u " + dbUserName + " -p" + dbPassword + " " + dbName + " --tables " + tblname + " -r " + path + ".sql";
}
String backupWindowsPath = settings.getProperty(BackupSettings.MYSQL_WINDOWS_PATH);
if (checkWindows(backupWindowsPath)) {
String executeCmd = backupWindowsPath + "\\bin\\mysqldump.exe -u " + dbUserName + " -p" + dbPassword + " " + dbName + " --tables " + tblname + " -r " + path + ".sql";
Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
@ -102,8 +109,12 @@ public class PerformBackup {
} else {
ConsoleLogger.showError("Could not create the backup!");
}
} catch (Exception ex) {
ex.printStackTrace();
} catch (IOException e) {
ConsoleLogger.showError("Error during backup: " + StringUtils.formatException(e));
ConsoleLogger.writeStackTrace(e);
} catch (InterruptedException e) {
ConsoleLogger.showError("Backup was interrupted: " + StringUtils.formatException(e));
ConsoleLogger.writeStackTrace(e);
}
} else {
String executeCmd = "mysqldump -u " + dbUserName + " -p" + dbPassword + " " + dbName + " --tables " + tblname + " -r " + path + ".sql";
@ -117,69 +128,54 @@ public class PerformBackup {
} else {
ConsoleLogger.showError("Could not create the backup!");
}
} catch (Exception ex) {
ex.printStackTrace();
} catch (IOException e) {
ConsoleLogger.showError("Error during backup: " + StringUtils.formatException(e));
ConsoleLogger.writeStackTrace(e);
} catch (InterruptedException e) {
ConsoleLogger.showError("Backup was interrupted: " + StringUtils.formatException(e));
ConsoleLogger.writeStackTrace(e);
}
}
return false;
}
/**
* Method FileBackup.
*
* @param backend String
*
* @return boolean
*/
private boolean FileBackup(String backend) {
File dirBackup = new File(AuthMe.getInstance().getDataFolder() + "/backups");
private boolean fileBackup(String backend) {
File dirBackup = new File(dataFolder + File.separator + "backups");
if (!dirBackup.exists())
dirBackup.mkdir();
try {
copy(new File("plugins" + File.separator + "AuthMe" + File.separator + backend), new File(path + ".db"));
copy("plugins" + File.separator + "AuthMe" + File.separator + backend, path + ".db");
return true;
} catch (Exception ex) {
ex.printStackTrace();
} catch (IOException ex) {
ConsoleLogger.showError("Encountered an error during file backup: " + StringUtils.formatException(ex));
ConsoleLogger.writeStackTrace(ex);
}
return false;
}
/**
* Method checkWindows.
* Check if we are under Windows and correct location of mysqldump.exe
* otherwise return error.
*
* @param windowsPath String
*
* @return boolean
* @param windowsPath The path to check
* @return True if the path is correct, false if it is incorrect or the OS is not Windows
*/
private boolean checkWindows(String windowsPath) {
private static boolean checkWindows(String windowsPath) {
String isWin = System.getProperty("os.name").toLowerCase();
if (isWin.contains("win")) {
if (new File(windowsPath + "\\bin\\mysqldump.exe").exists()) {
return true;
} else {
ConsoleLogger.showError("Mysql Windows Path is incorrect please check it");
return true;
ConsoleLogger.showError("Mysql Windows Path is incorrect. Please check it");
return false;
}
} else return false;
}
return false;
}
/*
* Check if we are under Windows and correct location of mysqldump.exe
* otherwise return error.
*/
/**
* Method copy.
*
* @param src File
* @param dst File
*
* @throws IOException
*/
void copy(File src, File dst) throws IOException {
private static void copy(String src, String dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
@ -193,27 +189,6 @@ public class PerformBackup {
out.close();
}
/*
* Copyr src bytefile into dst file
*/
/**
* Method getInstance.
*
* @return AuthMe
*/
public AuthMe getInstance() {
return instance;
}
/**
* Method setInstance.
*
* @param instance AuthMe
*/
public void setInstance(AuthMe instance) {
this.instance = instance;
}
/**
* Possible backup causes.
@ -221,8 +196,7 @@ public class PerformBackup {
public enum BackupCause {
START,
STOP,
COMMAND,
OTHER,
COMMAND
}
}

View File

@ -3,7 +3,6 @@ package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.Settings;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
@ -11,12 +10,15 @@ import org.bukkit.entity.Player;
import java.util.List;
import static fr.xephi.authme.settings.properties.PluginSettings.HELP_HEADER;
public class VersionCommand implements ExecutableCommand {
@Override
public void executeCommand(CommandSender sender, List<String> arguments, CommandService commandService) {
// Show some version info
sender.sendMessage(ChatColor.GOLD + "==========[ " + Settings.helpHeader + " ABOUT ]==========");
sender.sendMessage(ChatColor.GOLD + "==========[ " + commandService.getProperty(HELP_HEADER)
+ " ABOUT ]==========");
sender.sendMessage(ChatColor.GOLD + "Version: " + ChatColor.WHITE + AuthMe.getPluginName()
+ " v" + AuthMe.getPluginVersion() + ChatColor.GRAY + " (build: " + AuthMe.getPluginBuildNumber() + ")");
sender.sendMessage(ChatColor.GOLD + "Developers:");

View File

@ -10,7 +10,6 @@ import fr.xephi.authme.command.FoundCommandResult;
import fr.xephi.authme.permission.DefaultPermission;
import fr.xephi.authme.permission.PermissionNode;
import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.util.CollectionUtils;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
@ -44,9 +43,11 @@ public class HelpProvider {
public static final int ALL_OPTIONS = ~HIDE_COMMAND;
private final PermissionsManager permissionsManager;
private final String helpHeader;
public HelpProvider(PermissionsManager permissionsManager) {
public HelpProvider(PermissionsManager permissionsManager, String helpHeader) {
this.permissionsManager = permissionsManager;
this.helpHeader = helpHeader;
}
public List<String> printHelp(CommandSender sender, FoundCommandResult result, int options) {
@ -55,7 +56,7 @@ public class HelpProvider {
}
List<String> lines = new ArrayList<>();
lines.add(ChatColor.GOLD + "==========[ " + Settings.helpHeader + " HELP ]==========");
lines.add(ChatColor.GOLD + "==========[ " + helpHeader + " HELP ]==========");
CommandDescription command = result.getCommandDescription();
List<String> labels = ImmutableList.copyOf(result.getLabels());

View File

@ -24,6 +24,7 @@ import java.util.List;
import java.util.regex.Pattern;
/**
* Old settings manager. See {@link NewSetting} for the new manager.
*/
public final class Settings {
@ -66,8 +67,7 @@ public final class Settings {
isSaveQuitLocationEnabled, isForceSurvivalModeEnabled,
isCachingEnabled,
isKickOnWrongPasswordEnabled, enablePasswordConfirmation,
protectInventoryBeforeLogInEnabled, isBackupActivated,
isBackupOnStart, isBackupOnStop, isStopEnabled, reloadSupport,
protectInventoryBeforeLogInEnabled, isStopEnabled, reloadSupport,
rakamakUseIp, noConsoleSpam, removePassword, displayOtherAccounts,
useCaptcha, emailRegistration, multiverse, bungee,
banUnsafeIp, doubleEmailCheck, sessionExpireOnIpChange,
@ -79,7 +79,7 @@ public final class Settings {
checkVeryGames, delayJoinLeaveMessages, noTeleport, applyBlindEffect,
kickPlayersBeforeStopping,
customAttributes, generateImage, isRemoveSpeedEnabled, preventOtherCase;
public static String helpHeader, getNickRegex, getUnloggedinGroup, getMySQLHost,
public static String getNickRegex, getUnloggedinGroup, getMySQLHost,
getMySQLPort, getMySQLUsername, getMySQLPassword, getMySQLDatabase,
getMySQLTablename, getMySQLColumnName, getMySQLColumnPassword,
getMySQLColumnIp, getMySQLColumnLastLogin, getMySQLColumnSalt,
@ -135,7 +135,6 @@ public final class Settings {
}
public static void loadVariables() {
helpHeader = configFile.getString("settings.helpHeader", "AuthMeReloaded");
messagesLanguage = checkLang(configFile.getString("settings.messagesLanguage", "en").toLowerCase());
isPermissionCheckEnabled = configFile.getBoolean("permission.EnablePermissionCheck", false);
isForcedRegistrationEnabled = configFile.getBoolean("settings.registration.force", true);
@ -201,9 +200,6 @@ public final class Settings {
plugin.checkProtocolLib();
passwordMaxLength = configFile.getInt("settings.security.passwordMaxLength", 20);
isBackupActivated = configFile.getBoolean("BackupSystem.ActivateBackup", false);
isBackupOnStart = configFile.getBoolean("BackupSystem.OnServerStart", false);
isBackupOnStop = configFile.getBoolean("BackupSystem.OnServeStop", false);
backupWindowsPath = configFile.getString("BackupSystem.MysqlWindowsPath", "C:\\Program Files\\MySQL\\MySQL Server 5.1\\");
isStopEnabled = configFile.getBoolean("Security.SQLProblem.stopServer", true);
reloadSupport = configFile.getBoolean("Security.ReloadCommand.useReloadCommandSupport", true);

View File

@ -52,11 +52,12 @@ public final class CollectionUtils {
}
/**
* @param <T> element
* @param coll Collection
* @return boolean Boolean
* Null-safe way to check whether a collection is empty or not.
*
* @param coll The collection to verify
* @return True if the collection is null or empty, false otherwise
*/
public static <T> boolean isEmpty(Collection<T> coll) {
public static boolean isEmpty(Collection<?> coll) {
return coll == null || coll.isEmpty();
}

View File

@ -6,7 +6,6 @@ import fr.xephi.authme.command.FoundResultStatus;
import fr.xephi.authme.command.TestCommandsUtil;
import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.permission.PlayerPermission;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.util.WrapperMock;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
@ -40,22 +39,22 @@ import static org.mockito.Mockito.mock;
*/
public class HelpProviderTest {
private static final String HELP_HEADER = "Help";
private static Set<CommandDescription> commands;
private HelpProvider helpProvider;
private PermissionsManager permissionsManager;
private CommandSender sender;
private static Set<CommandDescription> commands;
@BeforeClass
public static void setUpCommands() {
WrapperMock.createInstance();
Settings.helpHeader = "Help";
commands = TestCommandsUtil.generateCommands();
}
@Before
public void setUpHelpProvider() {
permissionsManager = mock(PermissionsManager.class);
helpProvider = new HelpProvider(permissionsManager);
helpProvider = new HelpProvider(permissionsManager, HELP_HEADER);
sender = mock(CommandSender.class);
}
@ -70,7 +69,7 @@ public class HelpProviderTest {
// then
assertThat(lines, hasSize(5));
assertThat(lines.get(0), containsString(Settings.helpHeader + " HELP"));
assertThat(lines.get(0), containsString(HELP_HEADER + " HELP"));
assertThat(removeColors(lines.get(1)), containsString("Command: /authme login <password>"));
assertThat(removeColors(lines.get(2)), containsString("Short description: login cmd"));
assertThat(removeColors(lines.get(3)), equalTo("Detailed description:"));
@ -88,7 +87,7 @@ public class HelpProviderTest {
// then
assertThat(lines, hasSize(4));
assertThat(lines.get(0), containsString(Settings.helpHeader + " HELP"));
assertThat(lines.get(0), containsString(HELP_HEADER + " HELP"));
assertThat(removeColors(lines.get(1)), equalTo("Arguments:"));
assertThat(removeColors(lines.get(2)), containsString("password: 'password' argument description"));
assertThat(removeColors(lines.get(3)), containsString("confirmation: 'confirmation' argument description"));
@ -279,7 +278,7 @@ public class HelpProviderTest {
// then
assertThat(lines, hasSize(2));
assertThat(lines.get(0), containsString(Settings.helpHeader + " HELP"));
assertThat(lines.get(0), containsString(HELP_HEADER + " HELP"));
assertThat(removeColors(lines.get(1)), containsString("Command: /authme register <password> <confirmation>"));
}