diff --git a/README.md b/README.md
index 02e6a9d3..3f12a0cc 100644
--- a/README.md
+++ b/README.md
@@ -126,7 +126,7 @@ EUR: 
#####Sponsor
-GameHosting.it is leader in Italy in Game Server Provider. With its own DataCenter offers Anti-DDoS solutions at affordable prices. Game Server of Minecraft based on Multicraft are equipped with the latest technology in hardware.
+GameHosting.it is leader in Italy as Game Server Provider. With its own DataCenter offers Anti-DDoS solutions at affordable prices. Game Server of Minecraft based on Multicraft are equipped with the latest technology in hardware.
[](http://www.gamehosting.it)
#####Credits
diff --git a/pom.xml b/pom.xml
index e02a3bae..87feaae4 100644
--- a/pom.xml
+++ b/pom.xml
@@ -5,7 +5,7 @@
fr.xephi
authme
- 5.0-SNAPSHOT
+ 5.1-SNAPSHOT
AuthMeReloaded
Authentication plugin for CraftBukkit/Spigot!
@@ -13,6 +13,11 @@
http://dev.bukkit.org/bukkit-plugins/authme-reloaded/
+
+ AuthMe-Team
+ https://github.com/AuthMe-Team
+
+
scm:git:https://github.com/Xephi/AuthMeReloaded.git
scm:git:git@github.com:Xephi/AuthMeReloaded.git
@@ -56,6 +61,14 @@
*.yml
+
+ ./messages/
+ false
+ ${basedir}/src/main/resources/messages/
+
+ *.yml
+
+
@@ -74,13 +87,14 @@
- com.maxmind.geoip:*
- javax.mail:*
- com.sun.mail:*
- com.comphenix.attribute:*
- org.mcstats.*:*
- com.zaxxer:*
- org.slf4j:*
+ com.zaxxer:HikariCP
+ org.slf4j:slf4j-simple
+ org.slf4j:slf4j-api
+ com.google.code.gson:gson
+ com.maxmind.geoip:geoip-api
+ com.sun.mail:javax.mail
+ com.comphenix.attribute:AttributeStorage
+ org.mcstats.bukkit:metrics
@@ -116,12 +130,6 @@
https://ci.drtshock.net/plugin/repository/everything
-
-
- citizensapi-repo
- http://ci.citizensnpcs.co/plugin/repository/project/CitizensAPI/LastSuccessful/repository
-
-
minelink-thirdparty
@@ -170,18 +178,7 @@
-
-
- mysql
- mysql-connector-java
- 5.1.36
-
-
- org.slf4j
- slf4j-simple
- 1.7.12
- compile
-
+
com.zaxxer
HikariCP
@@ -189,17 +186,19 @@
compile
- org.slf4j
slf4j-api
-
-
org.slf4j
- slf4j-simple
+
+ org.slf4j
+ slf4j-simple
+ 1.7.12
+ compile
+
-
+
org.xerial
sqlite-jdbc
@@ -207,12 +206,32 @@
compile
-
+
+
+ com.google.code.gson
+ gson
+ 2.3.1
+ compile
+
+
+
+
+ javax.mail
+ javax.mail-api
+ 1.5.4
+ compile
+
com.sun.mail
javax.mail
1.5.4
compile
+
+
+ activation
+ javax.activation
+
+
@@ -283,24 +302,6 @@
-
-
- net.citizensnpcs
- citizensapi
- 2.0.16-SNAPSHOT
- provided
-
-
- org.bukkit
- bukkit
-
-
- org.bukkit
- craftbukkit
-
-
-
-
com.onarandombox.multiversecore
@@ -420,24 +421,6 @@
-
-
- com.trc202
- CombatTag
- 6.2.1-SNAPSHOT
- provided
-
-
- org.bukkit
- bukkit
-
-
- org.bukkit
- craftbukkit
-
-
-
-
de.luricos.bukkit
@@ -557,9 +540,7 @@
simplechestlock
-
- com.webkonsept.bukkit.simplechestlock
-
+ com.webkonsept.bukkit.simplechestlock
commandbook
diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java
index 08ab36a5..170e6d7d 100644
--- a/src/main/java/fr/xephi/authme/AuthMe.java
+++ b/src/main/java/fr/xephi/authme/AuthMe.java
@@ -1,23 +1,30 @@
package fr.xephi.authme;
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.lang.reflect.InvocationTargetException;
-import java.net.URL;
-import java.net.URLConnection;
-import java.util.Calendar;
-import java.util.Collection;
-import java.util.Date;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.logging.Logger;
-import java.util.zip.GZIPInputStream;
-
+import com.earth2me.essentials.Essentials;
+import com.maxmind.geoip.LookupService;
+import com.onarandombox.MultiverseCore.MultiverseCore;
+import fr.xephi.authme.api.API;
+import fr.xephi.authme.api.NewAPI;
+import fr.xephi.authme.cache.auth.PlayerAuth;
+import fr.xephi.authme.cache.auth.PlayerCache;
+import fr.xephi.authme.cache.backup.JsonCache;
+import fr.xephi.authme.cache.limbo.LimboCache;
+import fr.xephi.authme.cache.limbo.LimboPlayer;
+import fr.xephi.authme.commands.*;
+import fr.xephi.authme.converter.Converter;
+import fr.xephi.authme.converter.ForceFlatToSqlite;
+import fr.xephi.authme.datasource.*;
+import fr.xephi.authme.listener.*;
+import fr.xephi.authme.modules.ModuleManager;
+import fr.xephi.authme.plugin.manager.BungeeCordMessage;
+import fr.xephi.authme.plugin.manager.EssSpawn;
+import fr.xephi.authme.process.Management;
+import fr.xephi.authme.settings.Messages;
+import fr.xephi.authme.settings.OtherAccounts;
+import fr.xephi.authme.settings.Settings;
+import fr.xephi.authme.settings.Spawn;
+import net.milkbowl.vault.permission.Permission;
+import net.minelink.ctplus.CombatTagPlus;
import org.apache.logging.log4j.LogManager;
import org.bukkit.Bukkit;
import org.bukkit.Location;
@@ -31,139 +38,114 @@ import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import org.mcstats.Metrics;
-import com.earth2me.essentials.Essentials;
-import com.maxmind.geoip.LookupService;
-import com.onarandombox.MultiverseCore.MultiverseCore;
-
-import fr.xephi.authme.api.API;
-import fr.xephi.authme.api.NewAPI;
-import fr.xephi.authme.cache.auth.PlayerAuth;
-import fr.xephi.authme.cache.auth.PlayerCache;
-import fr.xephi.authme.cache.backup.FileCache;
-import fr.xephi.authme.cache.limbo.LimboCache;
-import fr.xephi.authme.cache.limbo.LimboPlayer;
-import fr.xephi.authme.commands.AdminCommand;
-import fr.xephi.authme.commands.CaptchaCommand;
-import fr.xephi.authme.commands.ChangePasswordCommand;
-import fr.xephi.authme.commands.ConverterCommand;
-import fr.xephi.authme.commands.EmailCommand;
-import fr.xephi.authme.commands.LoginCommand;
-import fr.xephi.authme.commands.LogoutCommand;
-import fr.xephi.authme.commands.RegisterCommand;
-import fr.xephi.authme.commands.UnregisterCommand;
-import fr.xephi.authme.converter.Converter;
-import fr.xephi.authme.converter.ForceFlatToSqlite;
-import fr.xephi.authme.datasource.CacheDataSource;
-import fr.xephi.authme.datasource.DataSource;
-import fr.xephi.authme.datasource.DatabaseCalls;
-import fr.xephi.authme.datasource.FlatFile;
-import fr.xephi.authme.datasource.MySQL;
-import fr.xephi.authme.datasource.SQLite;
-import fr.xephi.authme.listener.AuthMeBlockListener;
-import fr.xephi.authme.listener.AuthMeChestShopListener;
-import fr.xephi.authme.listener.AuthMeEntityListener;
-import fr.xephi.authme.listener.AuthMePlayerListener;
-import fr.xephi.authme.listener.AuthMeServerListener;
-import fr.xephi.authme.plugin.manager.BungeeCordMessage;
-import fr.xephi.authme.plugin.manager.CitizensCommunicator;
-import fr.xephi.authme.plugin.manager.CombatTagComunicator;
-import fr.xephi.authme.plugin.manager.EssSpawn;
-import fr.xephi.authme.process.Management;
-import fr.xephi.authme.settings.Messages;
-import fr.xephi.authme.settings.OtherAccounts;
-import fr.xephi.authme.settings.Settings;
-import fr.xephi.authme.settings.Spawn;
-import net.milkbowl.vault.permission.Permission;
+import java.io.*;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.Calendar;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.logging.Logger;
public class AuthMe extends JavaPlugin {
- public DataSource database = null;
+ private static AuthMe authme;
+
+ private final Server server = getServer();
+ private final Logger authmeLogger = Logger.getLogger("AuthMe");
+ public Management management;
+ public NewAPI api;
+ public SendMailSSL mail;
private Settings settings;
private Messages m;
+ public DataManager dataManager;
+ public DataSource database;
+ private JsonCache playerBackup;
public OtherAccounts otherAccounts;
- public static Server server;
- public static Logger authmeLogger = Logger.getLogger("AuthMe");
- public static AuthMe authme;
- public Permission permission;
- private Utils utils = Utils.getInstance();
- private FileCache playerBackup = new FileCache(this);
- public CitizensCommunicator citizens;
- public boolean isCitizensActive = false;
- public SendMailSSL mail = null;
- public boolean CombatTag = false;
- public double ChestShop = 0;
- public boolean BungeeCord = false;
- public Essentials ess;
- public NewAPI api;
- public Management management;
- public ConcurrentHashMap captcha = new ConcurrentHashMap();
- public ConcurrentHashMap cap = new ConcurrentHashMap();
- public ConcurrentHashMap realIp = new ConcurrentHashMap();
- public MultiverseCore multiverse = null;
public Location essentialsSpawn;
- public LookupService ls = null;
+ public LookupService lookupService;
+ public boolean legacyChestShop = false;
public boolean antibotMod = false;
public boolean delayedAntiBot = true;
- protected static String vgUrl = "http://monitor-1.verygames.net/api/?action=ipclean-real-ip&out=raw&ip=%IP%&port=%PORT%";
- public DataManager dataManager;
- public ConcurrentHashMap sessions = new ConcurrentHashMap();
+
+ // Hooks TODO: move into modules
+ public Permission permission;
+ public Essentials ess;
+ public MultiverseCore multiverse;
+ public CombatTagPlus combatTagPlus;
+
+ // Manager
+ private ModuleManager moduleManager;
+
+ // TODO: Create Manager for fields below
+ public ConcurrentHashMap sessions = new ConcurrentHashMap<>();
+ public ConcurrentHashMap captcha = new ConcurrentHashMap<>();
+ public ConcurrentHashMap cap = new ConcurrentHashMap<>();
+ public ConcurrentHashMap realIp = new ConcurrentHashMap<>();
+
+ public static AuthMe getInstance() {
+ return authme;
+ }
public Settings getSettings() {
return settings;
}
- public DataSource getAuthMeDatabase() {
- return database;
+ public void setMessages(Messages m) {
+ this.m = m;
}
- public void setAuthMeDatabase(DataSource database) {
- this.database = database;
+ public Messages getMessages() {
+ return m;
}
+
@Override
public void onEnable() {
+ // Set the Instance
authme = this;
+ // TODO: split the plugin in more modules
+ moduleManager = new ModuleManager(this);
+ int loaded = moduleManager.loadModules();
+
+ // TODO: remove vault as hard dependency
+ PluginManager pm = server.getPluginManager();
+
+ // Setup the Logger
authmeLogger.setParent(this.getLogger());
+ // Load settings and custom configurations
+ // TODO: new configuration style (more files)
try {
settings = new Settings(this);
+ settings.reload();
} catch (Exception e) {
+ ConsoleLogger.writeStackTrace(e);
ConsoleLogger.showError("Can't load the configuration file... Something went wrong, to avoid security issues the server will shutdown!");
- this.getServer().shutdown();
+ server.shutdown();
return;
}
+ // Setup otherAccounts file
+ otherAccounts = OtherAccounts.getInstance();
+
+ // Setup messages
+ m = Messages.getInstance();
+
+ // Start the metrics service
+ // TODO: add a setting to disable metrics
try {
Metrics metrics = new Metrics(this);
metrics.start();
ConsoleLogger.info("Metrics started successfully!");
- } catch (IOException e) {
+ } catch (Exception e) {
// Failed to submit the metrics data
+ ConsoleLogger.writeStackTrace(e);
ConsoleLogger.showError("Can't start Metrics! The plugin will work anyway...");
}
- citizens = new CitizensCommunicator(this);
-
- if (Settings.enableAntiBot) {
- Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
-
- @Override
- public void run() {
- delayedAntiBot = false;
- }
- }, 2400);
- }
-
- m = Messages.getInstance();
-
- otherAccounts = OtherAccounts.getInstance();
-
- server = getServer();
-
- // Find Permissions
- checkVault();
-
// Set Console Filter
if (Settings.removePassword) {
ConsoleFilter filter = new ConsoleFilter();
@@ -175,22 +157,35 @@ public class AuthMe extends JavaPlugin {
try {
Class.forName("org.apache.logging.log4j.core.Filter");
setLog4JFilter();
- } catch (ClassNotFoundException e) {
- ConsoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support will be disabled");
- } catch (NoClassDefFoundError e) {
+ } catch (ClassNotFoundException | NoClassDefFoundError e) {
ConsoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support will be disabled");
}
}
- // Load MailApi
- if (!Settings.getmailAccount.isEmpty() && !Settings.getmailPassword.isEmpty())
+ // AntiBot delay
+ if (Settings.enableAntiBot) {
+ Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
+
+ @Override
+ public void run() {
+ delayedAntiBot = false;
+ }
+ }, 2400);
+ }
+
+ // Download GeoIp.dat file
+ Utils.checkGeoIP();
+
+ // Load MailApi if needed
+ if (!Settings.getmailAccount.isEmpty() && !Settings.getmailPassword.isEmpty()) {
mail = new SendMailSSL(this);
+ }
- // Check Citizens Version
- checkCitizens();
+ // Find Permissions
+ checkVault();
- // Check Combat Tag Version
- checkCombatTag();
+ // Check Combat Tag Plus Version
+ checkCombatTagPlus();
// Check Multiverse
checkMultiverse();
@@ -204,74 +199,59 @@ public class AuthMe extends JavaPlugin {
// Check Essentials
checkEssentials();
- /*
- * Back style on start if avalaible
- */
+ // Do backup on start if enabled
if (Settings.isBackupActivated && Settings.isBackupOnStart) {
- Boolean Backup = new PerformBackup(this).DoBackup();
- if (Backup)
+ // Do backup and check return value!
+ if (new PerformBackup(this).doBackup()) {
ConsoleLogger.info("Backup performed correctly");
- else ConsoleLogger.showError("Error while performing the backup!");
+ } else {
+ ConsoleLogger.showError("Error while performing the backup!");
+ }
}
- setupDatabase();
+ // Connect to the database and setup tables
+ try {
+ setupDatabase();
+ } catch (Exception e) {
+ ConsoleLogger.writeStackTrace(e);
+ ConsoleLogger.showError(e.getMessage());
+ ConsoleLogger.showError("Fatal error occurred during database connection! Authme initialization ABORTED!");
+ stopOrUnload();
+ return;
+ }
+ // Setup the inventory backup
+ playerBackup = new JsonCache(this);
+
+ // Set the DataManager
dataManager = new DataManager(this);
- // Setup API
+ // Setup the new API
api = new NewAPI(this);
+ // Setup the old deprecated API
new API(this);
// Setup Management
management = new Management(this);
- PluginManager pm = getServer().getPluginManager();
+ // Bungeecord hook
if (Settings.bungee) {
Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new BungeeCordMessage(this));
}
- pm.registerEvents(new AuthMePlayerListener(this), this);
- pm.registerEvents(new AuthMeBlockListener(this), this);
- pm.registerEvents(new AuthMeEntityListener(this), this);
- pm.registerEvents(new AuthMeServerListener(this), this);
- if (ChestShop != 0) {
+ // Legacy chestshop hook
+ if (legacyChestShop) {
pm.registerEvents(new AuthMeChestShopListener(this), this);
ConsoleLogger.info("Hooked successfully with ChestShop!");
}
- this.getCommand("authme").setExecutor(new AdminCommand(this));
- this.getCommand("register").setExecutor(new RegisterCommand(this));
- this.getCommand("login").setExecutor(new LoginCommand(this));
- this.getCommand("changepassword").setExecutor(new ChangePasswordCommand(this));
- this.getCommand("logout").setExecutor(new LogoutCommand(this));
- this.getCommand("unregister").setExecutor(new UnregisterCommand(this));
- this.getCommand("email").setExecutor(new EmailCommand(this));
- this.getCommand("captcha").setExecutor(new CaptchaCommand(this));
- this.getCommand("converter").setExecutor(new ConverterCommand(this));
-
- if (!Settings.isForceSingleSessionEnabled) {
- ConsoleLogger.showError("WARNING!!! By disabling ForceSingleSession, your server protection is inadequate!");
- }
-
- if (Settings.getSessionTimeout == 0 && Settings.isSessionsEnabled) {
- ConsoleLogger.showError("WARNING!!! You set session timeout to 0, this may cause security issues!");
- }
-
+ // Reload support hook
if (Settings.reloadSupport) {
- try {
- int playersOnline = 0;
- try {
- if (Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).getReturnType() == Collection.class)
- playersOnline = ((Collection>) Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).invoke(null, new Object[0])).size();
- else playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).invoke(null, new Object[0])).length;
- } catch (Exception ex) {
- }
+ if (database != null) {
+ int playersOnline = Utils.getOnlinePlayers().size();
if (playersOnline < 1) {
- try {
- database.purgeLogged();
- } catch (NullPointerException npe) {
- }
+ database.purgeLogged();
} else {
for (PlayerAuth auth : database.getLoggedPlayers()) {
if (auth == null)
@@ -281,25 +261,142 @@ public class AuthMe extends JavaPlugin {
PlayerCache.getInstance().addPlayer(auth);
}
}
- } catch (Exception ex) {
}
}
- autoPurge();
+ // Register events
+ pm.registerEvents(new AuthMePlayerListener(this), this);
+ pm.registerEvents(new AuthMeBlockListener(this), this);
+ pm.registerEvents(new AuthMeEntityListener(this), this);
+ pm.registerEvents(new AuthMeServerListener(this), this);
- // Download GeoIp.dat file
- downloadGeoIp();
+ // Register commands
+ getCommand("authme").setExecutor(new AdminCommand(this));
+ getCommand("register").setExecutor(new RegisterCommand(this));
+ getCommand("login").setExecutor(new LoginCommand(this));
+ getCommand("changepassword").setExecutor(new ChangePasswordCommand(this));
+ getCommand("logout").setExecutor(new LogoutCommand(this));
+ getCommand("unregister").setExecutor(new UnregisterCommand(this));
+ getCommand("email").setExecutor(new EmailCommand(this));
+ getCommand("captcha").setExecutor(new CaptchaCommand(this));
+ getCommand("converter").setExecutor(new ConverterCommand(this));
+
+ // Purge on start if enabled
+ autoPurge();
// Start Email recall task if needed
recallEmail();
- // Sponsor message
- ConsoleLogger.info("AuthMe hooks perfectly with the VERYGAMES server hosting!");
- ConsoleLogger.info("AuthMe builds are available on jenkins, thanks to our sponsor GameHosting.it - leader in Italy in Game Server Provider");
+ // Configuration Security Warnings
+ if (!Settings.isForceSingleSessionEnabled) {
+ ConsoleLogger.showError("WARNING!!! By disabling ForceSingleSession, your server protection is inadequate!");
+ }
+ if (Settings.getSessionTimeout == 0 && Settings.isSessionsEnabled) {
+ ConsoleLogger.showError("WARNING!!! You set session timeout to 0, this may cause security issues!");
+ }
+ // Sponsor messages
+ ConsoleLogger.info("AuthMe hooks perfectly with the VERYGAMES server hosting!");
+ ConsoleLogger.info("Development builds are available on our jenkins, thanks to f14stelt.");
+ ConsoleLogger.info("Do you want a good gameserver? Look at our sponsor GameHosting.it leader in Italy as Game Server Provider!");
+
+ // Successful message
ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " correctly enabled!");
}
+ @Override
+ public void onDisable() {
+ // Save player data
+ Collection extends Player> players = Utils.getOnlinePlayers();
+ if (players != null) {
+ for (Player player : players) {
+ this.savePlayer(player);
+ }
+ }
+
+ // Close the database
+ if (database != null) {
+ database.close();
+ }
+
+ // Do backup on stop if enabled
+ if (Settings.isBackupActivated && Settings.isBackupOnStop) {
+ boolean Backup = new PerformBackup(this).doBackup();
+ if (Backup)
+ ConsoleLogger.info("Backup performed correctly.");
+ else ConsoleLogger.showError("Error while performing the backup!");
+ }
+
+ // Unload modules
+ moduleManager.unloadModules();
+
+ // Disabled correctly
+ ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " disabled!");
+ }
+
+ // Stop/unload the server/plugin as defined in the configuration
+ public void stopOrUnload() {
+ if (Settings.isStopEnabled) {
+ ConsoleLogger.showError("THE SERVER IS GOING TO SHUTDOWN AS DEFINED IN THE CONFIGURATION!");
+ server.shutdown();
+ } else {
+ server.getPluginManager().disablePlugin(AuthMe.getInstance());
+ }
+ }
+
+ // Show the exception message and stop/unload the server/plugin as defined in the configuration
+ public void stopOrUnload(Exception e) {
+ ConsoleLogger.showError(e.getMessage());
+ stopOrUnload();
+ }
+
+ // Initialize and setup the database
+ public void setupDatabase() throws Exception {
+ // Backend MYSQL - FILE - SQLITE - SQLITEHIKARI
+ boolean isSQLite = false;
+ switch (Settings.getDataSource) {
+ case FILE:
+ database = new FlatFile();
+ break;
+ case MYSQL:
+ database = new MySQL();
+ break;
+ case SQLITE:
+ database = new SQLite();
+ isSQLite = true;
+ break;
+ case SQLITEHIKARI:
+ database = new SQLite_HIKARI();
+ isSQLite = true;
+ break;
+ }
+
+ if (isSQLite) {
+ server.getScheduler().runTaskAsynchronously(this, new Runnable() {
+ @Override
+ public void run() {
+ int accounts = database.getAccountsRegistered();
+ if (accounts >= 4000)
+ ConsoleLogger.showError("YOU'RE USING THE SQLITE DATABASE WITH " + accounts + "+ ACCOUNTS, FOR BETTER PERFORMANCES, PLEASE UPGRADE TO MYSQL!!");
+ }
+ });
+ }
+
+ if (Settings.isCachingEnabled) {
+ database = new CacheDataSource(this, database);
+ }
+
+ database = new DatabaseCalls(database);
+
+ if (Settings.getDataSource == DataSource.DataSourceType.FILE) {
+ Converter converter = new ForceFlatToSqlite(database, this);
+ server.getScheduler().runTaskAsynchronously(this, converter);
+ ConsoleLogger.showError("FlatFile backend has been detected and is now deprecated, next time server starts up, it will be changed to SQLite... Conversion will be started Asynchronously, it will not drop down your performance !");
+ ConsoleLogger.showError("If you want to keep FlatFile, set file again into config at backend, but this message and this change will appear again at the next restart");
+ }
+ }
+
+ // Set the console filter to remove the passwords
private void setLog4JFilter() {
Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
@@ -311,9 +408,10 @@ public class AuthMe extends JavaPlugin {
});
}
+ // Check the presence of the Vault plugin and a permissions provider
public void checkVault() {
- if (this.getServer().getPluginManager().getPlugin("Vault") != null && this.getServer().getPluginManager().getPlugin("Vault").isEnabled()) {
- RegisteredServiceProvider permissionProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class);
+ if (server.getPluginManager().isPluginEnabled("Vault")) {
+ RegisteredServiceProvider permissionProvider = server.getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class);
if (permissionProvider != null) {
permission = permissionProvider.getProvider();
ConsoleLogger.info("Vault detected, hooking with the " + permission.getName() + " permissions system...");
@@ -325,74 +423,60 @@ public class AuthMe extends JavaPlugin {
}
}
+ // Check the version of the ChestShop plugin
public void checkChestShop() {
- if (!Settings.chestshop) {
- this.ChestShop = 0;
- return;
- }
- if (this.getServer().getPluginManager().getPlugin("ChestShop") != null && this.getServer().getPluginManager().getPlugin("ChestShop").isEnabled()) {
+ if (Settings.legacyChestShop && server.getPluginManager().isPluginEnabled("ChestShop")) {
+ String rawver = com.Acrobot.ChestShop.ChestShop.getVersion();
+ double version;
try {
- String ver = com.Acrobot.ChestShop.ChestShop.getVersion();
+ version = Double.valueOf(rawver.split(" ")[0]);
+ } catch (NumberFormatException nfe) {
try {
- double version = Double.valueOf(ver.split(" ")[0]);
- if (version >= 3.50) {
- this.ChestShop = version;
- } else {
- ConsoleLogger.showError("Please Update your ChestShop version! Bugs may occur!");
- }
- } catch (NumberFormatException nfe) {
- try {
- double version = Double.valueOf(ver.split("t")[0]);
- if (version >= 3.50) {
- this.ChestShop = version;
- } else {
- ConsoleLogger.showError("Please Update your ChestShop version! Bugs may occur!");
- }
- } catch (NumberFormatException nfee) {
- }
+ version = Double.valueOf(rawver.split("t")[0]);
+ } catch (NumberFormatException nfee) {
+ legacyChestShop = false;
+ return;
}
- } catch (Exception e) {
}
+ if (version >= 3.813) {
+ return;
+ }
+ if (version < 3.50) {
+ ConsoleLogger.showError("Please Update your ChestShop version! Bugs may occur!");
+ return;
+ }
+ legacyChestShop = true;
} else {
- this.ChestShop = 0;
+ legacyChestShop = false;
}
}
+ // Check PerWorldInventories version
public void checkPerWorldInventories() {
- if (this.getServer().getPluginManager().getPlugin("PerWorldInventories") != null && this.getServer().getPluginManager().getPlugin("PerWorldInventories").isEnabled()) {
+ if (server.getPluginManager().isPluginEnabled("PerWorldInventories")) {
+ double version = 0;
+ String ver = server.getPluginManager().getPlugin("PerWorldInventories").getDescription().getVersion();
try {
- String ver = Bukkit.getServer().getPluginManager().getPlugin("PerWorldInventories").getDescription().getVersion();
+ version = Double.valueOf(ver.split(" ")[0]);
+ } catch (NumberFormatException nfe) {
try {
- double version = Double.valueOf(ver.split(" ")[0]);
- if (version < 1.57)
- ConsoleLogger.showError("Please Update your PerWorldInventories version! INVENTORY WIPE may occur!");
- } catch (NumberFormatException nfe) {
- try {
- double version = Double.valueOf(ver.split("t")[0]);
- if (version < 1.57)
- ConsoleLogger.showError("Please Update your PerWorldInventories version! INVENTORY WIPE may occur!");
- } catch (NumberFormatException nfee) {
- }
+ version = Double.valueOf(ver.split("t")[0]);
+ } catch (NumberFormatException ignore) {
}
- } catch (Exception e) {
+ }
+ if (version < 1.57) {
+ ConsoleLogger.showError("Please Update your PerWorldInventories version! INVENTORY WIPE may occur!");
}
}
}
+ // Get the Multiverse plugin
public void checkMultiverse() {
- if (!Settings.multiverse) {
- multiverse = null;
- return;
- }
- if (this.getServer().getPluginManager().getPlugin("Multiverse-Core") != null && this.getServer().getPluginManager().getPlugin("Multiverse-Core").isEnabled()) {
+ if (Settings.multiverse && server.getPluginManager().isPluginEnabled("Multiverse-Core")) {
try {
- multiverse = (MultiverseCore) this.getServer().getPluginManager().getPlugin("Multiverse-Core");
+ multiverse = (MultiverseCore) server.getPluginManager().getPlugin("Multiverse-Core");
ConsoleLogger.info("Hooked correctly with Multiverse-Core");
- } catch (NullPointerException npe) {
- multiverse = null;
- } catch (ClassCastException cce) {
- multiverse = null;
- } catch (NoClassDefFoundError ncdfe) {
+ } catch (Exception | NoClassDefFoundError ignored) {
multiverse = null;
}
} else {
@@ -400,22 +484,19 @@ public class AuthMe extends JavaPlugin {
}
}
+ // Get the Essentials plugin
public void checkEssentials() {
- if (this.getServer().getPluginManager().getPlugin("Essentials") != null && this.getServer().getPluginManager().getPlugin("Essentials").isEnabled()) {
+ if (server.getPluginManager().isPluginEnabled("Essentials")) {
try {
- ess = (Essentials) this.getServer().getPluginManager().getPlugin("Essentials");
+ ess = (Essentials) server.getPluginManager().getPlugin("Essentials");
ConsoleLogger.info("Hooked correctly with Essentials");
- } catch (NullPointerException npe) {
- ess = null;
- } catch (ClassCastException cce) {
- ess = null;
- } catch (NoClassDefFoundError ncdfe) {
+ } catch (Exception | NoClassDefFoundError ingnored) {
ess = null;
}
} else {
ess = null;
}
- if (this.getServer().getPluginManager().getPlugin("EssentialsSpawn") != null && this.getServer().getPluginManager().getPlugin("EssentialsSpawn").isEnabled()) {
+ if (server.getPluginManager().isPluginEnabled("EssentialsSpawn")) {
try {
essentialsSpawn = new EssSpawn().getLocation();
ConsoleLogger.info("Hooked correctly with EssentialsSpawn");
@@ -428,106 +509,72 @@ public class AuthMe extends JavaPlugin {
}
}
- public void checkCombatTag() {
- if (this.getServer().getPluginManager().getPlugin("CombatTag") != null && this.getServer().getPluginManager().getPlugin("CombatTag").isEnabled()) {
- this.CombatTag = true;
- } else {
- this.CombatTag = false;
- }
- }
-
- public void checkCitizens() {
- if (this.getServer().getPluginManager().getPlugin("Citizens") != null && this.getServer().getPluginManager().getPlugin("Citizens").isEnabled())
- this.isCitizensActive = true;
- else this.isCitizensActive = false;
- }
-
- @Override
- public void onDisable() {
- int playersOnline = 0;
- try {
- if (Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).getReturnType() == Collection.class)
- playersOnline = ((Collection>) Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).invoke(null, new Object[0])).size();
- else playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).invoke(null, new Object[0])).length;
- } catch (NoSuchMethodException ex) {
- } // can never happen
- catch (InvocationTargetException ex) {
- } // can also never happen
- catch (IllegalAccessException ex) {
- } // can still never happen
- if (playersOnline != 0)
- for (Player player : Bukkit.getOnlinePlayers()) {
- this.savePlayer(player);
- }
-
- if (database != null) {
+ // Check the presence of CombatTag
+ public void checkCombatTagPlus() {
+ if (server.getPluginManager().isPluginEnabled("CombatTagPlus")) {
try {
- database.close();
- } catch (Exception e) {
+ combatTagPlus = (CombatTagPlus) server.getPluginManager().getPlugin("CombatTagPlus");
+ ConsoleLogger.info("Hooked correctly with CombatTagPlus");
+ } catch (Exception | NoClassDefFoundError ingnored) {
+ combatTagPlus = null;
}
+ } else {
+ combatTagPlus = null;
}
-
- if (Settings.isBackupActivated && Settings.isBackupOnStop) {
- Boolean Backup = new PerformBackup(this).DoBackup();
- if (Backup)
- ConsoleLogger.info("Backup performed correctly.");
- else ConsoleLogger.showError("Error while performing the backup!");
- }
- ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " disabled!");
}
- public static AuthMe getInstance() {
- return authme;
+ // Check if a player/command sender have a permission
+ public boolean authmePermissible(Player player, String perm) {
+ if (player.hasPermission(perm)) {
+ return true;
+ } else if (permission != null) {
+ return permission.playerHas(player, perm);
+ }
+ return false;
}
+ public boolean authmePermissible(CommandSender sender, String perm) {
+ if (sender.hasPermission(perm)) {
+ return true;
+ } else if (permission != null) {
+ return permission.has(sender, perm);
+ }
+ return false;
+ }
+
+ // Save Player Data
public void savePlayer(Player player) {
- try {
- if ((citizens.isNPC(player)) || (Utils.getInstance().isUnrestricted(player)) || (CombatTagComunicator.isNPC(player))) {
- return;
- }
- } catch (Exception e) {
+ if ((Utils.isNPC(player)) || (Utils.isUnrestricted(player))) {
+ return;
}
- try {
- String name = player.getName().toLowerCase();
- if (PlayerCache.getInstance().isAuthenticated(name) && !player.isDead() && Settings.isSaveQuitLocationEnabled) {
- final PlayerAuth auth = new PlayerAuth(player.getName().toLowerCase(), player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ(), player.getWorld().getName(), player.getName());
- database.updateQuitLoc(auth);
- }
- if (LimboCache.getInstance().hasLimboPlayer(name)) {
- LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
- if (Settings.protectInventoryBeforeLogInEnabled.booleanValue()) {
- player.getInventory().setArmorContents(limbo.getArmour());
- player.getInventory().setContents(limbo.getInventory());
- }
- if (!Settings.noTeleport)
- player.teleport(limbo.getLoc());
- this.utils.addNormal(player, limbo.getGroup());
- player.setOp(limbo.getOperator());
- limbo.getTimeoutTaskId().cancel();
- LimboCache.getInstance().deleteLimboPlayer(name);
- if (this.playerBackup.doesCacheExist(player)) {
- this.playerBackup.removeCache(player);
- }
- }
- PlayerCache.getInstance().removePlayer(name);
- database.setUnlogged(name);
- player.saveData();
- } catch (Exception ex) {
+ String name = player.getName().toLowerCase();
+ if (PlayerCache.getInstance().isAuthenticated(name) && !player.isDead() && Settings.isSaveQuitLocationEnabled) {
+ final PlayerAuth auth = new PlayerAuth(player.getName().toLowerCase(), player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ(), player.getWorld().getName(), player.getName());
+ database.updateQuitLoc(auth);
}
+ if (LimboCache.getInstance().hasLimboPlayer(name)) {
+ LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
+ if (Settings.protectInventoryBeforeLogInEnabled) {
+ player.getInventory().setArmorContents(limbo.getArmour());
+ player.getInventory().setContents(limbo.getInventory());
+ }
+ if (!Settings.noTeleport) {
+ player.teleport(limbo.getLoc());
+ }
+ Utils.addNormal(player, limbo.getGroup());
+ player.setOp(limbo.getOperator());
+ limbo.getTimeoutTaskId().cancel();
+ LimboCache.getInstance().deleteLimboPlayer(name);
+ if (this.playerBackup.doesCacheExist(player)) {
+ this.playerBackup.removeCache(player);
+ }
+ }
+ PlayerCache.getInstance().removePlayer(name);
+ database.setUnlogged(name);
+ player.saveData();
}
- public CitizensCommunicator getCitizensCommunicator() {
- return citizens;
- }
-
- public void setMessages(Messages m) {
- this.m = m;
- }
-
- public Messages getMessages() {
- return m;
- }
-
+ // Select the player to kick when a vip player join the server when full
public Player generateKickPlayer(Collection extends Player> collection) {
Player player = null;
for (Player p : collection) {
@@ -539,24 +586,7 @@ public class AuthMe extends JavaPlugin {
return player;
}
- public boolean authmePermissible(Player player, String perm) {
- if (player.hasPermission(perm))
- return true;
- else if (permission != null) {
- return permission.playerHas(player, perm);
- }
- return false;
- }
-
- public boolean authmePermissible(CommandSender sender, String perm) {
- if (sender.hasPermission(perm))
- return true;
- else if (permission != null) {
- return permission.has(sender, perm);
- }
- return false;
- }
-
+ // Purge inactive players from the database, as defined in the configuration
private void autoPurge() {
if (!Settings.usePurge) {
return;
@@ -565,27 +595,26 @@ public class AuthMe extends JavaPlugin {
calendar.add(Calendar.DATE, -(Settings.purgeDelay));
long until = calendar.getTimeInMillis();
List cleared = database.autoPurgeDatabase(until);
- if (cleared == null)
+ if (cleared == null) {
return;
- if (cleared.isEmpty())
+ }
+ if (cleared.isEmpty()) {
return;
+ }
ConsoleLogger.info("AutoPurging the Database: " + cleared.size() + " accounts removed!");
if (Settings.purgeEssentialsFile && this.ess != null)
- dataManager.purgeEssentials(cleared); // name to UUID convertion
- // needed with latest versions
+ dataManager.purgeEssentials(cleared); // name to UUID convertion needed with latest versions
if (Settings.purgePlayerDat)
- dataManager.purgeDat(cleared); // name to UUID convertion needed
- // with latest versions of MC
+ dataManager.purgeDat(cleared); // name to UUID convertion needed with latest versions of MC
if (Settings.purgeLimitedCreative)
dataManager.purgeLimitedCreative(cleared);
if (Settings.purgeAntiXray)
- dataManager.purgeAntiXray(cleared); // IDK if it uses UUID or
- // names... (Actually it purges
- // only names!)
+ dataManager.purgeAntiXray(cleared); // IDK if it uses UUID or names... (Actually it purges only names!)
if (Settings.purgePermissions)
dataManager.purgePermissions(cleared, permission);
}
+ // Return the spawn location of a player
public Location getSpawnLocation(Player player) {
World world = player.getWorld();
String[] spawnPriority = Settings.spawnPriority.split(",");
@@ -601,90 +630,46 @@ public class AuthMe extends JavaPlugin {
if (s.equalsIgnoreCase("authme") && getAuthMeSpawn(player) != null)
spawnLoc = getAuthMeSpawn(player);
}
- if (spawnLoc == null)
+ if (spawnLoc == null) {
spawnLoc = world.getSpawnLocation();
+ }
return spawnLoc;
}
+ // Return the default spawnpoint of a world
private Location getDefaultSpawn(World world) {
return world.getSpawnLocation();
}
+ // Return the multiverse spawnpoint of a world
private Location getMultiverseSpawn(World world) {
if (multiverse != null && Settings.multiverse) {
try {
return multiverse.getMVWorldManager().getMVWorld(world).getSpawnLocation();
- } catch (NullPointerException npe) {
- } catch (ClassCastException cce) {
- } catch (NoClassDefFoundError ncdfe) {
- }
- }
- return null;
- }
-
- private Location getEssentialsSpawn() {
- if (essentialsSpawn != null)
- return essentialsSpawn;
- return null;
- }
-
- private Location getAuthMeSpawn(Player player) {
- if ((!database.isAuthAvailable(player.getName().toLowerCase()) || !player.hasPlayedBefore()) && (Spawn.getInstance().getFirstSpawn() != null))
- return Spawn.getInstance().getFirstSpawn();
- if (Spawn.getInstance().getSpawn() != null)
- return Spawn.getInstance().getSpawn();
- return player.getWorld().getSpawnLocation();
- }
-
- public void downloadGeoIp() {
- ConsoleLogger.info("[LICENSE] This product uses data from the GeoLite API created by MaxMind, available at http://www.maxmind.com");
- File file = new File(getDataFolder(), "GeoIP.dat");
- if (!file.exists()) {
- try {
- String url = "http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz";
- URL downloadUrl = new URL(url);
- URLConnection conn = downloadUrl.openConnection();
- conn.setConnectTimeout(10000);
- conn.connect();
- InputStream input = conn.getInputStream();
- if (url.endsWith(".gz"))
- input = new GZIPInputStream(input);
- OutputStream output = new FileOutputStream(file);
- byte[] buffer = new byte[2048];
- int length = input.read(buffer);
- while (length >= 0) {
- output.write(buffer, 0, length);
- length = input.read(buffer);
- }
- output.close();
- input.close();
} catch (Exception e) {
+ e.printStackTrace();
}
}
+ return null;
}
- public String getCountryCode(String ip) {
- try {
- if (ls == null)
- ls = new LookupService(new File(getDataFolder(), "GeoIP.dat"));
- String code = ls.getCountry(ip).getCode();
- if (code != null && !code.isEmpty())
- return code;
- } catch (Exception e) {
+ // Return the essentials spawnpoint
+ private Location getEssentialsSpawn() {
+ if (essentialsSpawn != null) {
+ return essentialsSpawn;
}
return null;
}
- public String getCountryName(String ip) {
- try {
- if (ls == null)
- ls = new LookupService(new File(getDataFolder(), "GeoIP.dat"));
- String code = ls.getCountry(ip).getName();
- if (code != null && !code.isEmpty())
- return code;
- } catch (Exception e) {
+ // Return the authme soawnpoint
+ private Location getAuthMeSpawn(Player player) {
+ if ((!database.isAuthAvailable(player.getName().toLowerCase()) || !player.hasPlayedBefore()) && (Spawn.getInstance().getFirstSpawn() != null)) {
+ return Spawn.getInstance().getFirstSpawn();
}
- return null;
+ if (Spawn.getInstance().getSpawn() != null) {
+ return Spawn.getInstance().getSpawn();
+ }
+ return player.getWorld().getSpawnLocation();
}
public void switchAntiBotMod(boolean mode) {
@@ -699,7 +684,7 @@ public class AuthMe extends JavaPlugin {
@Override
public void run() {
- for (Player player : Bukkit.getOnlinePlayers()) {
+ for (Player player : Utils.getOnlinePlayers()) {
if (player.isOnline()) {
String name = player.getName().toLowerCase();
if (database.isAuthAvailable(name))
@@ -715,30 +700,17 @@ public class AuthMe extends JavaPlugin {
}
public String replaceAllInfos(String message, Player player) {
- int playersOnline = 0;
- try {
- if (Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).getReturnType() == Collection.class)
- playersOnline = ((Collection>) Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).invoke(null, new Object[0])).size();
- else playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).invoke(null, new Object[0])).length;
- } catch (NoSuchMethodException ex) {
- } // can never happen
- catch (InvocationTargetException ex) {
- } // can also never happen
- catch (IllegalAccessException ex) {
- } // can still never happen
- try {
- message = message.replace("&", "\u00a7");
- message = message.replace("{PLAYER}", player.getName());
- message = message.replace("{ONLINE}", "" + playersOnline);
- message = message.replace("{MAXPLAYERS}", "" + this.getServer().getMaxPlayers());
- message = message.replace("{IP}", getIP(player));
- message = message.replace("{LOGINS}", "" + PlayerCache.getInstance().getLogged());
- message = message.replace("{WORLD}", player.getWorld().getName());
- message = message.replace("{SERVER}", this.getServer().getServerName());
- message = message.replace("{VERSION}", this.getServer().getBukkitVersion());
- message = message.replace("{COUNTRY}", this.getCountryName(getIP(player)));
- } catch (Exception e) {
- }
+ int playersOnline = Utils.getOnlinePlayers().size();
+ message = message.replace("&", "\u00a7");
+ message = message.replace("{PLAYER}", player.getName());
+ message = message.replace("{ONLINE}", "" + playersOnline);
+ message = message.replace("{MAXPLAYERS}", "" + server.getMaxPlayers());
+ message = message.replace("{IP}", getIP(player));
+ message = message.replace("{LOGINS}", "" + PlayerCache.getInstance().getLogged());
+ message = message.replace("{WORLD}", player.getWorld().getName());
+ message = message.replace("{SERVER}", server.getServerName());
+ message = message.replace("{VERSION}", server.getBukkitVersion());
+ message = message.replace("{COUNTRY}", Utils.getCountryName(getIP(player)));
return message;
}
@@ -757,36 +729,31 @@ public class AuthMe extends JavaPlugin {
public boolean isLoggedIp(String name, String ip) {
int count = 0;
- for (Player player : this.getServer().getOnlinePlayers()) {
+ for (Player player : Utils.getOnlinePlayers()) {
if (ip.equalsIgnoreCase(getIP(player)) && database.isLogged(player.getName().toLowerCase()) && !player.getName().equalsIgnoreCase(name))
count++;
}
- if (count >= Settings.getMaxLoginPerIp)
- return true;
- return false;
+ return count >= Settings.getMaxLoginPerIp;
}
public boolean hasJoinedIp(String name, String ip) {
int count = 0;
- for (Player player : this.getServer().getOnlinePlayers()) {
+ for (Player player : Utils.getOnlinePlayers()) {
if (ip.equalsIgnoreCase(getIP(player)) && !player.getName().equalsIgnoreCase(name))
count++;
}
- if (count >= Settings.getMaxJoinPerIp)
- return true;
- return false;
+ return count >= Settings.getMaxJoinPerIp;
}
/**
* Get Player real IP through VeryGames method
- *
- * @param Player
- * player
+ *
+ * @param player player
*/
@Deprecated
public String getVeryGamesIP(Player player) {
String realIP = player.getAddress().getAddress().getHostAddress();
- String sUrl = vgUrl;
+ String sUrl = "http://monitor-1.verygames.net/api/?action=ipclean-real-ip&out=raw&ip=%IP%&port=%PORT%";
sUrl = sUrl.replace("%IP%", player.getAddress().getAddress().getHostAddress()).replace("%PORT%", "" + player.getAddress().getPort());
try {
URL url = new URL(sUrl);
@@ -796,45 +763,10 @@ public class AuthMe extends JavaPlugin {
if (inputLine != null && !inputLine.isEmpty() && !inputLine.equalsIgnoreCase("error") && !inputLine.contains("error")) {
realIP = inputLine;
}
- } catch (Exception e) {
+ } catch (Exception ignored) {
}
return realIP;
}
- public void setupDatabase() {
- /*
- * Backend MYSQL - FILE - SQLITE
- */
- switch (Settings.getDataSource) {
- case FILE:
- database = new FlatFile();
- break;
- case MYSQL:
- database = new MySQL();
- break;
- case SQLITE:
- database = new SQLite();
- final int b = database.getAccountsRegistered();
- if (b >= 4000)
- ConsoleLogger.showError("YOU'RE USING THE SQLITE DATABASE WITH " + b + "+ ACCOUNTS, FOR BETTER PERFORMANCES, PLEASE UPGRADE TO MYSQL!!");
- break;
- }
- if (Settings.isCachingEnabled) {
- database = new CacheDataSource(this, database);
- }
-
- database = new DatabaseCalls(database);
-
- if (Settings.getDataSource == DataSource.DataSourceType.FILE) {
- Converter converter = new ForceFlatToSqlite(database, this);
- try {
- Thread t = new Thread(converter);
- t.start();
- } catch (Exception e) {
- }
- ConsoleLogger.showError("FlatFile backend has been detected and is now deprecated, next time server starts up, it will be changed to SQLite... Conversion will be started Asynchronously, it will not drop down your performance !");
- ConsoleLogger.showError("If you want to keep FlatFile, set file again into config at backend, but this message and this change will appear again at the next restart");
- }
- }
}
diff --git a/src/main/java/fr/xephi/authme/ConsoleLogger.java b/src/main/java/fr/xephi/authme/ConsoleLogger.java
index 3a73ab5c..befffc68 100644
--- a/src/main/java/fr/xephi/authme/ConsoleLogger.java
+++ b/src/main/java/fr/xephi/authme/ConsoleLogger.java
@@ -1,63 +1,62 @@
package fr.xephi.authme;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.text.DateFormat;
-import java.util.Calendar;
-import java.util.logging.Logger;
-
-import org.bukkit.Bukkit;
-
+import com.google.common.base.Throwables;
+import fr.xephi.authme.api.NewAPI;
import fr.xephi.authme.settings.Settings;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.StandardOpenOption;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.logging.Logger;
+
public class ConsoleLogger {
- private static final Logger log = Logger.getLogger("AuthMe");
+ private static final Logger log = AuthMe.getInstance().getLogger();
+ private static final DateFormat df = new SimpleDateFormat("[MM-dd HH:mm:ss]");
public static void info(String message) {
if (AuthMe.getInstance().isEnabled()) {
log.info("[AuthMe] " + message);
if (Settings.useLogging) {
- Calendar date = Calendar.getInstance();
- final String actually = "[" + DateFormat.getDateInstance().format(date.getTime()) + ", " + date.get(Calendar.HOUR_OF_DAY) + ":" + date.get(Calendar.MINUTE) + ":" + date.get(Calendar.SECOND) + "] " + message;
- Bukkit.getScheduler().runTaskAsynchronously(AuthMe.getInstance(), new Runnable() {
- @Override
- public void run() {
- writeLog(actually);
- }
- });
+ String dateTime;
+ synchronized (df) {
+ dateTime = df.format(new Date());
+ }
+ writeLog(dateTime + " " + message);
}
}
}
public static void showError(String message) {
if (AuthMe.getInstance().isEnabled()) {
- log.warning("[AuthMe] ERROR: " + message);
+ log.warning("[AuthMe] " + message);
if (Settings.useLogging) {
- Calendar date = Calendar.getInstance();
- final String actually = "[" + DateFormat.getDateInstance().format(date.getTime()) + ", " + date.get(Calendar.HOUR_OF_DAY) + ":" + date.get(Calendar.MINUTE) + ":" + date.get(Calendar.SECOND) + "] ERROR : " + message;
- Bukkit.getScheduler().runTaskAsynchronously(AuthMe.getInstance(), new Runnable() {
- @Override
- public void run() {
- writeLog(actually);
- }
- });
+ String dateTime;
+ synchronized (df) {
+ dateTime = df.format(new Date());
+ }
+ writeLog(dateTime + " ERROR: " + message);
}
}
}
- public static void writeLog(String string) {
+ public static void writeLog(String message) {
try {
- FileWriter fw = new FileWriter(AuthMe.getInstance().getDataFolder() + File.separator + "authme.log", true);
- BufferedWriter w = new BufferedWriter(fw);
- w.write(string);
- w.newLine();
- w.close();
- } catch (IOException e) {
- e.printStackTrace();
+ Files.write(Settings.LOG_FILE.toPath(), (message + NewAPI.newline).getBytes(),
+ StandardOpenOption.APPEND,
+ StandardOpenOption.CREATE);
+ } catch (IOException ignored) {
}
}
+ public static void writeStackTrace(Exception ex) {
+ String dateTime;
+ synchronized (df) {
+ dateTime = df.format(new Date());
+ }
+ writeLog(dateTime + " " + Throwables.getStackTraceAsString(ex));
+ }
}
diff --git a/src/main/java/fr/xephi/authme/DataManager.java b/src/main/java/fr/xephi/authme/DataManager.java
index 8f9db6d8..43782c5b 100644
--- a/src/main/java/fr/xephi/authme/DataManager.java
+++ b/src/main/java/fr/xephi/authme/DataManager.java
@@ -1,5 +1,11 @@
package fr.xephi.authme;
+import fr.xephi.authme.settings.Settings;
+import net.milkbowl.vault.permission.Permission;
+import org.bukkit.Bukkit;
+import org.bukkit.OfflinePlayer;
+import org.bukkit.entity.Player;
+
import java.io.File;
import java.util.List;
import java.util.concurrent.Callable;
@@ -7,13 +13,6 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
-import org.bukkit.Bukkit;
-import org.bukkit.OfflinePlayer;
-import org.bukkit.entity.Player;
-
-import fr.xephi.authme.settings.Settings;
-import net.milkbowl.vault.permission.Permission;
-
public class DataManager {
public AuthMe plugin;
@@ -134,10 +133,13 @@ public class DataManager {
playerFile.delete();
i++;
} else {
- playerFile = new File(plugin.ess.getDataFolder() + File.separator + "userdata" + File.separator + Bukkit.getOfflinePlayer(name).getUniqueId() + ".yml");
- if (playerFile.exists()) {
- playerFile.delete();
- i++;
+ try {
+ playerFile = new File(plugin.ess.getDataFolder() + File.separator + "userdata" + File.separator + Bukkit.getOfflinePlayer(name).getUniqueId() + ".yml");
+ if (playerFile.exists()) {
+ playerFile.delete();
+ i++;
+ }
+ } catch (Exception e) { // Don't do nothing if the method getUniqueId() isn't avariable ( MC version < 1.7.5 )
}
}
} catch (Exception e) {
@@ -147,7 +149,7 @@ public class DataManager {
}
public synchronized void purgePermissions(List cleared,
- Permission permission) {
+ Permission permission) {
int i = 0;
for (String name : cleared) {
try {
@@ -167,24 +169,19 @@ public class DataManager {
return true;
ExecutorService executor = Executors.newSingleThreadExecutor();
Future result = executor.submit(new Callable() {
-
+ @Override
public synchronized Boolean call() throws Exception {
- Boolean result = null;
- try {
- for (OfflinePlayer op : Bukkit.getOnlinePlayers())
- if (op.getName().equalsIgnoreCase(name)) {
- result = true;
- break;
- }
- } catch (Exception e) {
- }
- return result;
+ for (OfflinePlayer op : Utils.getOnlinePlayers())
+ if (op.getName().equalsIgnoreCase(name)) {
+ return true;
+ }
+ return false;
}
});
try {
- return result.get().booleanValue();
+ return result.get();
} catch (Exception e) {
- return (false);
+ return false;
} finally {
executor.shutdown();
}
diff --git a/src/main/java/fr/xephi/authme/PerformBackup.java b/src/main/java/fr/xephi/authme/PerformBackup.java
index 71a69f04..5550a7c7 100644
--- a/src/main/java/fr/xephi/authme/PerformBackup.java
+++ b/src/main/java/fr/xephi/authme/PerformBackup.java
@@ -30,18 +30,16 @@ public class PerformBackup {
this.setInstance(instance);
}
- public boolean DoBackup() {
+ public boolean doBackup() {
switch (Settings.getDataSource) {
case FILE:
return FileBackup("auths.db");
-
case MYSQL:
return MySqlBackup();
-
+ case SQLITEHIKARI:
case SQLITE:
return FileBackup(Settings.getMySQLDatabase + ".db");
-
}
return false;
diff --git a/src/main/java/fr/xephi/authme/Utils.java b/src/main/java/fr/xephi/authme/Utils.java
index c1975486..bdd156ff 100644
--- a/src/main/java/fr/xephi/authme/Utils.java
+++ b/src/main/java/fr/xephi/authme/Utils.java
@@ -1,93 +1,154 @@
package fr.xephi.authme;
-import java.io.File;
-import java.util.Iterator;
-
-import org.bukkit.Bukkit;
-import org.bukkit.GameMode;
-import org.bukkit.Location;
-import org.bukkit.World;
-import org.bukkit.entity.Player;
-
+import com.maxmind.geoip.LookupService;
+import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.cache.limbo.LimboPlayer;
import fr.xephi.authme.events.AuthMeTeleportEvent;
import fr.xephi.authme.settings.Settings;
+import org.bukkit.Bukkit;
+import org.bukkit.GameMode;
+import org.bukkit.Location;
+import org.bukkit.World;
+import org.bukkit.entity.Entity;
+import org.bukkit.entity.Player;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.lang.reflect.Method;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.zip.GZIPInputStream;
public class Utils {
- private String currentGroup;
- private static Utils singleton;
- int id;
- public AuthMe plugin;
+ public static AuthMe plugin;
- public Utils(AuthMe plugin) {
- this.plugin = plugin;
+ private static boolean getOnlinePlayersIsCollection;
+ private static Method getOnlinePlayers;
+ private static LookupService lookupService;
+
+ static {
+ plugin = AuthMe.getInstance();
+ checkGeoIP();
+ try {
+ Method m = Bukkit.class.getDeclaredMethod("getOnlinePlayers");
+ getOnlinePlayersIsCollection = m.getReturnType() == Collection.class;
+ } catch (Exception ignored) {
+ }
}
- public void setGroup(Player player, groupType group) {
- setGroup(player.getName(), group);
+ // Check and Download GeoIP data if not exist
+ public static boolean checkGeoIP() {
+ if (lookupService != null) {
+ return true;
+ }
+ ConsoleLogger.info("[LICENSE] This product uses data from the GeoLite API created by MaxMind, available at http://www.maxmind.com");
+ File file = new File(Settings.PLUGIN_FOLDER, "GeoIP.dat");
+ try {
+ if (file.exists()) {
+ if (lookupService == null) {
+ lookupService = new LookupService(file);
+ return true;
+ }
+ }
+ String url = "http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz";
+ URL downloadUrl = new URL(url);
+ URLConnection conn = downloadUrl.openConnection();
+ conn.setConnectTimeout(10000);
+ conn.connect();
+ InputStream input = conn.getInputStream();
+ if (conn.getURL().toString().endsWith(".gz")) {
+ input = new GZIPInputStream(input);
+ }
+ OutputStream output = new FileOutputStream(file);
+ byte[] buffer = new byte[2048];
+ int length = input.read(buffer);
+ while (length >= 0) {
+ output.write(buffer, 0, length);
+ length = input.read(buffer);
+ }
+ output.close();
+ input.close();
+ } catch (Exception e) {
+ ConsoleLogger.writeStackTrace(e);
+ return false;
+ }
+ return checkGeoIP();
}
- @SuppressWarnings("deprecation")
- public void setGroup(String player, groupType group) {
+ public static String getCountryCode(String ip) {
+ if (checkGeoIP()) {
+ return lookupService.getCountry(ip).getCode();
+ }
+ return "--";
+ }
+
+ public static String getCountryName(String ip) {
+ if (checkGeoIP()) {
+ return lookupService.getCountry(ip).getName();
+ }
+ return "N/A";
+ }
+
+ public static void setGroup(Player player, GroupType group) {
if (!Settings.isPermissionCheckEnabled)
return;
if (plugin.permission == null)
return;
- String name = player;
+ String currentGroup;
try {
- World world = null;
- currentGroup = plugin.permission.getPrimaryGroup(world, name);
+ currentGroup = plugin.permission.getPrimaryGroup(player);
} catch (UnsupportedOperationException e) {
ConsoleLogger.showError("Your permission plugin (" + plugin.permission.getName() + ") doesn't support the Group system... unhook!");
plugin.permission = null;
return;
}
- World world = null;
switch (group) {
case UNREGISTERED: {
- plugin.permission.playerRemoveGroup(world, name, currentGroup);
- plugin.permission.playerAddGroup(world, name, Settings.unRegisteredGroup);
+ plugin.permission.playerRemoveGroup(player, currentGroup);
+ plugin.permission.playerAddGroup(player, Settings.unRegisteredGroup);
break;
}
case REGISTERED: {
- plugin.permission.playerRemoveGroup(world, name, currentGroup);
- plugin.permission.playerAddGroup(world, name, Settings.getRegisteredGroup);
+ plugin.permission.playerRemoveGroup(player, currentGroup);
+ plugin.permission.playerAddGroup(player, Settings.getRegisteredGroup);
break;
}
case NOTLOGGEDIN: {
if (!useGroupSystem())
break;
- plugin.permission.playerRemoveGroup(world, name, currentGroup);
- plugin.permission.playerAddGroup(world, name, Settings.getUnloggedinGroup);
+ plugin.permission.playerRemoveGroup(player, currentGroup);
+ plugin.permission.playerAddGroup(player, Settings.getUnloggedinGroup);
break;
}
case LOGGEDIN: {
if (!useGroupSystem())
break;
- LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name.toLowerCase());
+ LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(player.getName().toLowerCase());
if (limbo == null)
break;
String realGroup = limbo.getGroup();
- plugin.permission.playerRemoveGroup(world, name, currentGroup);
- plugin.permission.playerAddGroup(world, name, realGroup);
+ plugin.permission.playerRemoveGroup(player, currentGroup);
+ plugin.permission.playerAddGroup(player, realGroup);
break;
}
}
- return;
}
- @SuppressWarnings("deprecation")
- public boolean addNormal(Player player, String group) {
+ public static boolean addNormal(Player player, String group) {
if (!useGroupSystem()) {
return false;
}
if (plugin.permission == null)
return false;
- World world = null;
try {
- if (plugin.permission.playerRemoveGroup(world, player.getName().toString(), Settings.getUnloggedinGroup) && plugin.permission.playerAddGroup(world, player.getName().toString(), group)) {
+ if (plugin.permission.playerRemoveGroup(player, Settings.getUnloggedinGroup) && plugin.permission.playerAddGroup(player, group)) {
return true;
}
} catch (UnsupportedOperationException e) {
@@ -98,39 +159,45 @@ public class Utils {
return false;
}
- public void hasPermOnJoin(Player player) {
+ // TODO: remove if not needed
+ @SuppressWarnings("unused")
+ public static void hasPermOnJoin(Player player) {
if (plugin.permission == null)
return;
- Iterator iter = Settings.getJoinPermissions.iterator();
- while (iter.hasNext()) {
- String permission = iter.next();
+ for (String permission : Settings.getJoinPermissions) {
if (plugin.permission.playerHas(player, permission)) {
plugin.permission.playerAddTransient(player, permission);
}
}
}
- public boolean isUnrestricted(Player player) {
- if (!Settings.isAllowRestrictedIp)
- return false;
- if (Settings.getUnrestrictedName == null || Settings.getUnrestrictedName.isEmpty())
- return false;
- return (Settings.getUnrestrictedName.contains(player.getName()));
- }
-
- public static Utils getInstance() {
- singleton = new Utils(AuthMe.getInstance());
- return singleton;
- }
-
- private boolean useGroupSystem() {
- if (Settings.isPermissionCheckEnabled && !Settings.getUnloggedinGroup.isEmpty())
+ // TODO: Move to a Manager
+ public static boolean checkAuth(Player player) {
+ if (player == null || Utils.isUnrestricted(player)) {
return true;
+ }
+ String name = player.getName().toLowerCase();
+ if (PlayerCache.getInstance().isAuthenticated(name)) {
+ return true;
+ }
+ if (!plugin.database.isAuthAvailable(name)) {
+ if (!Settings.isForcedRegistrationEnabled) {
+ return true;
+ }
+ }
return false;
}
- public void packCoords(double x, double y, double z, String w,
- final Player pl) {
+ public static boolean isUnrestricted(Player player) {
+ return Settings.isAllowRestrictedIp && !(Settings.getUnrestrictedName == null || Settings.getUnrestrictedName.isEmpty()) && (Settings.getUnrestrictedName.contains(player.getName()));
+ }
+
+ private static boolean useGroupSystem() {
+ return Settings.isPermissionCheckEnabled && !Settings.getUnloggedinGroup.isEmpty();
+ }
+
+ public static void packCoords(double x, double y, double z, String w,
+ final Player pl) {
World theWorld;
if (w.equals("unavailableworld")) {
theWorld = pl.getWorld();
@@ -161,29 +228,66 @@ public class Utils {
* Used for force player GameMode
*/
public static void forceGM(Player player) {
- if (!AuthMe.getInstance().authmePermissible(player, "authme.bypassforcesurvival"))
+ if (!plugin.authmePermissible(player, "authme.bypassforcesurvival"))
player.setGameMode(GameMode.SURVIVAL);
}
- public enum groupType {
+ public enum GroupType {
UNREGISTERED,
REGISTERED,
NOTLOGGEDIN,
LOGGEDIN
}
-
- public static void purgeDirectory(File file){
- String files[] = file.list();
- if (files != null && files.length != 0){
- for (String temp : files) {
- File fileDelete = new File(file, temp);
- if (fileDelete.isDirectory()){
- purgeDirectory(fileDelete);
- fileDelete.delete();
- } else {
- fileDelete.delete();
- }
+
+ public static void purgeDirectory(File file) {
+ if (!file.isDirectory()) {
+ return;
+ }
+ File[] files = file.listFiles();
+ if (files == null) {
+ return;
+ }
+ for (File target : files) {
+ if (target.isDirectory()) {
+ purgeDirectory(target);
+ target.delete();
+ } else {
+ target.delete();
}
}
}
+
+ @SuppressWarnings("unchecked")
+ public static Collection extends Player> getOnlinePlayers() {
+ if (getOnlinePlayersIsCollection) {
+ return Bukkit.getOnlinePlayers();
+ }
+ try {
+ if (getOnlinePlayers == null) {
+ getOnlinePlayers = Bukkit.class.getMethod("getOnlinePlayers");
+ }
+ Object obj = getOnlinePlayers.invoke(null);
+ if (obj instanceof Collection) {
+ return (Collection extends Player>) obj;
+ }
+ return Arrays.asList((Player[]) obj);
+ } catch (Exception ignored) {
+ }
+ return Collections.emptyList();
+ }
+
+ public static boolean isNPC(final Entity player) {
+ try {
+ if (player.hasMetadata("NPC")) {
+ return true;
+ } else if (plugin.combatTagPlus != null
+ && player instanceof Player
+ && plugin.combatTagPlus.getNpcPlayerHelper().isNpc((Player) player)) {
+ return true;
+ }
+ return false;
+ } catch (Exception e) {
+ return false;
+ }
+ }
}
diff --git a/src/main/java/fr/xephi/authme/api/API.java b/src/main/java/fr/xephi/authme/api/API.java
index 477494a2..11eba861 100644
--- a/src/main/java/fr/xephi/authme/api/API.java
+++ b/src/main/java/fr/xephi/authme/api/API.java
@@ -12,7 +12,6 @@ import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
-import fr.xephi.authme.plugin.manager.CombatTagComunicator;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Settings;
@@ -65,9 +64,7 @@ public class API {
*/
@Deprecated
public boolean isaNPC(Player player) {
- if (instance.getCitizensCommunicator().isNPC(player))
- return true;
- return CombatTagComunicator.isNPC(player);
+ return Utils.isNPC(player);
}
/**
@@ -77,9 +74,7 @@ public class API {
*/
@Deprecated
public boolean isNPC(Player player) {
- if (instance.getCitizensCommunicator().isNPC(player))
- return true;
- return CombatTagComunicator.isNPC(player);
+ return Utils.isNPC(player);
}
/**
@@ -89,7 +84,7 @@ public class API {
*/
@Deprecated
public static boolean isUnrestricted(Player player) {
- return Utils.getInstance().isUnrestricted(player);
+ return Utils.isUnrestricted(player);
}
@Deprecated
diff --git a/src/main/java/fr/xephi/authme/api/NewAPI.java b/src/main/java/fr/xephi/authme/api/NewAPI.java
index a632ea60..937a8abe 100644
--- a/src/main/java/fr/xephi/authme/api/NewAPI.java
+++ b/src/main/java/fr/xephi/authme/api/NewAPI.java
@@ -14,7 +14,6 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
-import fr.xephi.authme.plugin.manager.CombatTagComunicator;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Settings;
@@ -34,9 +33,7 @@ public class NewAPI {
/**
* Hook into AuthMe
- *
- * @return
- *
+ *
* @return AuthMe plugin
*/
public static NewAPI getInstance() {
@@ -70,9 +67,7 @@ public class NewAPI {
* @return true if player is a npc
*/
public boolean isNPC(Player player) {
- if (plugin.getCitizensCommunicator().isNPC(player))
- return true;
- return CombatTagComunicator.isNPC(player);
+ return Utils.isNPC(player);
}
/**
@@ -81,7 +76,7 @@ public class NewAPI {
* @return true if the player is unrestricted
*/
public boolean isUnrestricted(Player player) {
- return Utils.getInstance().isUnrestricted(player);
+ return Utils.isUnrestricted(player);
}
public Location getLastLocation(Player player) {
@@ -89,8 +84,7 @@ public class NewAPI {
PlayerAuth auth = PlayerCache.getInstance().getAuth(player.getName().toLowerCase());
if (auth != null) {
- Location loc = new Location(Bukkit.getWorld(auth.getWorld()), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ());
- return loc;
+ return new Location(Bukkit.getWorld(auth.getWorld()), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ());
} else {
return null;
}
@@ -152,10 +146,7 @@ public class NewAPI {
return false;
}
PlayerAuth auth = new PlayerAuth(name, hash, "192.168.0.1", 0, "your@email.com");
- if (!plugin.database.saveAuth(auth)) {
- return false;
- }
- return true;
+ return plugin.database.saveAuth(auth);
} catch (NoSuchAlgorithmException ex) {
return false;
}
diff --git a/src/main/java/fr/xephi/authme/cache/auth/PlayerCache.java b/src/main/java/fr/xephi/authme/cache/auth/PlayerCache.java
index 8f39c0d3..491c33a4 100644
--- a/src/main/java/fr/xephi/authme/cache/auth/PlayerCache.java
+++ b/src/main/java/fr/xephi/authme/cache/auth/PlayerCache.java
@@ -8,7 +8,7 @@ public class PlayerCache {
private ConcurrentHashMap cache;
private PlayerCache() {
- cache = new ConcurrentHashMap();
+ cache = new ConcurrentHashMap<>();
}
public void addPlayer(PlayerAuth auth) {
diff --git a/src/main/java/fr/xephi/authme/cache/backup/DataFileCache.java b/src/main/java/fr/xephi/authme/cache/backup/DataFileCache.java
index ef5ab501..6644166f 100644
--- a/src/main/java/fr/xephi/authme/cache/backup/DataFileCache.java
+++ b/src/main/java/fr/xephi/authme/cache/backup/DataFileCache.java
@@ -11,8 +11,7 @@ public class DataFileCache {
private boolean flying;
public DataFileCache(ItemStack[] inventory, ItemStack[] armor) {
- this.inventory = inventory;
- this.armor = armor;
+ this(inventory, armor, "", false, false);
}
public DataFileCache(ItemStack[] inventory, ItemStack[] armor,
diff --git a/src/main/java/fr/xephi/authme/cache/backup/FileCache.java b/src/main/java/fr/xephi/authme/cache/backup/FileCache.java
deleted file mode 100644
index 2a4b09eb..00000000
--- a/src/main/java/fr/xephi/authme/cache/backup/FileCache.java
+++ /dev/null
@@ -1,570 +0,0 @@
-package fr.xephi.authme.cache.backup;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Scanner;
-import java.util.UUID;
-
-import org.bukkit.Material;
-import org.bukkit.enchantments.Enchantment;
-import org.bukkit.entity.Player;
-import org.bukkit.inventory.ItemStack;
-import org.bukkit.inventory.meta.ItemMeta;
-
-import com.comphenix.attribute.Attributes;
-import com.comphenix.attribute.Attributes.Attribute;
-import com.comphenix.attribute.Attributes.Attribute.Builder;
-import com.comphenix.attribute.Attributes.AttributeType;
-import com.comphenix.attribute.Attributes.Operation;
-
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.ConsoleLogger;
-import fr.xephi.authme.Utils;
-import fr.xephi.authme.api.API;
-import fr.xephi.authme.settings.Settings;
-
-public class FileCache {
-
- private AuthMe plugin;
-
- public FileCache(AuthMe plugin) {
- this.plugin = plugin;
- final File file = new File(plugin.getDataFolder() + File.separator + "cache");
- if (!file.exists())
- file.mkdir();
- }
-
- public void createCache(Player player, DataFileCache playerData,
- String group, boolean operator, boolean flying) {
- String path = "";
- if (player == null)
- return;
- try {
- path = player.getUniqueId().toString();
- } catch (Exception e) {
- path = player.getName().toLowerCase();
- } catch (Error e) {
- path = player.getName().toLowerCase();
- }
- File file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "playerdatas.cache");
-
- if (!file.getParentFile().exists())
- file.getParentFile().mkdirs();
- if (file.exists()) {
- return;
- }
-
- FileWriter writer = null;
- try {
- file.createNewFile();
-
- writer = new FileWriter(file);
- writer.write(group + API.newline);
- writer.write(String.valueOf(operator) + API.newline);
- writer.write(String.valueOf(flying) + API.newline);
- writer.close();
-
- file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "inventory");
-
- file.mkdirs();
- ItemStack[] inv = playerData.getInventory();
- for (int i = 0; i < inv.length; i++) {
- ItemStack item = inv[i];
- file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "inventory" + File.separator + i + ".cache");
- file.createNewFile();
- writer = new FileWriter(file);
- if (item != null) {
- if (item.getType() == Material.AIR) {
- writer.write("AIR");
- writer.close();
- continue;
- }
- writer.write(item.getType().name() + API.newline);
- writer.write(item.getDurability() + API.newline);
- writer.write(item.getAmount() + API.newline);
- writer.flush();
- if (item.hasItemMeta()) {
- ItemMeta meta = item.getItemMeta();
- if (meta.hasDisplayName())
- writer.write("name=" + meta.getDisplayName() + API.newline);
- if (meta.hasLore()) {
- String lores = "";
- for (String lore : meta.getLore())
- lores = lore + "%newline%";
- writer.write("lore=" + lores + API.newline);
- }
- if (meta.hasEnchants()) {
- for (Enchantment ench : meta.getEnchants().keySet()) {
- writer.write("metaenchant=" + ench.getName() + ":" + meta.getEnchants().get(ench) + API.newline);
- }
- }
- writer.flush();
- }
- for (Enchantment ench : item.getEnchantments().keySet()) {
- writer.write("enchant=" + ench.getName() + ":" + item.getEnchantments().get(ench) + API.newline);
- }
- if (Settings.customAttributes) {
- try {
- Attributes attributes = new Attributes(item);
- if (attributes != null) {
- Iterator iter = attributes.values().iterator();
- Attribute a = null;
- while (iter.hasNext()) {
- Attribute b = iter.next();
- if (a != null && a == b)
- break;
- a = b;
- if (a != null) {
- if (a.getName() != null && a.getAttributeType() != null && a.getOperation() != null && a.getUUID() != null)
- writer.write("attribute=" + a.getName() + ";" + a.getAttributeType().getMinecraftId() + ";" + a.getAmount() + ";" + a.getOperation().getId() + ";" + a.getUUID().toString());
- }
- }
- }
- } catch (Exception e) {
- } catch (Error e) {
- }
- }
- } else {
- writer.write("AIR");
- }
- writer.close();
- }
-
- file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "armours");
- if (!file.getParentFile().exists())
- file.getParentFile().mkdirs();
- file.mkdirs();
-
- ItemStack[] armors = playerData.getArmour();
- for (int i = 0; i < armors.length; i++) {
- ItemStack item = armors[i];
- file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "armours" + File.separator + i + ".cache");
- file.createNewFile();
- writer = new FileWriter(file);
- if (item != null) {
- if (item.getType() == Material.AIR) {
- writer.write("AIR");
- writer.close();
- continue;
- }
- writer.write(item.getType().name() + API.newline);
- writer.write(item.getDurability() + API.newline);
- writer.write(item.getAmount() + API.newline);
- writer.flush();
- if (item.hasItemMeta()) {
- ItemMeta meta = item.getItemMeta();
- if (meta.hasDisplayName())
- writer.write("name=" + meta.getDisplayName() + API.newline);
- if (meta.hasLore()) {
- String lores = "";
- for (String lore : meta.getLore())
- lores = lore + "%newline%";
- writer.write("lore=" + lores + API.newline);
- }
- writer.flush();
- }
- for (Enchantment ench : item.getEnchantments().keySet()) {
- writer.write("enchant=" + ench.getName() + ":" + item.getEnchantments().get(ench) + API.newline);
- }
- if (Settings.customAttributes) {
- try {
- Attributes attributes = new Attributes(item);
- if (attributes != null)
- while (attributes.values().iterator().hasNext()) {
- Attribute a = attributes.values().iterator().next();
- if (a != null) {
- if (a.getName() != null && a.getAttributeType() != null && a.getOperation() != null && a.getUUID() != null && a.getAttributeType().getMinecraftId() != null)
- writer.write("attribute=" + a.getName() + ";" + a.getAttributeType().getMinecraftId() + ";" + a.getAmount() + ";" + a.getOperation().getId() + ";" + a.getUUID().toString());
- }
- }
- } catch (Exception e) {
- }
- }
- } else {
- writer.write("AIR" + API.newline);
- }
- writer.close();
- }
- } catch (final Exception e) {
- ConsoleLogger.showError("Some error on creating file cache...");
- }
- }
-
- public DataFileCache readCache(Player player) {
- String path = "";
- try {
- path = player.getUniqueId().toString();
- } catch (Exception e) {
- path = player.getName().toLowerCase();
- } catch (Error e) {
- path = player.getName().toLowerCase();
- }
- try {
- File file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "playerdatas.cache");
- String playername = player.getName().toLowerCase();
- if (!file.exists()) {
- // OLD METHOD
- file = new File("cache/" + playername + ".cache");
- ItemStack[] stacki = new ItemStack[36];
- ItemStack[] stacka = new ItemStack[4];
- if (!file.exists()) {
- return new DataFileCache(stacki, stacka);
- }
- String group = null;
- boolean op = false;
- boolean flying = false;
-
- Scanner reader = new Scanner(file);
-
- int i = 0;
- int a = 0;
- while (reader.hasNextLine()) {
- String line = reader.nextLine();
-
- if (!line.contains(":")) {
- // the fist line represent the player group,
- // operator
- // status
- // and flying status
- final String[] playerInfo = line.split(";");
- group = playerInfo[0];
-
- if (Integer.parseInt(playerInfo[1]) == 1) {
- op = true;
- } else op = false;
- if (playerInfo.length > 2) {
- if (Integer.parseInt(playerInfo[2]) == 1)
- flying = true;
- else flying = false;
- }
-
- continue;
- }
-
- if (!line.startsWith("i") && !line.startsWith("w")) {
- continue;
- }
- String lores = "";
- String name = "";
- if (line.split("\\*").length > 1) {
- lores = line.split("\\*")[1];
- line = line.split("\\*")[0];
- }
- if (line.split(";").length > 1) {
- name = line.split(";")[1];
- line = line.split(";")[0];
- }
- final String[] in = line.split(":");
- // can enchant item? size ofstring in file - 4 all / 2 =
- // number
- // of enchant
- if (in[0].equals("i")) {
- stacki[i] = new ItemStack(Material.getMaterial(in[1]), Integer.parseInt(in[2]), Short.parseShort((in[3])));
- if (in.length > 4 && !in[4].isEmpty()) {
- for (int k = 4; k < in.length - 1; k++) {
- stacki[i].addUnsafeEnchantment(Enchantment.getByName(in[k]), Integer.parseInt(in[k + 1]));
- k++;
- }
- }
- ItemMeta meta = stacki[i].getItemMeta();
- if (!name.isEmpty()) {
- meta.setDisplayName(name);
- }
- if (!lores.isEmpty()) {
- List loreList = new ArrayList();
- for (String s : lores.split("%newline%")) {
- loreList.add(s);
- }
- meta.setLore(loreList);
- }
- if (meta != null)
- stacki[i].setItemMeta(meta);
- i++;
- } else {
- stacka[a] = new ItemStack(Material.getMaterial(in[1]), Integer.parseInt(in[2]), Short.parseShort((in[3])));
- if (in.length > 4 && !in[4].isEmpty()) {
- for (int k = 4; k < in.length - 1; k++) {
- stacka[a].addUnsafeEnchantment(Enchantment.getByName(in[k]), Integer.parseInt(in[k + 1]));
- k++;
- }
- }
- ItemMeta meta = stacka[a].getItemMeta();
- if (!name.isEmpty())
- meta.setDisplayName(name);
- if (!lores.isEmpty()) {
- List loreList = new ArrayList();
- for (String s : lores.split("%newline%")) {
- loreList.add(s);
- }
- meta.setLore(loreList);
- }
- if (meta != null)
- stacki[i].setItemMeta(meta);
- a++;
- }
- }
- if (reader != null)
- reader.close();
- return new DataFileCache(stacki, stacka, group, op, flying);
- } else {
- // NEW METHOD
- ItemStack[] inv = new ItemStack[36];
- ItemStack[] armours = new ItemStack[4];
- String group = null;
- boolean op = false;
- boolean flying = false;
-
- Scanner reader = null;
- try {
- reader = new Scanner(file);
-
- int count = 1;
- while (reader.hasNextLine()) {
- String line = reader.nextLine();
- switch (count) {
- case 1:
- group = line;
- break;
- case 2:
- op = Boolean.parseBoolean(line);
- break;
- case 3:
- flying = Boolean.parseBoolean(line);
- break;
- default:
- break;
- }
- count++;
- }
- if (reader != null)
- reader.close();
- for (int i = 0; i < inv.length; i++) {
- reader = new Scanner(new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "inventory" + File.separator + i + ".cache"));
- ItemStack item = new ItemStack(Material.AIR);
- ItemMeta meta = item.getItemMeta();
- Attributes attributes = null;
- count = 1;
- boolean v = true;
- while (reader.hasNextLine() && v == true) {
- String line = reader.nextLine();
- switch (count) {
- case 1:
- item = new ItemStack(Material.getMaterial(line));
- if (item.getType() == Material.AIR)
- v = false;
- meta = item.getItemMeta();
- count++;
- continue;
- case 2:
- item.setDurability((short) Integer.parseInt(line));
- count++;
- continue;
- case 3:
- item.setAmount(Integer.parseInt(line));
- count++;
- continue;
- default:
- break;
- }
- meta = item.getItemMeta();
- if (line.startsWith("name=")) {
- line = line.substring(5);
- meta.setDisplayName(line);
- item.setItemMeta(meta);
- continue;
- }
- if (line.startsWith("lore=")) {
- line = line.substring(5);
- List lore = new ArrayList();
- for (String s : line.split("%newline%"))
- lore.add(s);
- meta.setLore(lore);
- item.setItemMeta(meta);
- continue;
- }
- if (line.startsWith("enchant=")) {
- line = line.substring(8);
- item.addEnchantment(Enchantment.getByName(line.split(":")[0]), Integer.parseInt(line.split(":")[1]));
- continue;
- }
- if (Settings.customAttributes) {
- if (line.startsWith("attribute=")) {
- if (attributes == null)
- attributes = new Attributes(item);
- try {
- line = line.substring(10);
- String[] args = line.split(";");
- if (args.length != 5)
- continue;
- String name = args[0];
- AttributeType type = AttributeType.fromId(args[1]);
- double amount = Double.parseDouble(args[2]);
- Operation operation = Operation.fromId(Integer.parseInt(args[3]));
- UUID uuid = UUID.fromString(args[4]);
- Builder build = Attribute.newBuilder();
- build.amount(amount);
- build.operation(operation);
- build.type(type);
- build.name(name);
- build.uuid(uuid);
- attributes.add(build.build());
- } catch (Exception e) {
- }
- }
- }
- count++;
- }
- if (reader != null)
- reader.close();
- if (Settings.customAttributes && attributes != null)
- inv[i] = attributes.getStack();
- else inv[i] = item;
- }
- for (int i = 0; i < armours.length; i++) {
- reader = new Scanner(new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "armours" + File.separator + i + ".cache"));
- ItemStack item = new ItemStack(Material.AIR);
- ItemMeta meta = null;
- Attributes attributes = null;
- count = 1;
- boolean v = true;
- while (reader.hasNextLine() && v == true) {
- String line = reader.nextLine();
- switch (count) {
- case 1:
- item = new ItemStack(Material.getMaterial(line));
- if (item.getType() == Material.AIR)
- v = false;
- meta = item.getItemMeta();
- count++;
- continue;
- case 2:
- item.setDurability((short) Integer.parseInt(line));
- count++;
- continue;
- case 3:
- item.setAmount(Integer.parseInt(line));
- count++;
- continue;
- default:
- break;
- }
- meta = item.getItemMeta();
- if (line.startsWith("name=")) {
- line = line.substring(5);
- meta.setDisplayName(line);
- item.setItemMeta(meta);
- continue;
- }
- if (line.startsWith("lore=")) {
- line = line.substring(5);
- List lore = new ArrayList();
- for (String s : line.split("%newline%"))
- lore.add(s);
- meta.setLore(lore);
- item.setItemMeta(meta);
- continue;
- }
- if (line.startsWith("enchant=")) {
- line = line.substring(8);
- item.addEnchantment(Enchantment.getByName(line.split(":")[0]), Integer.parseInt(line.split(":")[1]));
- }
- if (Settings.customAttributes) {
- if (line.startsWith("attribute=")) {
- if (attributes == null)
- attributes = new Attributes(item);
- try {
- line = line.substring(10);
- String[] args = line.split(";");
- if (args.length != 5)
- continue;
- String name = args[0];
- AttributeType type = AttributeType.fromId(args[1]);
- double amount = Double.parseDouble(args[2]);
- Operation operation = Operation.fromId(Integer.parseInt(args[3]));
- UUID uuid = UUID.fromString(args[4]);
- Builder build = Attribute.newBuilder();
- build.amount(amount);
- build.operation(operation);
- build.type(type);
- build.name(name);
- build.uuid(uuid);
- attributes.add(build.build());
- } catch (Exception e) {
- }
- }
- }
- count++;
- }
- if (reader != null)
- reader.close();
- if (attributes != null)
- armours[i] = attributes.getStack();
- else armours[i] = item;
- }
- } catch (final RuntimeException e) {
- ConsoleLogger.showError("Error while reading file for " + player.getName() + ", some wipe inventory incoming...");
- } catch (final Exception e) {
- ConsoleLogger.showError("Error while reading file for " + player.getName() + ", some wipe inventory incoming...");
- } finally {
- if (reader != null)
- reader.close();
- }
- return new DataFileCache(inv, armours, group, op, flying);
- }
- } catch (RuntimeException e) {
- ConsoleLogger.showError("Error while reading file for " + player.getName() + ", some wipe inventory incoming...");
- return null;
- } catch (Exception e) {
- ConsoleLogger.showError("Error while reading file for " + player.getName() + ", some wipe inventory incoming...");
- return null;
- }
- }
-
- public void removeCache(Player player) {
- String path = "";
- try {
- path = player.getUniqueId().toString();
- } catch (Exception e) {
- path = player.getName().toLowerCase();
- } catch (Error e) {
- path = player.getName().toLowerCase();
- }
- try {
- File file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path);
- if (file.list() != null) {
- Utils.purgeDirectory(file);
- file.delete();
- } else {
- file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + player.getName().toLowerCase() + ".cache");
- if (file.isFile()) {
- file.delete();
- } else {
- ConsoleLogger.showError("Failed to remove" + player.getName() + "cache, it doesn't exist!");
- }
- }
- } catch (Exception e) {
- ConsoleLogger.showError("Failed to remove" + player.getName() + "cache :/");
- }
- }
-
- public boolean doesCacheExist(Player player) {
- String path = "";
- try {
- path = player.getUniqueId().toString();
- } catch (Exception e) {
- path = player.getName().toLowerCase();
- } catch (Error e) {
- path = player.getName().toLowerCase();
- }
- File file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "playerdatas.cache");
- if (!file.exists()) {
- file = new File("cache/" + player.getName().toLowerCase() + ".cache");
- }
-
- return file.exists();
- }
-
-}
diff --git a/src/main/java/fr/xephi/authme/cache/backup/JsonCache.java b/src/main/java/fr/xephi/authme/cache/backup/JsonCache.java
new file mode 100644
index 00000000..760def96
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/cache/backup/JsonCache.java
@@ -0,0 +1,232 @@
+package fr.xephi.authme.cache.backup;
+
+import com.google.common.base.Charsets;
+import com.google.common.io.Files;
+import com.google.gson.*;
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.ConsoleLogger;
+import fr.xephi.authme.Utils;
+import fr.xephi.authme.settings.Settings;
+import org.bukkit.Material;
+import org.bukkit.entity.Player;
+import org.bukkit.inventory.ItemStack;
+import org.bukkit.inventory.meta.SkullMeta;
+import org.bukkit.util.io.BukkitObjectInputStream;
+import org.bukkit.util.io.BukkitObjectOutputStream;
+import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.Type;
+
+public class JsonCache {
+
+ private final Gson gson;
+ private final AuthMe plugin;
+ private final File cacheDir;
+
+ public JsonCache(AuthMe plugin) {
+ this.plugin = plugin;
+ cacheDir = Settings.CACHE_FOLDER;
+ if (!cacheDir.exists() && !cacheDir.isDirectory() && !cacheDir.mkdir()) {
+ ConsoleLogger.showError("Failed to create cache directory.");
+ }
+ gson = new GsonBuilder()
+ .registerTypeAdapter(DataFileCache.class, new PlayerDataSerializer())
+ .registerTypeAdapter(DataFileCache.class, new PlayerDataDeserializer())
+ .setPrettyPrinting()
+ .create();
+ }
+
+ public void createCache(Player player, DataFileCache playerData) {
+ if (player == null) {
+ return;
+ }
+
+ String path;
+ try {
+ path = player.getUniqueId().toString();
+ } catch (Exception | Error e) {
+ path = player.getName().toLowerCase();
+ }
+
+ File file = new File(cacheDir, path + File.separator + "cache.json");
+ if (file.exists()) {
+ return;
+ }
+ if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
+ return;
+ }
+
+ try {
+ String data = gson.toJson(playerData);
+ Files.touch(file);
+ Files.write(data, file, Charsets.UTF_8);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public DataFileCache readCache(Player player) {
+ String path;
+ try {
+ path = player.getUniqueId().toString();
+ } catch (Exception | Error e) {
+ path = player.getName().toLowerCase();
+ }
+
+ File file = new File(cacheDir, path + File.separator + "cache.json");
+ if (!file.exists()) {
+ return null;
+ }
+
+ try {
+ String str = Files.toString(file, Charsets.UTF_8);
+ return gson.fromJson(str, DataFileCache.class);
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ private class PlayerDataSerializer implements JsonSerializer {
+ @Override
+ public JsonElement serialize(DataFileCache dataFileCache, Type type, JsonSerializationContext jsonSerializationContext) {
+ JsonObject jsonObject = new JsonObject();
+ jsonObject.addProperty("group", dataFileCache.getGroup());
+ jsonObject.addProperty("operator", dataFileCache.getOperator());
+ jsonObject.addProperty("flying", dataFileCache.isFlying());
+
+ JsonArray arr;
+ ItemStack[] contents;
+
+ // inventory
+ contents = dataFileCache.getInventory();
+ arr = new JsonArray();
+ putItems(contents, arr);
+ jsonObject.add("inventory", arr);
+
+ // armour
+ contents = dataFileCache.getArmour();
+ arr = new JsonArray();
+ putItems(contents, arr);
+ jsonObject.add("armour", arr);
+
+ return jsonObject;
+ }
+
+ private void putItems(ItemStack[] contents, JsonArray target) {
+ for (ItemStack item : contents) {
+ if (item == null) {
+ item = new ItemStack(Material.AIR);
+ }
+ JsonObject val = new JsonObject();
+ if (item.getType() == Material.SKULL_ITEM) {
+ SkullMeta meta = (SkullMeta) item.getItemMeta();
+ if (meta.hasOwner() && (meta.getOwner() == null || meta.getOwner().isEmpty())) {
+ item.setItemMeta(plugin.getServer().getItemFactory().getItemMeta(Material.SKULL_ITEM));
+ }
+ }
+ try {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ BukkitObjectOutputStream objectOut = new BukkitObjectOutputStream(baos);
+ objectOut.writeObject(item);
+ objectOut.close();
+ val.addProperty("item", Base64Coder.encodeLines(baos.toByteArray()));
+ } catch (IOException e) {
+ e.printStackTrace();
+ continue;
+ }
+ target.add(val);
+ }
+ }
+ }
+
+ private static class PlayerDataDeserializer implements JsonDeserializer {
+ @Override
+ public DataFileCache deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
+ JsonObject jsonObject = jsonElement.getAsJsonObject();
+ if (jsonObject == null) {
+ return null;
+ }
+ JsonElement e;
+ String group = null;
+ boolean operator = false;
+ boolean flying = false;
+
+ if ((e = jsonObject.get("group")) != null) {
+ group = e.getAsString();
+ }
+ if ((e = jsonObject.get("operator")) != null) {
+ operator = e.getAsBoolean();
+ }
+ if ((e = jsonObject.get("flying")) != null) {
+ flying = e.getAsBoolean();
+ }
+
+ JsonArray arr;
+ ItemStack[] inv = null;
+ ItemStack[] armour = null;
+
+ if (jsonObject.has("inventory")) {
+ arr = jsonObject.get("inventory").getAsJsonArray();
+ inv = getItems(arr);
+ }
+
+ if (jsonObject.has("armour")) {
+ arr = jsonObject.get("armour").getAsJsonArray();
+ armour = getItems(arr);
+ }
+
+ return new DataFileCache(inv, armour, group, operator, flying);
+ }
+
+ private ItemStack[] getItems(JsonArray arr) {
+ ItemStack[] contents = new ItemStack[arr.size()];
+ for (int i = 0; i < arr.size(); i++) {
+ JsonObject item = arr.get(i).getAsJsonObject();
+ String encoded = item.get("item").getAsString();
+ byte[] decoded = Base64Coder.decodeLines(encoded);
+ try {
+ ByteArrayInputStream baos = new ByteArrayInputStream(decoded);
+ BukkitObjectInputStream objectIn = new BukkitObjectInputStream(baos);
+ contents[i] = (ItemStack) objectIn.readObject();
+ objectIn.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ return contents;
+ }
+ }
+
+ public void removeCache(Player player) {
+ String path;
+ try {
+ path = player.getUniqueId().toString();
+ } catch (Exception | Error e) {
+ path = player.getName().toLowerCase();
+ }
+ File file = new File(cacheDir, path);
+ if (file.exists()) {
+ Utils.purgeDirectory(file);
+ if (!file.delete()) {
+ ConsoleLogger.showError("Failed to remove" + player.getName() + "cache.");
+ }
+ }
+ }
+
+ public boolean doesCacheExist(Player player) {
+ String path;
+ try {
+ path = player.getUniqueId().toString();
+ } catch (Exception | Error e) {
+ path = player.getName().toLowerCase();
+ }
+ File file = new File(cacheDir, path + File.separator + "cache.json");
+ return file.exists();
+ }
+
+}
diff --git a/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java b/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java
index 2c3d89be..366bc60a 100644
--- a/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java
+++ b/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java
@@ -1,31 +1,31 @@
package fr.xephi.authme.cache.limbo;
-import java.util.concurrent.ConcurrentHashMap;
-
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.ConsoleLogger;
+import fr.xephi.authme.cache.backup.DataFileCache;
+import fr.xephi.authme.cache.backup.JsonCache;
+import fr.xephi.authme.events.ResetInventoryEvent;
+import fr.xephi.authme.events.StoreInventoryEvent;
+import fr.xephi.authme.settings.Settings;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.ConsoleLogger;
-import fr.xephi.authme.cache.backup.FileCache;
-import fr.xephi.authme.events.ResetInventoryEvent;
-import fr.xephi.authme.events.StoreInventoryEvent;
-import fr.xephi.authme.settings.Settings;
+import java.util.concurrent.ConcurrentHashMap;
public class LimboCache {
- private volatile static LimboCache singleton = null;
+ private volatile static LimboCache singleton;
public ConcurrentHashMap cache;
- private FileCache playerData;
+ private JsonCache playerData;
public AuthMe plugin;
private LimboCache(AuthMe plugin) {
this.plugin = plugin;
- this.cache = new ConcurrentHashMap();
- this.playerData = new FileCache(plugin);
+ this.cache = new ConcurrentHashMap<>();
+ this.playerData = new JsonCache(plugin);
}
public void addLimboPlayer(Player player) {
@@ -48,12 +48,11 @@ public class LimboCache {
inv = null;
arm = null;
}
- try {
- playerGroup = playerData.readCache(player).getGroup();
- operator = playerData.readCache(player).getOperator();
- flying = playerData.readCache(player).isFlying();
- } catch (Exception e) {
- ConsoleLogger.showError("Some error on reading cache of " + name);
+ DataFileCache cache = playerData.readCache(player);
+ if (cache != null) {
+ playerGroup = cache.getGroup();
+ operator = cache.getOperator();
+ flying = cache.isFlying();
}
} else {
StoreInventoryEvent event = new StoreInventoryEvent(player);
@@ -65,12 +64,8 @@ public class LimboCache {
inv = null;
arm = null;
}
- if (player.isOp())
- operator = true;
- else operator = false;
- if (player.isFlying())
- flying = true;
- else flying = false;
+ operator = player.isOp();
+ flying = player.isFlying();
if (plugin.permission != null) {
try {
playerGroup = plugin.permission.getPrimaryGroup(player);
@@ -82,7 +77,7 @@ public class LimboCache {
}
if (Settings.isForceSurvivalModeEnabled) {
- if (Settings.isResetInventoryIfCreative && player.getGameMode() == GameMode.CREATIVE) {
+ if (Settings.isResetInventoryIfCreative && gameMode == GameMode.CREATIVE) {
ResetInventoryEvent event = new ResetInventoryEvent(player);
Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) {
@@ -128,7 +123,7 @@ public class LimboCache {
if (this.hasLimboPlayer(player.getName().toLowerCase())) {
this.deleteLimboPlayer(player.getName().toLowerCase());
}
- this.addLimboPlayer(player);
+ addLimboPlayer(player);
}
}
diff --git a/src/main/java/fr/xephi/authme/commands/AdminCommand.java b/src/main/java/fr/xephi/authme/commands/AdminCommand.java
index cdcbf997..7a562ea5 100644
--- a/src/main/java/fr/xephi/authme/commands/AdminCommand.java
+++ b/src/main/java/fr/xephi/authme/commands/AdminCommand.java
@@ -1,31 +1,9 @@
package fr.xephi.authme.commands;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.InputStream;
-import java.security.NoSuchAlgorithmException;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.List;
-
-import org.bukkit.Bukkit;
-import org.bukkit.Location;
-import org.bukkit.OfflinePlayer;
-import org.bukkit.command.Command;
-import org.bukkit.command.CommandExecutor;
-import org.bukkit.command.CommandSender;
-import org.bukkit.configuration.file.YamlConfiguration;
-import org.bukkit.entity.Player;
-import org.bukkit.potion.PotionEffect;
-import org.bukkit.potion.PotionEffectType;
-import org.bukkit.scheduler.BukkitScheduler;
-import org.bukkit.scheduler.BukkitTask;
-
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
-import fr.xephi.authme.Utils.groupType;
+import fr.xephi.authme.Utils.GroupType;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.limbo.LimboCache;
@@ -36,6 +14,23 @@ import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.Spawn;
import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask;
+import org.bukkit.Bukkit;
+import org.bukkit.Location;
+import org.bukkit.OfflinePlayer;
+import org.bukkit.command.Command;
+import org.bukkit.command.CommandExecutor;
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+import org.bukkit.potion.PotionEffect;
+import org.bukkit.potion.PotionEffectType;
+import org.bukkit.scheduler.BukkitScheduler;
+import org.bukkit.scheduler.BukkitTask;
+
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
public class AdminCommand implements CommandExecutor {
@@ -48,7 +43,7 @@ public class AdminCommand implements CommandExecutor {
@Override
public boolean onCommand(final CommandSender sender, Command cmnd,
- String label, String[] args) {
+ String label, String[] args) {
if (args.length == 0) {
sender.sendMessage("Usage:");
sender.sendMessage("/authme reload - Reload the config");
@@ -113,44 +108,23 @@ public class AdminCommand implements CommandExecutor {
return true;
}
} else if (args[0].equalsIgnoreCase("reload")) {
- File newConfigFile = new File("plugins" + File.separator + "AuthMe", "config.yml");
- if (!newConfigFile.exists()) {
- InputStream fis = getClass().getResourceAsStream("" + File.separator + "config.yml");
- FileOutputStream fos = null;
- try {
- fos = new FileOutputStream(newConfigFile);
- byte[] buf = new byte[1024];
- int i = 0;
-
- while ((i = fis.read(buf)) != -1) {
- fos.write(buf, 0, i);
- }
- } catch (Exception e) {
- ConsoleLogger.showError("Failed to load config from JAR");
- } finally {
- try {
- if (fis != null) {
- fis.close();
- }
- if (fos != null) {
- fos.close();
- }
- } catch (Exception e) {
- }
- }
+ try {
+ plugin.getSettings().reload();
+ m.reloadMessages();
+ plugin.database.close();
+ plugin.setupDatabase();
+ } catch (Exception e) {
+ ConsoleLogger.showError("Fatal error occurred! Authme instance ABORTED!");
+ plugin.stopOrUnload();
+ return false;
}
- YamlConfiguration newConfig = YamlConfiguration.loadConfiguration(newConfigFile);
- Settings.reloadConfigOptions(newConfig);
- m.reloadMessages();
- plugin.database.close();
- plugin.setupDatabase();
m.send(sender, "reload");
} else if (args[0].equalsIgnoreCase("lastlogin")) {
if (args.length != 2) {
sender.sendMessage("Usage: /authme lastlogin ");
return true;
}
- PlayerAuth auth = null;
+ PlayerAuth auth;
try {
auth = plugin.database.getAuth(args[1].toLowerCase());
} catch (NullPointerException e) {
@@ -176,92 +150,89 @@ public class AdminCommand implements CommandExecutor {
return true;
}
if (!args[1].contains(".")) {
- final CommandSender fSender = sender;
final String[] arguments = args;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
- PlayerAuth auth = null;
- String message = "[AuthMe] ";
+ PlayerAuth auth;
+ StringBuilder message = new StringBuilder("[AuthMe] ");
try {
auth = plugin.database.getAuth(arguments[1].toLowerCase());
} catch (NullPointerException npe) {
- m.send(fSender, "unknown_user");
+ m.send(sender, "unknown_user");
return;
}
if (auth == null) {
- m.send(fSender, "unknown_user");
+ m.send(sender, "unknown_user");
return;
}
List accountList = plugin.database.getAllAuthsByName(auth);
if (accountList == null || accountList.isEmpty()) {
- m.send(fSender, "user_unknown");
+ m.send(sender, "user_unknown");
return;
}
if (accountList.size() == 1) {
- fSender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player");
+ sender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player");
return;
}
int i = 0;
for (String account : accountList) {
i++;
- message = message + account;
+ message.append(account);
if (i != accountList.size()) {
- message = message + ", ";
+ message.append(", ");
} else {
- message = message + ".";
+ message.append(".");
}
}
- fSender.sendMessage("[AuthMe] " + arguments[1] + " has " + String.valueOf(accountList.size()) + " accounts");
- fSender.sendMessage(message);
+ sender.sendMessage("[AuthMe] " + arguments[1] + " has " + String.valueOf(accountList.size()) + " accounts");
+ sender.sendMessage(message.toString());
}
});
return true;
} else {
- final CommandSender fSender = sender;
final String[] arguments = args;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
-
@Override
public void run() {
- String message = "[AuthMe] ";
+ StringBuilder message = new StringBuilder("[AuthMe] ");
if (arguments[1] == null) {
- fSender.sendMessage("[AuthMe] Please put a valid IP");
+ sender.sendMessage("[AuthMe] Please put a valid IP");
return;
}
List accountList = plugin.database.getAllAuthsByIp(arguments[1]);
if (accountList == null || accountList.isEmpty()) {
- fSender.sendMessage("[AuthMe] This IP does not exist in the database");
+ sender.sendMessage("[AuthMe] This IP does not exist in the database");
return;
}
if (accountList.size() == 1) {
- fSender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player");
+ sender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player");
return;
}
int i = 0;
for (String account : accountList) {
i++;
- message = message + account;
+ message.append(account);
if (i != accountList.size()) {
- message = message + ", ";
+ message.append(", ");
} else {
- message = message + ".";
+ message.append(".");
}
}
- fSender.sendMessage("[AuthMe] " + arguments[1] + " has " + String.valueOf(accountList.size()) + " accounts");
- fSender.sendMessage(message);
+ sender.sendMessage("[AuthMe] " + arguments[1] + " has " + String.valueOf(accountList.size()) + " accounts");
+ sender.sendMessage(message.toString());
}
});
return true;
}
- } else
- if (args[0].equalsIgnoreCase("register") || args[0].equalsIgnoreCase("reg")) {
+ } else if (args[0].equalsIgnoreCase("register") || args[0].equalsIgnoreCase("reg")) {
if (args.length != 3) {
sender.sendMessage("Usage: /authme register ");
return true;
}
- String lowpass = args[2].toLowerCase();
+ final String name = args[1].toLowerCase();
+ final String lowpass = args[2].toLowerCase();
if (lowpass.contains("delete") || lowpass.contains("where") || lowpass.contains("insert") || lowpass.contains("modify") || lowpass.contains("from") || lowpass.contains("select") || lowpass.contains(";") || lowpass.contains("null") || !lowpass.matches(Settings.getPassRegex)) {
m.send(sender, "password_error");
return true;
@@ -280,27 +251,32 @@ public class AdminCommand implements CommandExecutor {
return true;
}
}
- try {
- String name = args[1].toLowerCase();
- if (plugin.database.isAuthAvailable(name)) {
- m.send(sender, "user_regged");
- return true;
+ plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
+ @Override
+ public void run() {
+ try {
+ if (plugin.database.isAuthAvailable(name)) {
+ m.send(sender, "user_regged");
+ return;
+ }
+ String hash = PasswordSecurity.getHash(Settings.getPasswordHash, lowpass, name);
+ PlayerAuth auth = new PlayerAuth(name, hash, "192.168.0.1", 0L, "your@email.com");
+ if (PasswordSecurity.userSalt.containsKey(name) && PasswordSecurity.userSalt.get(name) != null)
+ auth.setSalt(PasswordSecurity.userSalt.get(name));
+ else auth.setSalt("");
+ if (!plugin.database.saveAuth(auth)) {
+ m.send(sender, "error");
+ return;
+ }
+ m.send(sender, "registered");
+ ConsoleLogger.info(name + " registered");
+ } catch (NoSuchAlgorithmException ex) {
+ ConsoleLogger.showError(ex.getMessage());
+ m.send(sender, "error");
+ }
+
}
- String hash = PasswordSecurity.getHash(Settings.getPasswordHash, args[2], name);
- PlayerAuth auth = new PlayerAuth(name, hash, "192.168.0.1", 0L, "your@email.com");
- if (PasswordSecurity.userSalt.containsKey(name) && PasswordSecurity.userSalt.get(name) != null)
- auth.setSalt(PasswordSecurity.userSalt.get(name));
- else auth.setSalt("");
- if (!plugin.database.saveAuth(auth)) {
- m.send(sender, "error");
- return true;
- }
- m.send(sender, "registered");
- ConsoleLogger.info(args[1] + " registered");
- } catch (NoSuchAlgorithmException ex) {
- ConsoleLogger.showError(ex.getMessage());
- m.send(sender, "error");
- }
+ });
return true;
} else if (args[0].equalsIgnoreCase("getemail")) {
if (args.length != 2) {
@@ -368,7 +344,7 @@ public class AdminCommand implements CommandExecutor {
}
return true;
} else if (args[0].equalsIgnoreCase("purgebannedplayers")) {
- List bannedPlayers = new ArrayList();
+ List bannedPlayers = new ArrayList<>();
for (OfflinePlayer off : plugin.getServer().getBannedPlayers()) {
bannedPlayers.add(off.getName().toLowerCase());
}
@@ -409,8 +385,7 @@ public class AdminCommand implements CommandExecutor {
ConsoleLogger.showError(ex.getMessage());
}
return true;
- } else
- if (args[0].equalsIgnoreCase("changepassword") || args[0].equalsIgnoreCase("cp")) {
+ } else if (args[0].equalsIgnoreCase("changepassword") || args[0].equalsIgnoreCase("cp")) {
if (args.length != 3) {
sender.sendMessage("Usage: /authme changepassword ");
return true;
@@ -486,9 +461,10 @@ public class AdminCommand implements CommandExecutor {
m.send(sender, "error");
return true;
}
+ @SuppressWarnings("deprecation")
Player target = Bukkit.getPlayer(name);
PlayerCache.getInstance().removePlayer(name);
- Utils.getInstance().setGroup(name, groupType.UNREGISTERED);
+ Utils.setGroup(target, GroupType.UNREGISTERED);
if (target != null) {
if (target.isOnline()) {
if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
@@ -510,18 +486,17 @@ public class AdminCommand implements CommandExecutor {
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("reg_msg"), interval)));
if (Settings.applyBlindEffect)
target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
+ if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
+ target.setWalkSpeed(0.0f);
+ target.setFlySpeed(0.0f);
+ }
m.send(target, "unregistered");
- } else {
- // Player isn't online, do nothing else
}
- } else {
- // Player does not exist, do nothing else
}
m.send(sender, "unregistered");
ConsoleLogger.info(args[1] + " unregistered");
return true;
- } else
- if (args[0].equalsIgnoreCase("purgelastpos") || args[0].equalsIgnoreCase("resetposition")) {
+ } else if (args[0].equalsIgnoreCase("purgelastpos") || args[0].equalsIgnoreCase("resetposition")) {
if (args.length != 2) {
sender.sendMessage("Usage: /authme purgelastpos ");
return true;
@@ -568,6 +543,7 @@ public class AdminCommand implements CommandExecutor {
sender.sendMessage("Usage: /authme getip ");
return true;
}
+ @SuppressWarnings("deprecation")
Player player = Bukkit.getPlayer(args[1]);
if (player == null) {
sender.sendMessage("This player is not actually online");
@@ -583,6 +559,7 @@ public class AdminCommand implements CommandExecutor {
return true;
}
try {
+ @SuppressWarnings("deprecation")
Player player = Bukkit.getPlayer(args[1]);
if (player == null || !player.isOnline()) {
sender.sendMessage("Player needs to be online!");
diff --git a/src/main/java/fr/xephi/authme/commands/ChangePasswordCommand.java b/src/main/java/fr/xephi/authme/commands/ChangePasswordCommand.java
index 7577a202..6d3c1f2f 100644
--- a/src/main/java/fr/xephi/authme/commands/ChangePasswordCommand.java
+++ b/src/main/java/fr/xephi/authme/commands/ChangePasswordCommand.java
@@ -1,20 +1,15 @@
package fr.xephi.authme.commands;
-import java.security.NoSuchAlgorithmException;
-
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.cache.auth.PlayerCache;
+import fr.xephi.authme.settings.Messages;
+import fr.xephi.authme.settings.Settings;
+import fr.xephi.authme.task.ChangePasswordTask;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.ConsoleLogger;
-import fr.xephi.authme.cache.auth.PlayerAuth;
-import fr.xephi.authme.cache.auth.PlayerCache;
-import fr.xephi.authme.security.PasswordSecurity;
-import fr.xephi.authme.settings.Messages;
-import fr.xephi.authme.settings.Settings;
-
public class ChangePasswordCommand implements CommandExecutor {
private Messages m = Messages.getInstance();
@@ -26,7 +21,7 @@ public class ChangePasswordCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label,
- String[] args) {
+ String[] args) {
if (!(sender instanceof Player)) {
return true;
}
@@ -67,30 +62,7 @@ public class ChangePasswordCommand implements CommandExecutor {
return true;
}
}
- try {
- String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, args[1], name);
-
- if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache.getInstance().getAuth(name).getHash(), player.getName())) {
- PlayerAuth auth = PlayerCache.getInstance().getAuth(name);
- auth.setHash(hashnew);
- if (PasswordSecurity.userSalt.containsKey(name) && PasswordSecurity.userSalt.get(name) != null)
- auth.setSalt(PasswordSecurity.userSalt.get(name));
- else auth.setSalt("");
- if (!plugin.database.updatePassword(auth)) {
- m.send(player, "error");
- return true;
- }
- plugin.database.updateSalt(auth);
- PlayerCache.getInstance().updatePlayer(auth);
- m.send(player, "pwd_changed");
- ConsoleLogger.info(player.getName() + " changed his password");
- } else {
- m.send(player, "wrong_pwd");
- }
- } catch (NoSuchAlgorithmException ex) {
- ConsoleLogger.showError(ex.getMessage());
- m.send(sender, "error");
- }
+ plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new ChangePasswordTask(plugin, player, args[0]));
return true;
}
}
diff --git a/src/main/java/fr/xephi/authme/commands/RegisterCommand.java b/src/main/java/fr/xephi/authme/commands/RegisterCommand.java
index 11ab0a12..68f59b94 100644
--- a/src/main/java/fr/xephi/authme/commands/RegisterCommand.java
+++ b/src/main/java/fr/xephi/authme/commands/RegisterCommand.java
@@ -1,15 +1,14 @@
package fr.xephi.authme.commands;
-import org.bukkit.command.Command;
-import org.bukkit.command.CommandExecutor;
-import org.bukkit.command.CommandSender;
-import org.bukkit.entity.Player;
-
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
+import org.bukkit.command.Command;
+import org.bukkit.command.CommandExecutor;
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
public class RegisterCommand implements CommandExecutor {
@@ -23,26 +22,23 @@ public class RegisterCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label,
- String[] args) {
+ String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("Player Only! Use 'authme register ' instead");
return true;
}
- if (args.length == 0) {
- m.send(sender, "usage_reg");
- }
- if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) {
- m.send(sender, "no_perm");
+ final Player player = (Player) sender;
+ if (args.length == 0 || (Settings.getEnablePasswordVerifier && args.length < 2)) {
+ m.send(player, "usage_reg");
+ return true;
+ }
+ if (!plugin.authmePermissible(player, "authme." + label.toLowerCase())) {
+ m.send(player, "no_perm");
return true;
}
- final Player player = (Player) sender;
if (Settings.emailRegistration && !Settings.getmailAccount.isEmpty()) {
if (Settings.doubleEmailCheck) {
- if (args.length < 2) {
- m.send(player, "usage_reg");
- return true;
- }
- if (!args[0].equals(args[1])) {
+ if (args.length < 2 || !args[0].equals(args[1])) {
m.send(player, "usage_reg");
return true;
}
@@ -57,10 +53,6 @@ public class RegisterCommand implements CommandExecutor {
plugin.management.performRegister(player, thePass, email);
return true;
}
- if (args.length == 0 || (Settings.getEnablePasswordVerifier && args.length < 2)) {
- m.send(player, "usage_reg");
- return true;
- }
if (args.length > 1 && Settings.getEnablePasswordVerifier)
if (!args[0].equals(args[1])) {
m.send(player, "password_error");
diff --git a/src/main/java/fr/xephi/authme/commands/UnregisterCommand.java b/src/main/java/fr/xephi/authme/commands/UnregisterCommand.java
index 1361656d..814757e1 100644
--- a/src/main/java/fr/xephi/authme/commands/UnregisterCommand.java
+++ b/src/main/java/fr/xephi/authme/commands/UnregisterCommand.java
@@ -1,7 +1,18 @@
package fr.xephi.authme.commands;
-import java.security.NoSuchAlgorithmException;
-
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.ConsoleLogger;
+import fr.xephi.authme.Utils;
+import fr.xephi.authme.Utils.GroupType;
+import fr.xephi.authme.cache.auth.PlayerCache;
+import fr.xephi.authme.cache.backup.JsonCache;
+import fr.xephi.authme.cache.limbo.LimboCache;
+import fr.xephi.authme.events.SpawnTeleportEvent;
+import fr.xephi.authme.security.PasswordSecurity;
+import fr.xephi.authme.settings.Messages;
+import fr.xephi.authme.settings.Settings;
+import fr.xephi.authme.task.MessageTask;
+import fr.xephi.authme.task.TimeoutTask;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
@@ -13,34 +24,22 @@ import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.ConsoleLogger;
-import fr.xephi.authme.Utils;
-import fr.xephi.authme.Utils.groupType;
-import fr.xephi.authme.cache.auth.PlayerCache;
-import fr.xephi.authme.cache.backup.FileCache;
-import fr.xephi.authme.cache.limbo.LimboCache;
-import fr.xephi.authme.events.SpawnTeleportEvent;
-import fr.xephi.authme.security.PasswordSecurity;
-import fr.xephi.authme.settings.Messages;
-import fr.xephi.authme.settings.Settings;
-import fr.xephi.authme.task.MessageTask;
-import fr.xephi.authme.task.TimeoutTask;
+import java.security.NoSuchAlgorithmException;
public class UnregisterCommand implements CommandExecutor {
private Messages m = Messages.getInstance();
public AuthMe plugin;
- private FileCache playerCache;
+ private JsonCache playerCache;
public UnregisterCommand(AuthMe plugin) {
this.plugin = plugin;
- this.playerCache = new FileCache(plugin);
+ this.playerCache = new JsonCache(plugin);
}
@Override
- public boolean onCommand(CommandSender sender, Command cmnd, String label,
- String[] args) {
+ public boolean onCommand(final CommandSender sender, Command cmnd, String label,
+ final String[] args) {
if (!(sender instanceof Player)) {
return true;
}
@@ -50,8 +49,8 @@ public class UnregisterCommand implements CommandExecutor {
return true;
}
- Player player = (Player) sender;
- String name = player.getName().toLowerCase();
+ final Player player = (Player) sender;
+ final String name = player.getName().toLowerCase();
if (!PlayerCache.getInstance().isAuthenticated(name)) {
m.send(player, "not_logged_in");
@@ -62,72 +61,81 @@ public class UnregisterCommand implements CommandExecutor {
m.send(player, "usage_unreg");
return true;
}
- try {
- if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache.getInstance().getAuth(name).getHash(), player.getName())) {
- if (!plugin.database.removeAuth(name)) {
- player.sendMessage("error");
- return true;
- }
- if (Settings.isForcedRegistrationEnabled) {
- if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
- Location spawn = plugin.getSpawnLocation(player);
- SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawn, false);
- plugin.getServer().getPluginManager().callEvent(tpEvent);
- if (!tpEvent.isCancelled()) {
- player.teleport(tpEvent.getTo());
+ plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
+ @Override
+ public void run() {
+ try {
+ if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache.getInstance().getAuth(name).getHash(), player.getName())) {
+ if (!plugin.database.removeAuth(name)) {
+ player.sendMessage("error");
+ return;
}
- }
- player.getInventory().setContents(new ItemStack[36]);
- player.getInventory().setArmorContents(new ItemStack[4]);
- player.saveData();
- PlayerCache.getInstance().removePlayer(player.getName().toLowerCase());
- if (!Settings.getRegisteredGroup.isEmpty())
- Utils.getInstance().setGroup(player, groupType.UNREGISTERED);
- LimboCache.getInstance().addLimboPlayer(player);
- int delay = Settings.getRegistrationTimeout * 20;
- int interval = Settings.getWarnMessageInterval;
- BukkitScheduler sched = sender.getServer().getScheduler();
- if (delay != 0) {
- BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), delay);
- LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
- }
- LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("reg_msg"), interval)));
- m.send(player, "unregistered");
- ConsoleLogger.info(player.getDisplayName() + " unregistered himself");
- return true;
- }
- if (!Settings.unRegisteredGroup.isEmpty()) {
- Utils.getInstance().setGroup(player, Utils.groupType.UNREGISTERED);
- }
- PlayerCache.getInstance().removePlayer(player.getName().toLowerCase());
- // check if Player cache File Exist and delete it, preventing
- // duplication of items
- if (playerCache.doesCacheExist(player)) {
- playerCache.removeCache(player);
- }
- if (Settings.applyBlindEffect)
- player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
- m.send(player, "unregistered");
- ConsoleLogger.info(player.getDisplayName() + " unregistered himself");
- if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
- Location spawn = plugin.getSpawnLocation(player);
- SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawn, false);
- plugin.getServer().getPluginManager().callEvent(tpEvent);
- if (!tpEvent.isCancelled()) {
- if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) {
- tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load();
+ if (Settings.isForcedRegistrationEnabled) {
+ if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
+ Location spawn = plugin.getSpawnLocation(player);
+ SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawn, false);
+ plugin.getServer().getPluginManager().callEvent(tpEvent);
+ if (!tpEvent.isCancelled()) {
+ player.teleport(tpEvent.getTo());
+ }
+ }
+ player.getInventory().setContents(new ItemStack[36]);
+ player.getInventory().setArmorContents(new ItemStack[4]);
+ player.saveData();
+ PlayerCache.getInstance().removePlayer(player.getName().toLowerCase());
+ if (!Settings.getRegisteredGroup.isEmpty())
+ Utils.setGroup(player, GroupType.UNREGISTERED);
+ LimboCache.getInstance().addLimboPlayer(player);
+ int delay = Settings.getRegistrationTimeout * 20;
+ int interval = Settings.getWarnMessageInterval;
+ BukkitScheduler sched = sender.getServer().getScheduler();
+ if (delay != 0) {
+ BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), delay);
+ LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
+ }
+ LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("reg_msg"), interval)));
+ m.send(player, "unregistered");
+ ConsoleLogger.info(player.getDisplayName() + " unregistered himself");
+ return;
}
- player.teleport(tpEvent.getTo());
+ if (!Settings.unRegisteredGroup.isEmpty()) {
+ Utils.setGroup(player, Utils.GroupType.UNREGISTERED);
+ }
+ PlayerCache.getInstance().removePlayer(player.getName().toLowerCase());
+ // check if Player cache File Exist and delete it, preventing
+ // duplication of items
+ if (playerCache.doesCacheExist(player)) {
+ playerCache.removeCache(player);
+ }
+ if (Settings.applyBlindEffect)
+ player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
+ if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
+ player.setWalkSpeed(0.0f);
+ player.setFlySpeed(0.0f);
+ }
+ m.send(player, "unregistered");
+ ConsoleLogger.info(player.getDisplayName() + " unregistered himself");
+ if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
+ Location spawn = plugin.getSpawnLocation(player);
+ SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawn, false);
+ plugin.getServer().getPluginManager().callEvent(tpEvent);
+ if (!tpEvent.isCancelled()) {
+ if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) {
+ tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load();
+ }
+ player.teleport(tpEvent.getTo());
+ }
+ }
+ return;
+ } else {
+ m.send(player, "wrong_pwd");
}
+ } catch (NoSuchAlgorithmException ex) {
+ ConsoleLogger.showError(ex.getMessage());
+ sender.sendMessage("Internal Error please read the server log");
}
- return true;
- } else {
- m.send(player, "wrong_pwd");
}
- } catch (NoSuchAlgorithmException ex) {
- ConsoleLogger.showError(ex.getMessage());
- sender.sendMessage("Internal Error please read the server log");
- }
+ });
return true;
}
}
diff --git a/src/main/java/fr/xephi/authme/converter/CrazyLoginConverter.java b/src/main/java/fr/xephi/authme/converter/CrazyLoginConverter.java
index 0ffae7db..dbb247d0 100644
--- a/src/main/java/fr/xephi/authme/converter/CrazyLoginConverter.java
+++ b/src/main/java/fr/xephi/authme/converter/CrazyLoginConverter.java
@@ -2,7 +2,6 @@ package fr.xephi.authme.converter;
import java.io.BufferedReader;
import java.io.File;
-import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
@@ -70,10 +69,9 @@ public class CrazyLoginConverter implements Converter {
}
users.close();
ConsoleLogger.info("CrazyLogin database has been imported correctly");
- } catch (FileNotFoundException ex) {
- ConsoleLogger.showError(ex.getMessage());
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
+ ConsoleLogger.showError("Can't open the crazylogin database file! Does it exist?");
}
}
diff --git a/src/main/java/fr/xephi/authme/converter/FlatToSql.java b/src/main/java/fr/xephi/authme/converter/FlatToSql.java
index 03112a60..0f0b7bf8 100644
--- a/src/main/java/fr/xephi/authme/converter/FlatToSql.java
+++ b/src/main/java/fr/xephi/authme/converter/FlatToSql.java
@@ -3,7 +3,6 @@ package fr.xephi.authme.converter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
-import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
@@ -79,10 +78,9 @@ public class FlatToSql implements Converter {
sql.close();
br.close();
ConsoleLogger.info("The FlatFile has been converted to authme.sql file");
- } catch (FileNotFoundException ex) {
- ConsoleLogger.showError(ex.getMessage());
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
+ ConsoleLogger.showError("Can't open the flat database file! Does it exist?");
}
}
}
diff --git a/src/main/java/fr/xephi/authme/converter/FlatToSqlite.java b/src/main/java/fr/xephi/authme/converter/FlatToSqlite.java
index 757a9d2d..f81d4a69 100644
--- a/src/main/java/fr/xephi/authme/converter/FlatToSqlite.java
+++ b/src/main/java/fr/xephi/authme/converter/FlatToSqlite.java
@@ -2,7 +2,6 @@ package fr.xephi.authme.converter;
import java.io.BufferedReader;
import java.io.File;
-import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
@@ -90,12 +89,10 @@ public class FlatToSqlite implements Converter {
close();
sender.sendMessage("The FlatFile has been converted to " + database + ".db file");
return;
- } catch (FileNotFoundException ex) {
- ConsoleLogger.showError(ex.getMessage());
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
+ sender.sendMessage("Can't open the flat database file! Does it exist?");
}
- sender.sendMessage("Errors appears while trying to convert to SQLite");
return;
}
diff --git a/src/main/java/fr/xephi/authme/converter/RakamakConverter.java b/src/main/java/fr/xephi/authme/converter/RakamakConverter.java
index 333b6bde..38697dbb 100644
--- a/src/main/java/fr/xephi/authme/converter/RakamakConverter.java
+++ b/src/main/java/fr/xephi/authme/converter/RakamakConverter.java
@@ -2,7 +2,6 @@ package fr.xephi.authme.converter;
import java.io.BufferedReader;
import java.io.File;
-import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
@@ -100,12 +99,9 @@ public class RakamakConverter implements Converter {
}
ConsoleLogger.info("Rakamak database has been imported correctly");
sender.sendMessage("Rakamak database has been imported correctly");
- } catch (FileNotFoundException ex) {
- ConsoleLogger.showError(ex.getMessage());
- sender.sendMessage("Error file not found");
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
- sender.sendMessage("Error IOException");
+ sender.sendMessage("Can't open the rakamak database file! Does it exist?");
}
}
}
diff --git a/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java b/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java
index 3d1aa5cc..d4b0772c 100644
--- a/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java
+++ b/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java
@@ -1,30 +1,36 @@
package fr.xephi.authme.datasource;
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.Utils;
+import fr.xephi.authme.cache.auth.PlayerAuth;
+import fr.xephi.authme.cache.auth.PlayerCache;
+import org.bukkit.entity.Player;
+
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
-import org.bukkit.entity.Player;
-
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.cache.auth.PlayerAuth;
-import fr.xephi.authme.cache.auth.PlayerCache;
-
public class CacheDataSource implements DataSource {
- private DataSource source;
- public AuthMe plugin;
- private ConcurrentHashMap cache = new ConcurrentHashMap();
+ private final DataSource source;
+ private final AuthMe plugin;
+ private ConcurrentHashMap cache = new ConcurrentHashMap<>();
- public CacheDataSource(AuthMe plugin, DataSource source) {
- this.plugin = plugin;
- this.source = source;
+ public CacheDataSource(AuthMe pl, DataSource src) {
+ this.plugin = pl;
+ this.source = src;
/*
* We need to load all players in cache ... It will took more time to
* load the server, but it will be much easier to check for an
* isAuthAvailable !
*/
- for (PlayerAuth auth : source.getAllAuths())
- cache.put(auth.getNickname().toLowerCase(), auth);
+ pl.getServer().getScheduler().runTaskAsynchronously(pl, new Runnable() {
+ @Override
+ public void run() {
+ for (PlayerAuth auth : source.getAllAuths()) {
+ cache.put(auth.getNickname().toLowerCase(), auth);
+ }
+ }
+ });
}
@Override
@@ -37,21 +43,22 @@ public class CacheDataSource implements DataSource {
user = user.toLowerCase();
if (cache.containsKey(user)) {
return cache.get(user);
- } else {
- PlayerAuth auth = source.getAuth(user);
- if (auth != null)
- cache.put(user, auth);
- return auth;
}
+ return null;
}
@Override
- public synchronized boolean saveAuth(PlayerAuth auth) {
- if (source.saveAuth(auth)) {
- cache.put(auth.getNickname(), auth);
- return true;
- }
- return false;
+ public synchronized boolean saveAuth(final PlayerAuth auth) {
+ cache.put(auth.getNickname(), auth);
+ plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
+ @Override
+ public void run() {
+ if (!source.saveAuth(auth)) {
+ cache.remove(auth.getNickname());
+ }
+ }
+ });
+ return true;
}
@Override
@@ -140,15 +147,11 @@ public class CacheDataSource implements DataSource {
public void reload() {
cache.clear();
source.reload();
- for (Player player : plugin.getServer().getOnlinePlayers()) {
+ for (Player player : Utils.getOnlinePlayers()) {
String user = player.getName().toLowerCase();
if (PlayerCache.getInstance().isAuthenticated(user)) {
- try {
- PlayerAuth auth = source.getAuth(user);
- cache.put(user, auth);
- } catch (NullPointerException npe) {
- }
-
+ PlayerAuth auth = source.getAuth(user);
+ cache.put(user, auth);
}
}
}
diff --git a/src/main/java/fr/xephi/authme/datasource/DataSource.java b/src/main/java/fr/xephi/authme/datasource/DataSource.java
index ef445dc4..b89f13aa 100644
--- a/src/main/java/fr/xephi/authme/datasource/DataSource.java
+++ b/src/main/java/fr/xephi/authme/datasource/DataSource.java
@@ -1,16 +1,16 @@
package fr.xephi.authme.datasource;
-import java.util.List;
-
import fr.xephi.authme.cache.auth.PlayerAuth;
+import java.util.List;
+
public interface DataSource {
- public enum DataSourceType {
-
+ enum DataSourceType {
MYSQL,
FILE,
- SQLITE
+ SQLITE,
+ SQLITEHIKARI
}
boolean isAuthAvailable(String user);
diff --git a/src/main/java/fr/xephi/authme/datasource/DatabaseCalls.java b/src/main/java/fr/xephi/authme/datasource/DatabaseCalls.java
index 1b3e0993..6b84c7d7 100644
--- a/src/main/java/fr/xephi/authme/datasource/DatabaseCalls.java
+++ b/src/main/java/fr/xephi/authme/datasource/DatabaseCalls.java
@@ -1,67 +1,42 @@
package fr.xephi.authme.datasource;
+import fr.xephi.authme.cache.auth.PlayerAuth;
+
import java.util.ArrayList;
import java.util.List;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-
-import fr.xephi.authme.cache.auth.PlayerAuth;
+import java.util.concurrent.*;
public class DatabaseCalls implements DataSource {
private DataSource database;
+ private final ExecutorService exec;
public DatabaseCalls(DataSource database) {
this.database = database;
+ this.exec = Executors.newCachedThreadPool();
}
@Override
public synchronized boolean isAuthAvailable(final String user) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Boolean result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public Boolean call() throws Exception {
return database.isAuthAvailable(user);
}
}).get();
- } catch (InterruptedException e1) {
- return false;
- } catch (ExecutionException e1) {
- return false;
- } finally {
- executor.shutdown();
- }
- try {
- return result.booleanValue();
} catch (Exception e) {
- return (false);
+ return false;
}
}
@Override
public synchronized PlayerAuth getAuth(final String user) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- PlayerAuth result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public PlayerAuth call() throws Exception {
return database.getAuth(user);
}
}).get();
- } catch (InterruptedException e1) {
- return null;
- } catch (ExecutionException e1) {
- return null;
- } finally {
- executor.shutdown();
- }
- try {
- return result;
} catch (Exception e) {
return null;
}
@@ -69,332 +44,183 @@ public class DatabaseCalls implements DataSource {
@Override
public synchronized boolean saveAuth(final PlayerAuth auth) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Boolean result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public Boolean call() throws Exception {
return database.saveAuth(auth);
}
}).get();
- } catch (InterruptedException e1) {
- return false;
- } catch (ExecutionException e1) {
- return false;
- } finally {
- executor.shutdown();
- }
- try {
- return result.booleanValue();
} catch (Exception e) {
- return (false);
+ return false;
}
}
@Override
public synchronized boolean updateSession(final PlayerAuth auth) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Boolean result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public Boolean call() throws Exception {
return database.updateSession(auth);
}
}).get();
- } catch (InterruptedException e1) {
- return false;
- } catch (ExecutionException e1) {
- return false;
- } finally {
- executor.shutdown();
- }
- try {
- return result.booleanValue();
} catch (Exception e) {
- return (false);
+ return false;
}
}
@Override
public synchronized boolean updatePassword(final PlayerAuth auth) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Boolean result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public Boolean call() throws Exception {
return database.updatePassword(auth);
}
}).get();
- } catch (InterruptedException e1) {
- return false;
- } catch (ExecutionException e1) {
- return false;
- } finally {
- executor.shutdown();
- }
- try {
- return result.booleanValue();
} catch (Exception e) {
- return (false);
+ return false;
}
}
@Override
public synchronized int purgeDatabase(final long until) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Integer result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public Integer call() throws Exception {
return database.purgeDatabase(until);
}
}).get();
- } catch (InterruptedException e1) {
- return 0;
- } catch (ExecutionException e1) {
- return 0;
- } finally {
- executor.shutdown();
- }
- try {
- return result.intValue();
} catch (Exception e) {
- return (0);
+ return -1;
}
}
@Override
public synchronized List autoPurgeDatabase(final long until) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- List result;
try {
- result = executor.submit(new Callable>() {
-
+ return exec.submit(new Callable>() {
public List call() throws Exception {
return database.autoPurgeDatabase(until);
}
}).get();
- } catch (InterruptedException e1) {
- return new ArrayList();
- } catch (ExecutionException e1) {
- return new ArrayList();
- } finally {
- executor.shutdown();
- }
- try {
- return result;
} catch (Exception e) {
- return (new ArrayList());
+ return new ArrayList<>();
}
}
@Override
public synchronized boolean removeAuth(final String user) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Boolean result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public Boolean call() throws Exception {
return database.removeAuth(user);
}
}).get();
- } catch (InterruptedException e1) {
- return false;
- } catch (ExecutionException e1) {
- return false;
- } finally {
- executor.shutdown();
- }
- try {
- return result.booleanValue();
} catch (Exception e) {
- return (false);
+ return false;
}
}
@Override
public synchronized boolean updateQuitLoc(final PlayerAuth auth) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Boolean result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public Boolean call() throws Exception {
return database.updateQuitLoc(auth);
}
}).get();
- } catch (InterruptedException e1) {
- return false;
- } catch (ExecutionException e1) {
- return false;
- } finally {
- executor.shutdown();
- }
- try {
- return result.booleanValue();
} catch (Exception e) {
- return (false);
+ return false;
}
}
@Override
public synchronized int getIps(final String ip) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Integer result;
try {
- result = executor.submit(new Callable() {
+ return exec.submit(new Callable() {
public Integer call() throws Exception {
return database.getIps(ip);
}
}).get();
- } catch (InterruptedException e1) {
- return 0;
- } catch (ExecutionException e1) {
- return 0;
- } finally {
- executor.shutdown();
- }
- try {
- return result.intValue();
} catch (Exception e) {
- return (0);
+ return -1;
}
}
@Override
public synchronized List getAllAuthsByName(final PlayerAuth auth) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- List result;
try {
- result = executor.submit(new Callable>() {
-
+ return exec.submit(new Callable>() {
public List call() throws Exception {
return database.getAllAuthsByName(auth);
}
}).get();
- } catch (InterruptedException e1) {
- return new ArrayList();
- } catch (ExecutionException e1) {
- return new ArrayList();
- } finally {
- executor.shutdown();
- }
- try {
- return result;
} catch (Exception e) {
- return (new ArrayList());
+ return new ArrayList<>();
}
}
@Override
public synchronized List getAllAuthsByIp(final String ip) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- List result;
try {
- result = executor.submit(new Callable>() {
-
+ return exec.submit(new Callable>() {
public List call() throws Exception {
return database.getAllAuthsByIp(ip);
}
}).get();
- } catch (InterruptedException e1) {
- return new ArrayList();
- } catch (ExecutionException e1) {
- return new ArrayList();
- } finally {
- executor.shutdown();
- }
- try {
- return result;
} catch (Exception e) {
- return (new ArrayList());
+ return new ArrayList<>();
}
}
@Override
public synchronized List getAllAuthsByEmail(final String email) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- List result;
try {
- result = executor.submit(new Callable>() {
-
+ return exec.submit(new Callable>() {
public List call() throws Exception {
return database.getAllAuthsByEmail(email);
}
}).get();
- } catch (InterruptedException e1) {
- return new ArrayList();
- } catch (ExecutionException e1) {
- return new ArrayList();
- } finally {
- executor.shutdown();
- }
- try {
- return result;
} catch (Exception e) {
- return (new ArrayList());
+ return new ArrayList<>();
}
}
@Override
public synchronized boolean updateEmail(final PlayerAuth auth) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Boolean result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public Boolean call() throws Exception {
return database.updateEmail(auth);
}
}).get();
- } catch (InterruptedException e1) {
- return false;
- } catch (ExecutionException e1) {
- return false;
- } finally {
- executor.shutdown();
- }
- try {
- return result.booleanValue();
} catch (Exception e) {
- return (false);
+ return false;
}
}
@Override
public synchronized boolean updateSalt(final PlayerAuth auth) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Boolean result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public Boolean call() throws Exception {
return database.updateSalt(auth);
}
}).get();
- } catch (InterruptedException e1) {
- return false;
- } catch (ExecutionException e1) {
- return false;
- } finally {
- executor.shutdown();
- }
- try {
- return result.booleanValue();
} catch (Exception e) {
- return (false);
+ return false;
}
}
@Override
public synchronized void close() {
- database.close();
+ try {
+ exec.shutdown();
+ exec.awaitTermination(10, TimeUnit.SECONDS);
+ database.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
}
@Override
@@ -405,8 +231,6 @@ public class DatabaseCalls implements DataSource {
@Override
public synchronized void purgeBanned(final List banned) {
new Thread(new Runnable() {
-
- @Override
public synchronized void run() {
database.purgeBanned(banned);
}
@@ -420,139 +244,90 @@ public class DatabaseCalls implements DataSource {
@Override
public synchronized boolean isLogged(final String user) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Boolean result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public Boolean call() throws Exception {
return database.isLogged(user);
}
}).get();
- } catch (InterruptedException e1) {
- return false;
- } catch (ExecutionException e1) {
- return false;
- } finally {
- executor.shutdown();
- }
- try {
- return result.booleanValue();
} catch (Exception e) {
- return (false);
+ return false;
}
}
@Override
public synchronized void setLogged(final String user) {
- new Thread(new Runnable() {
-
- @Override
+ exec.execute(new Runnable() {
public synchronized void run() {
database.setLogged(user);
}
- }).start();
+ });
}
@Override
public synchronized void setUnlogged(final String user) {
- new Thread(new Runnable() {
-
- @Override
+ exec.execute(new Runnable() {
public synchronized void run() {
database.setUnlogged(user);
}
- }).start();
+ });
}
@Override
public synchronized void purgeLogged() {
- new Thread(new Runnable() {
-
- @Override
+ exec.execute(new Runnable() {
public synchronized void run() {
database.purgeLogged();
}
- }).start();
+ });
}
@Override
public synchronized int getAccountsRegistered() {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Integer result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public Integer call() throws Exception {
return database.getAccountsRegistered();
}
}).get();
- } catch (InterruptedException e1) {
- return 0;
- } catch (ExecutionException e1) {
- return 0;
- } finally {
- executor.shutdown();
- }
- try {
- return result.intValue();
} catch (Exception e) {
- return (0);
+ return -1;
}
}
@Override
- public synchronized void updateName(final String oldone,
- final String newone) {
- new Thread(new Runnable() {
-
- @Override
+ public synchronized void updateName(final String oldone, final String newone) {
+ exec.execute(new Runnable() {
public synchronized void run() {
database.updateName(oldone, newone);
}
- }).start();
+ });
}
@Override
public synchronized List getAllAuths() {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- List result;
try {
- result = executor.submit(new Callable>() {
-
+ return exec.submit(new Callable>() {
public List call() throws Exception {
return database.getAllAuths();
}
}).get();
- } catch (InterruptedException e1) {
- return (new ArrayList());
- } catch (ExecutionException e1) {
- return (new ArrayList());
- } finally {
- executor.shutdown();
+ } catch (Exception e) {
+ return new ArrayList<>();
}
- return result;
}
@Override
public List getLoggedPlayers() {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- List result;
try {
- result = executor.submit(new Callable>() {
-
+ return exec.submit(new Callable>() {
public List call() throws Exception {
return database.getLoggedPlayers();
}
}).get();
- } catch (InterruptedException e1) {
- return (new ArrayList());
- } catch (ExecutionException e1) {
- return (new ArrayList());
- } finally {
- executor.shutdown();
+ } catch (Exception e) {
+ return new ArrayList<>();
}
- return result;
}
}
diff --git a/src/main/java/fr/xephi/authme/datasource/FlatFile.java b/src/main/java/fr/xephi/authme/datasource/FlatFile.java
index 2b54e4df..22fee78c 100644
--- a/src/main/java/fr/xephi/authme/datasource/FlatFile.java
+++ b/src/main/java/fr/xephi/authme/datasource/FlatFile.java
@@ -1,21 +1,15 @@
package fr.xephi.authme.datasource;
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.settings.Settings;
+import java.io.*;
+import java.util.ArrayList;
+import java.util.List;
+
public class FlatFile implements DataSource {
/*
@@ -32,7 +26,7 @@ public class FlatFile implements DataSource {
private File source;
public FlatFile() {
- source = new File(Settings.AUTH_FILE);
+ source = Settings.AUTH_FILE;
try {
source.createNewFile();
} catch (IOException e) {
@@ -41,9 +35,10 @@ public class FlatFile implements DataSource {
ConsoleLogger.showError("Can't use FLAT FILE... SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
}
- if (!Settings.isStopEnabled)
+ if (!Settings.isStopEnabled) {
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
- return;
+ }
+ e.printStackTrace();
}
}
@@ -108,7 +103,7 @@ public class FlatFile implements DataSource {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(source));
- String line = "";
+ String line;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args[0].equals(auth.getNickname())) {
@@ -167,7 +162,7 @@ public class FlatFile implements DataSource {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(source));
- String line = "";
+ String line;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args[0].equalsIgnoreCase(auth.getNickname())) {
@@ -226,7 +221,7 @@ public class FlatFile implements DataSource {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(source));
- String line = "";
+ String line;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args[0].equalsIgnoreCase(auth.getNickname())) {
diff --git a/src/main/java/fr/xephi/authme/datasource/MySQL.java b/src/main/java/fr/xephi/authme/datasource/MySQL.java
index 1588ac6b..8e5d4cc1 100644
--- a/src/main/java/fr/xephi/authme/datasource/MySQL.java
+++ b/src/main/java/fr/xephi/authme/datasource/MySQL.java
@@ -1,25 +1,18 @@
package fr.xephi.authme.datasource;
-import java.sql.Blob;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.TimeoutException;
-
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.pool.PoolInitializationException;
-
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.security.HashAlgorithm;
import fr.xephi.authme.settings.Settings;
+import java.sql.*;
+import java.util.ArrayList;
+import java.util.List;
+
public class MySQL implements DataSource {
private String host;
@@ -44,8 +37,9 @@ public class MySQL implements DataSource {
private List columnOthers;
private HikariDataSource ds;
private String columnRealName;
+ private int maxConnections;
- public MySQL() {
+ public MySQL() throws ClassNotFoundException, SQLException, PoolInitializationException {
this.host = Settings.getMySQLHost;
this.port = Settings.getMySQLPort;
this.username = Settings.getMySQLUsername;
@@ -67,73 +61,78 @@ public class MySQL implements DataSource {
this.columnID = Settings.getMySQLColumnId;
this.columnLogged = Settings.getMySQLColumnLogged;
this.columnRealName = Settings.getMySQLColumnRealName;
+ this.maxConnections = Settings.getMySQLMaxConnections;
+
+ // Set the connection arguments (and check if connection is ok)
try {
- this.connect();
- this.setup();
- } catch (ClassNotFoundException e) {
- ConsoleLogger.showError(e.getMessage());
- if (Settings.isStopEnabled) {
- ConsoleLogger.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN...");
- AuthMe.getInstance().getServer().shutdown();
+ this.setConnectionArguments();
+ } catch (RuntimeException e) {
+ if (e instanceof IllegalArgumentException) {
+ ConsoleLogger.showError("Invalid database arguments! Please check your configuration!");
+ ConsoleLogger.showError("If this error persists, please report it to the developer! SHUTDOWN...");
+ throw new IllegalArgumentException(e);
}
- if (!Settings.isStopEnabled)
- AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
- return;
+ if (e instanceof PoolInitializationException) {
+ ConsoleLogger.showError("Can't initialize database connection! Please check your configuration!");
+ ConsoleLogger.showError("If this error persists, please report it to the developer! SHUTDOWN...");
+ throw new PoolInitializationException(e);
+ }
+ ConsoleLogger.showError("Can't use the Hikari Connection Pool! Please, report this error to the developer! SHUTDOWN...");
+ throw e;
+ }
+
+ // Initialize the database
+ try {
+ this.setupConnection();
} catch (SQLException e) {
- ConsoleLogger.showError(e.getMessage());
- if (Settings.isStopEnabled) {
- ConsoleLogger.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN...");
- AuthMe.getInstance().getServer().shutdown();
- }
- if (!Settings.isStopEnabled)
- AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
- return;
- } catch (TimeoutException e) {
- ConsoleLogger.showError(e.getMessage());
- if (Settings.isStopEnabled) {
- ConsoleLogger.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN...");
- AuthMe.getInstance().getServer().shutdown();
- }
- if (!Settings.isStopEnabled)
- AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
- return;
- } catch (PoolInitializationException e) {
- ConsoleLogger.showError(e.getMessage());
- if (Settings.isStopEnabled) {
- ConsoleLogger.showError("Can't use MySQL... Please input correct MySQL informations ! SHUTDOWN...");
- AuthMe.getInstance().getServer().shutdown();
- }
- if (!Settings.isStopEnabled)
- AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
- return;
+ this.close();
+ ConsoleLogger.showError("Can't initialize the MySQL database... Please check your database settings in the config.yml file! SHUTDOWN...");
+ ConsoleLogger.showError("If this error persists, please report it to the developer! SHUTDOWN...");
+ throw e;
}
}
- private synchronized void connect()
- throws ClassNotFoundException, SQLException, TimeoutException,
- NumberFormatException, PoolInitializationException {
+ private synchronized void setConnectionArguments()
+ throws ClassNotFoundException, IllegalArgumentException {
HikariConfig config = new HikariConfig();
+ config.setPoolName("AuthMeMYSQLPool");
config.setDriverClassName("com.mysql.jdbc.Driver");
config.setJdbcUrl("jdbc:mysql://" + this.host + ":" + this.port + "/" + this.database);
config.setUsername(this.username);
config.setPassword(this.password);
- config.setPoolName("AuthMeMYSQLPool");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
- config.addDataSourceProperty("autoReconnect", true);
- config.setMaxLifetime(30000);
- config.setInitializationFailFast(false);
+ config.addDataSourceProperty("autoReconnect", false);
+ config.setInitializationFailFast(true); // Don't start the plugin if the database is unavariable
+ config.setMaxLifetime(180000); // 3 Min
+ config.setIdleTimeout(60000); // 1 Min
+ config.setMaximumPoolSize(maxConnections);
ds = new HikariDataSource(config);
- ConsoleLogger.info("Connection pool ready");
+ ConsoleLogger.info("Connection arguments loaded, Hikari ConnectionPool ready!");
}
- private synchronized void setup() throws SQLException {
+ private synchronized void reloadArguments()
+ throws ClassNotFoundException, IllegalArgumentException {
+ if (ds != null) {
+ ds.close();
+ }
+ setConnectionArguments();
+ ConsoleLogger.info("Hikari ConnectionPool arguments reloaded!");
+ }
+
+ private synchronized Connection getConnection() throws SQLException {
+ Connection con;
+ con = ds.getConnection();
+ return con;
+ }
+
+ private synchronized void setupConnection() throws SQLException {
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
st = con.createStatement();
st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " (" + columnID + " INTEGER AUTO_INCREMENT," + columnName + " VARCHAR(255) NOT NULL UNIQUE," + columnPassword + " VARCHAR(255) NOT NULL," + columnIp + " VARCHAR(40) NOT NULL DEFAULT '127.0.0.1'," + columnLastLogin + " BIGINT NOT NULL DEFAULT '" + System.currentTimeMillis() + "'," + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT '" + Settings.defaultWorld + "'," + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com'," + columnLogged + " SMALLINT NOT NULL DEFAULT '0'," + "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + "));");
rs = con.getMetaData().getColumns(null, null, tableName, columnPassword);
@@ -185,6 +184,7 @@ public class MySQL implements DataSource {
close(st);
close(con);
}
+ ConsoleLogger.info("MySQL Setup finished");
}
@Override
@@ -193,7 +193,7 @@ public class MySQL implements DataSource {
PreparedStatement pst = null;
ResultSet rs = null;
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=LOWER(?);");
pst.setString(1, user);
rs = pst.executeQuery();
@@ -208,16 +208,15 @@ public class MySQL implements DataSource {
}
}
- @SuppressWarnings("resource")
@Override
public synchronized PlayerAuth getAuth(String user) {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
PlayerAuth pAuth = null;
- int id = -1;
+ int id;
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=LOWER(?);");
pst.setString(1, user);
rs = pst.executeQuery();
@@ -229,13 +228,15 @@ public class MySQL implements DataSource {
if (!columnSalt.isEmpty()) {
if (!columnGroup.isEmpty())
pAuth = new PlayerAuth(rs.getString(columnName).toLowerCase(), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
- else pAuth = new PlayerAuth(rs.getString(columnName).toLowerCase(), rs.getString(columnPassword), rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
+ else
+ pAuth = new PlayerAuth(rs.getString(columnName).toLowerCase(), rs.getString(columnPassword), rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} else {
pAuth = new PlayerAuth(rs.getString(columnName).toLowerCase(), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
}
}
if (Settings.getPasswordHash == HashAlgorithm.XENFORO) {
rs.close();
+ pst.close();
pst = con.prepareStatement("SELECT * FROM xf_user_authenticate WHERE " + columnID + "=?;");
pst.setInt(1, id);
rs = pst.executeQuery();
@@ -263,8 +264,9 @@ public class MySQL implements DataSource {
public synchronized boolean saveAuth(PlayerAuth auth) {
Connection con = null;
PreparedStatement pst = null;
+ ResultSet rs = null;
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
if ((columnSalt == null || columnSalt.isEmpty()) || (auth.getSalt() == null || auth.getSalt().isEmpty())) {
pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + columnRealName + ") VALUES (?,?,?,?,?);");
pst.setString(1, auth.getNickname());
@@ -295,13 +297,11 @@ public class MySQL implements DataSource {
}
}
if (Settings.getPasswordHash == HashAlgorithm.PHPBB) {
- int id;
- ResultSet rs = null;
PreparedStatement pst2 = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;");
pst2.setString(1, auth.getNickname());
rs = pst2.executeQuery();
if (rs.next()) {
- id = rs.getInt(columnID);
+ int id = rs.getInt(columnID);
// Insert player in phpbb_user_group
pst = con.prepareStatement("INSERT INTO " + Settings.getPhpbbPrefix + "user_group (group_id, user_id, group_leader, user_pending) VALUES (?,?,?,?);");
pst.setInt(1, Settings.getPhpbbGroup);
@@ -341,16 +341,15 @@ public class MySQL implements DataSource {
pst.executeUpdate();
pst.close();
}
+ rs.close();
pst2.close();
}
if (Settings.getPasswordHash == HashAlgorithm.WORDPRESS) {
- int id;
- ResultSet rs = null;
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;");
pst.setString(1, auth.getNickname());
rs = pst.executeQuery();
if (rs.next()) {
- id = rs.getInt(columnID);
+ int id = rs.getInt(columnID);
// First Name
pst = con.prepareStatement("INSERT INTO " + Settings.getWordPressPrefix + "usermeta (user_id, meta_key, meta_value) VALUES (?,?,?);");
pst.setInt(1, id);
@@ -436,15 +435,14 @@ public class MySQL implements DataSource {
pst.executeUpdate();
pst.close();
}
+ rs.close();
}
if (Settings.getPasswordHash == HashAlgorithm.XENFORO) {
- int id;
- ResultSet rs = null;
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?;");
pst.setString(1, auth.getNickname());
rs = pst.executeQuery();
if (rs.next()) {
- id = rs.getInt(columnID);
+ int id = rs.getInt(columnID);
// Insert password in the correct table
pst = con.prepareStatement("INSERT INTO xf_user_authenticate (user_id, scheme_class, data) VALUES (?,?,?);");
pst.setInt(1, id);
@@ -455,13 +453,13 @@ public class MySQL implements DataSource {
pst.setBlob(3, blob);
pst.executeUpdate();
}
- if (rs != null && !rs.isClosed())
- rs.close();
+ rs.close();
}
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
+ close(rs);
close(pst);
close(con);
}
@@ -472,21 +470,20 @@ public class MySQL implements DataSource {
public synchronized boolean updatePassword(PlayerAuth auth) {
Connection con = null;
PreparedStatement pst = null;
+ ResultSet rs = null;
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnPassword + "=? WHERE LOWER(" + columnName + ")=?;");
pst.setString(1, auth.getHash());
pst.setString(2, auth.getNickname());
pst.executeUpdate();
pst.close();
if (Settings.getPasswordHash == HashAlgorithm.XENFORO) {
- int id;
- ResultSet rs = null;
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;");
pst.setString(1, auth.getNickname());
rs = pst.executeQuery();
if (rs.next()) {
- id = rs.getInt(columnID);
+ int id = rs.getInt(columnID);
// Insert password in the correct table
pst = con.prepareStatement("UPDATE xf_user_authenticate SET data=? WHERE " + columnID + "=?;");
byte[] bytes = auth.getHash().getBytes();
@@ -500,13 +497,13 @@ public class MySQL implements DataSource {
pst.setInt(2, id);
pst.executeUpdate();
}
- if (rs != null && !rs.isClosed())
- rs.close();
+ rs.close();
}
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
+ close(rs);
close(pst);
close(con);
}
@@ -518,7 +515,7 @@ public class MySQL implements DataSource {
Connection con = null;
PreparedStatement pst = null;
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnIp + "=?, " + columnLastLogin + "=?, " + columnRealName + "=? WHERE LOWER(" + columnName + ")=?;");
pst.setString(1, auth.getIp());
pst.setLong(2, auth.getLastLogin());
@@ -540,7 +537,7 @@ public class MySQL implements DataSource {
Connection con = null;
PreparedStatement pst = null;
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + ";");
pst.setLong(1, until);
return pst.executeUpdate();
@@ -558,9 +555,9 @@ public class MySQL implements DataSource {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
- List list = new ArrayList();
+ List list = new ArrayList<>();
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + ";");
pst.setLong(1, until);
rs = pst.executeQuery();
@@ -574,7 +571,7 @@ public class MySQL implements DataSource {
return list;
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
- return new ArrayList();
+ return new ArrayList<>();
} finally {
close(rs);
close(pst);
@@ -587,10 +584,10 @@ public class MySQL implements DataSource {
Connection con = null;
PreparedStatement pst = null;
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
if (Settings.getPasswordHash == HashAlgorithm.XENFORO) {
int id;
- ResultSet rs = null;
+ ResultSet rs;
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;");
pst.setString(1, user);
rs = pst.executeQuery();
@@ -623,7 +620,7 @@ public class MySQL implements DataSource {
Connection con = null;
PreparedStatement pst = null;
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + lastlocX + " =?, " + lastlocY + "=?, " + lastlocZ + "=?, " + lastlocWorld + "=? WHERE LOWER(" + columnName + ")=?;");
pst.setDouble(1, auth.getQuitLocX());
pst.setDouble(2, auth.getQuitLocY());
@@ -648,7 +645,7 @@ public class MySQL implements DataSource {
ResultSet rs = null;
int countIp = 0;
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
pst.setString(1, ip);
rs = pst.executeQuery();
@@ -671,7 +668,7 @@ public class MySQL implements DataSource {
Connection con = null;
PreparedStatement pst = null;
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnEmail + " =? WHERE LOWER(" + columnName + ")=?;");
pst.setString(1, auth.getEmail());
pst.setString(2, auth.getNickname());
@@ -694,7 +691,7 @@ public class MySQL implements DataSource {
Connection con = null;
PreparedStatement pst = null;
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnSalt + " =? WHERE LOWER(" + columnName + ")=?;");
pst.setString(1, auth.getSalt());
pst.setString(2, auth.getNickname());
@@ -709,23 +706,14 @@ public class MySQL implements DataSource {
return true;
}
- @Override
- public synchronized void close() {
- try {
- if (ds != null)
- ds.close();
- } catch (Exception e) {
- }
- }
-
@Override
public void reload() {
try {
- reconnect(true);
+ reloadArguments();
} catch (Exception e) {
ConsoleLogger.showError(e.getMessage());
+ ConsoleLogger.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN...");
if (Settings.isStopEnabled) {
- ConsoleLogger.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
}
if (!Settings.isStopEnabled)
@@ -733,30 +721,16 @@ public class MySQL implements DataSource {
}
}
- private void close(Statement st) {
- if (st != null) {
- try {
- st.close();
- } catch (Exception ex) {
- ConsoleLogger.showError(ex.getMessage());
- }
- }
+ @Override
+ public synchronized void close() {
+ if (ds != null)
+ ds.close();
}
- private void close(ResultSet rs) {
- if (rs != null) {
+ private void close(AutoCloseable o) {
+ if (o != null) {
try {
- rs.close();
- } catch (Exception ex) {
- ConsoleLogger.showError(ex.getMessage());
- }
- }
- }
-
- private void close(Connection con) {
- if (con != null) {
- try {
- con.close();
+ o.close();
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
}
@@ -768,9 +742,9 @@ public class MySQL implements DataSource {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
- List countIp = new ArrayList();
+ List countIp = new ArrayList<>();
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
pst.setString(1, auth.getIp());
rs = pst.executeQuery();
@@ -780,7 +754,7 @@ public class MySQL implements DataSource {
return countIp;
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
- return new ArrayList();
+ return new ArrayList<>();
} finally {
close(rs);
close(pst);
@@ -793,9 +767,9 @@ public class MySQL implements DataSource {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
- List countIp = new ArrayList();
+ List countIp = new ArrayList<>();
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
pst.setString(1, ip);
rs = pst.executeQuery();
@@ -805,7 +779,7 @@ public class MySQL implements DataSource {
return countIp;
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
- return new ArrayList();
+ return new ArrayList<>();
} finally {
close(rs);
close(pst);
@@ -818,9 +792,9 @@ public class MySQL implements DataSource {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
- List countEmail = new ArrayList();
+ List countEmail = new ArrayList<>();
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnEmail + "=?;");
pst.setString(1, email);
rs = pst.executeQuery();
@@ -830,7 +804,7 @@ public class MySQL implements DataSource {
return countEmail;
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
- return new ArrayList();
+ return new ArrayList<>();
} finally {
close(rs);
close(pst);
@@ -844,7 +818,7 @@ public class MySQL implements DataSource {
PreparedStatement pst = null;
try {
for (String name : banned) {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;");
pst.setString(1, name);
pst.executeUpdate();
@@ -857,75 +831,6 @@ public class MySQL implements DataSource {
}
}
- private synchronized Connection makeSureConnectionIsReady() {
- Connection con = null;
- try {
- con = ds.getConnection();
- } catch (Exception te) {
- try {
- con = null;
- reconnect(false);
- } catch (Exception e) {
- ConsoleLogger.showError(e.getMessage());
- if (Settings.isStopEnabled) {
- ConsoleLogger.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN...");
- AuthMe.getInstance().getServer().shutdown();
- }
- if (!Settings.isStopEnabled)
- AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
- }
- } catch (AssertionError ae) {
- // Make sure assertionerror is caused by the connectionpoolmanager,
- // else re-throw it
- if (!ae.getMessage().equalsIgnoreCase("AuthMeDatabaseError"))
- throw new AssertionError(ae.getMessage());
- try {
- con = null;
- reconnect(false);
- } catch (Exception e) {
- ConsoleLogger.showError(e.getMessage());
- if (Settings.isStopEnabled) {
- ConsoleLogger.showError("Can't reconnect to MySQL database... Please check your MySQL informations ! SHUTDOWN...");
- AuthMe.getInstance().getServer().shutdown();
- }
- if (!Settings.isStopEnabled)
- AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
- }
- }
- while (con == null)
- try {
- con = ds.getConnection();
- } catch (Exception e) {
- try {
- reconnect(false);
- con = ds.getConnection();
- } catch (Exception ex) {
- }
- }
- return con;
- }
-
- private synchronized void reconnect(boolean reload)
- throws ClassNotFoundException, SQLException, TimeoutException,
- PoolInitializationException {
- if (ds != null)
- ds.close();
- HikariConfig config = new HikariConfig();
- config.setJdbcUrl("jdbc:mysql://" + this.host + ":" + this.port + "/" + this.database);
- config.setUsername(this.username);
- config.setPassword(this.password);
- config.addDataSourceProperty("cachePrepStmts", "true");
- config.addDataSourceProperty("prepStmtCacheSize", "250");
- config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
- config.addDataSourceProperty("autoReconnect", true);
- config.setInitializationFailFast(false);
- config.setMaxLifetime(12000);
- config.setPoolName("AuthMeMYSQLPool");
- ds = new HikariDataSource(config);
- if (!reload)
- ConsoleLogger.info("ConnectionPool was unavailable... Reconnected!");
- }
-
@Override
public DataSourceType getType() {
return DataSourceType.MYSQL;
@@ -937,7 +842,7 @@ public class MySQL implements DataSource {
PreparedStatement pst = null;
ResultSet rs = null;
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;");
pst.setString(1, user);
rs = pst.executeQuery();
@@ -959,19 +864,17 @@ public class MySQL implements DataSource {
Connection con = null;
PreparedStatement pst = null;
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE LOWER(" + columnName + ")=?;");
pst.setInt(1, 1);
pst.setString(2, user);
pst.executeUpdate();
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
- return;
} finally {
close(pst);
close(con);
}
- return;
}
@Override
@@ -980,19 +883,17 @@ public class MySQL implements DataSource {
PreparedStatement pst = null;
if (user != null)
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE LOWER(" + columnName + ")=?;");
pst.setInt(1, 0);
pst.setString(2, user);
pst.executeUpdate();
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
- return;
} finally {
close(pst);
close(con);
}
- return;
}
@Override
@@ -1000,19 +901,17 @@ public class MySQL implements DataSource {
Connection con = null;
PreparedStatement pst = null;
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE " + columnLogged + "=?;");
pst.setInt(1, 0);
pst.setInt(2, 1);
pst.executeUpdate();
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
- return;
} finally {
close(pst);
close(con);
}
- return;
}
@Override
@@ -1020,9 +919,9 @@ public class MySQL implements DataSource {
int result = 0;
Connection con = null;
PreparedStatement pst = null;
- ResultSet rs = null;
+ ResultSet rs;
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("SELECT COUNT(*) FROM " + tableName + ";");
rs = pst.executeQuery();
if (rs != null && rs.next()) {
@@ -1043,33 +942,31 @@ public class MySQL implements DataSource {
Connection con = null;
PreparedStatement pst = null;
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnName + "=? WHERE LOWER(" + columnName + ")=?;");
pst.setString(1, newone);
pst.setString(2, oldone);
pst.executeUpdate();
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
- return;
} finally {
close(pst);
close(con);
}
- return;
}
@Override
public List getAllAuths() {
- List auths = new ArrayList();
+ List auths = new ArrayList<>();
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + ";");
rs = pst.executeQuery();
while (rs.next()) {
- PlayerAuth pAuth = null;
+ PlayerAuth pAuth;
int id = rs.getInt(columnID);
if (rs.getString(columnIp).isEmpty() && rs.getString(columnIp) != null) {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "192.168.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
@@ -1077,13 +974,14 @@ public class MySQL implements DataSource {
if (!columnSalt.isEmpty()) {
if (!columnGroup.isEmpty())
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
- else pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
+ else
+ pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} else {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
}
}
if (Settings.getPasswordHash == HashAlgorithm.XENFORO) {
- ResultSet rsid = null;
+ ResultSet rsid;
pst = con.prepareStatement("SELECT * FROM xf_user_authenticate WHERE " + columnID + "=?;");
pst.setInt(1, id);
rsid = pst.executeQuery();
@@ -1092,11 +990,9 @@ public class MySQL implements DataSource {
byte[] bytes = blob.getBytes(1, (int) blob.length());
pAuth.setHash(new String(bytes));
}
- if (rsid != null)
- rsid.close();
+ rsid.close();
}
- if (pAuth != null)
- auths.add(pAuth);
+ auths.add(pAuth);
}
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
@@ -1111,16 +1007,16 @@ public class MySQL implements DataSource {
@Override
public List getLoggedPlayers() {
- List auths = new ArrayList();
+ List auths = new ArrayList<>();
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
- con = makeSureConnectionIsReady();
+ con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLogged + "=1;");
rs = pst.executeQuery();
while (rs.next()) {
- PlayerAuth pAuth = null;
+ PlayerAuth pAuth;
int id = rs.getInt(columnID);
if (rs.getString(columnIp).isEmpty() && rs.getString(columnIp) != null) {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "192.168.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
@@ -1128,13 +1024,14 @@ public class MySQL implements DataSource {
if (!columnSalt.isEmpty()) {
if (!columnGroup.isEmpty())
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
- else pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
+ else
+ pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} else {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
}
}
if (Settings.getPasswordHash == HashAlgorithm.XENFORO) {
- ResultSet rsid = null;
+ ResultSet rsid;
pst = con.prepareStatement("SELECT * FROM xf_user_authenticate WHERE " + columnID + "=?;");
pst.setInt(1, id);
rsid = pst.executeQuery();
@@ -1143,11 +1040,9 @@ public class MySQL implements DataSource {
byte[] bytes = blob.getBytes(1, (int) blob.length());
pAuth.setHash(new String(bytes));
}
- if (rsid != null)
- rsid.close();
+ rsid.close();
}
- if (pAuth != null)
- auths.add(pAuth);
+ auths.add(pAuth);
}
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
diff --git a/src/main/java/fr/xephi/authme/datasource/SQLite.java b/src/main/java/fr/xephi/authme/datasource/SQLite.java
index a465ddd7..466dbe7f 100644
--- a/src/main/java/fr/xephi/authme/datasource/SQLite.java
+++ b/src/main/java/fr/xephi/authme/datasource/SQLite.java
@@ -1,19 +1,13 @@
package fr.xephi.authme.datasource;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.ArrayList;
-import java.util.List;
-
-import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.settings.Settings;
+import java.sql.*;
+import java.util.ArrayList;
+import java.util.List;
+
public class SQLite implements DataSource {
private String database;
@@ -34,7 +28,7 @@ public class SQLite implements DataSource {
private String columnLogged;
private String columnRealName;
- public SQLite() {
+ public SQLite() throws ClassNotFoundException, SQLException {
this.database = Settings.getMySQLDatabase;
this.tableName = Settings.getMySQLTablename;
this.columnName = Settings.getMySQLColumnName;
@@ -55,29 +49,13 @@ public class SQLite implements DataSource {
try {
this.connect();
this.setup();
- } catch (ClassNotFoundException e) {
- ConsoleLogger.showError(e.getMessage());
- if (Settings.isStopEnabled) {
- ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN...");
- AuthMe.getInstance().getServer().shutdown();
- }
- if (!Settings.isStopEnabled)
- AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
- return;
- } catch (SQLException e) {
- ConsoleLogger.showError(e.getMessage());
- if (Settings.isStopEnabled) {
- ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN...");
- AuthMe.getInstance().getServer().shutdown();
- }
- if (!Settings.isStopEnabled)
- AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
- return;
+ } catch (ClassNotFoundException | SQLException cnf) {
+ ConsoleLogger.showError("Can't use SQLITE... !");
+ throw cnf;
}
}
- private synchronized void connect()
- throws ClassNotFoundException, SQLException {
+ private synchronized void connect() throws ClassNotFoundException, SQLException {
Class.forName("org.sqlite.JDBC");
ConsoleLogger.info("SQLite driver loaded");
this.con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/" + database + ".db");
@@ -273,7 +251,7 @@ public class SQLite implements DataSource {
public List autoPurgeDatabase(long until) {
PreparedStatement pst = null;
ResultSet rs = null;
- List list = new ArrayList();
+ List list = new ArrayList<>();
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + ";");
pst.setLong(1, until);
@@ -284,7 +262,7 @@ public class SQLite implements DataSource {
return list;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
- return new ArrayList();
+ return new ArrayList<>();
} finally {
close(rs);
close(pst);
@@ -423,7 +401,7 @@ public class SQLite implements DataSource {
public List getAllAuthsByName(PlayerAuth auth) {
PreparedStatement pst = null;
ResultSet rs = null;
- List countIp = new ArrayList();
+ List countIp = new ArrayList<>();
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
pst.setString(1, auth.getIp());
@@ -434,9 +412,9 @@ public class SQLite implements DataSource {
return countIp;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
- return new ArrayList();
+ return new ArrayList<>();
} catch (NullPointerException npe) {
- return new ArrayList();
+ return new ArrayList<>();
} finally {
close(rs);
close(pst);
@@ -447,7 +425,7 @@ public class SQLite implements DataSource {
public List getAllAuthsByIp(String ip) {
PreparedStatement pst = null;
ResultSet rs = null;
- List countIp = new ArrayList();
+ List countIp = new ArrayList<>();
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
pst.setString(1, ip);
@@ -458,9 +436,9 @@ public class SQLite implements DataSource {
return countIp;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
- return new ArrayList();
+ return new ArrayList<>();
} catch (NullPointerException npe) {
- return new ArrayList();
+ return new ArrayList<>();
} finally {
close(rs);
close(pst);
@@ -471,7 +449,7 @@ public class SQLite implements DataSource {
public List getAllAuthsByEmail(String email) {
PreparedStatement pst = null;
ResultSet rs = null;
- List countEmail = new ArrayList();
+ List countEmail = new ArrayList<>();
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnEmail + "=?;");
pst.setString(1, email);
@@ -482,9 +460,9 @@ public class SQLite implements DataSource {
return countEmail;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
- return new ArrayList();
+ return new ArrayList<>();
} catch (NullPointerException npe) {
- return new ArrayList();
+ return new ArrayList<>();
} finally {
close(rs);
close(pst);
@@ -542,11 +520,9 @@ public class SQLite implements DataSource {
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
- return;
} finally {
close(pst);
}
- return;
}
@Override
@@ -560,11 +536,9 @@ public class SQLite implements DataSource {
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
- return;
} finally {
close(pst);
}
- return;
}
@Override
@@ -577,18 +551,16 @@ public class SQLite implements DataSource {
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
- return;
} finally {
close(pst);
}
- return;
}
@Override
public int getAccountsRegistered() {
int result = 0;
PreparedStatement pst = null;
- ResultSet rs = null;
+ ResultSet rs;
try {
pst = con.prepareStatement("SELECT COUNT(*) FROM " + tableName + ";");
rs = pst.executeQuery();
@@ -614,23 +586,21 @@ public class SQLite implements DataSource {
pst.executeUpdate();
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
- return;
} finally {
close(pst);
}
- return;
}
@Override
public List getAllAuths() {
- List auths = new ArrayList();
+ List auths = new ArrayList<>();
PreparedStatement pst = null;
- ResultSet rs = null;
+ ResultSet rs;
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + ";");
rs = pst.executeQuery();
while (rs.next()) {
- PlayerAuth pAuth = null;
+ PlayerAuth pAuth;
if (rs.getString(columnIp).isEmpty()) {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "127.0.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} else {
@@ -640,8 +610,7 @@ public class SQLite implements DataSource {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
}
}
- if (pAuth != null)
- auths.add(pAuth);
+ auths.add(pAuth);
}
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
@@ -654,14 +623,14 @@ public class SQLite implements DataSource {
@Override
public List getLoggedPlayers() {
- List auths = new ArrayList();
+ List auths = new ArrayList<>();
PreparedStatement pst = null;
- ResultSet rs = null;
+ ResultSet rs;
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLogged + "=1;");
rs = pst.executeQuery();
while (rs.next()) {
- PlayerAuth pAuth = null;
+ PlayerAuth pAuth;
if (rs.getString(columnIp).isEmpty()) {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "127.0.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} else {
@@ -671,8 +640,7 @@ public class SQLite implements DataSource {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
}
}
- if (pAuth != null)
- auths.add(pAuth);
+ auths.add(pAuth);
}
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
diff --git a/src/main/java/fr/xephi/authme/datasource/SQLite_HIKARI.java b/src/main/java/fr/xephi/authme/datasource/SQLite_HIKARI.java
index 6f1350e3..d0b14026 100644
--- a/src/main/java/fr/xephi/authme/datasource/SQLite_HIKARI.java
+++ b/src/main/java/fr/xephi/authme/datasource/SQLite_HIKARI.java
@@ -1,23 +1,16 @@
package fr.xephi.authme.datasource;
-import java.io.EOFException;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
-
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.settings.Settings;
+import java.sql.*;
+import java.util.ArrayList;
+import java.util.List;
+
public class SQLite_HIKARI implements DataSource {
private String database;
@@ -38,7 +31,7 @@ public class SQLite_HIKARI implements DataSource {
private String columnLogged;
private String columnRealName;
- public SQLite_HIKARI() {
+ public SQLite_HIKARI() throws ClassNotFoundException, SQLException {
this.database = Settings.getMySQLDatabase;
this.tableName = Settings.getMySQLTablename;
this.columnName = Settings.getMySQLColumnName;
@@ -56,60 +49,57 @@ public class SQLite_HIKARI implements DataSource {
this.columnLogged = Settings.getMySQLColumnLogged;
this.columnRealName = Settings.getMySQLColumnRealName;
+ // Set the connection arguments
try {
- this.connect();
- this.setup();
- } catch (ClassNotFoundException e) {
- ConsoleLogger.showError(e.getMessage());
- if (Settings.isStopEnabled) {
- ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN...");
- AuthMe.getInstance().getServer().shutdown();
- }
- if (!Settings.isStopEnabled)
- AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
- return;
+ this.setConnectionArguments();
+ } catch (RuntimeException rt) {
+ ConsoleLogger.showError("Can't use the Hikari Connection Pool! Please, report this error to the developer!");
+ throw rt;
+ }
+
+ // Initialize the database
+ try {
+ this.setupConnection();
} catch (SQLException e) {
- ConsoleLogger.showError(e.getMessage());
- if (Settings.isStopEnabled) {
- ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN...");
- AuthMe.getInstance().getServer().shutdown();
- }
- if (!Settings.isStopEnabled)
- AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
- return;
- } catch (EOFException e) {
- ConsoleLogger.showError(e.getMessage());
- if (Settings.isStopEnabled) {
- ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN...");
- AuthMe.getInstance().getServer().shutdown();
- }
- if (!Settings.isStopEnabled)
- AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
- return;
+ this.close();
+ ConsoleLogger.showError("Can't initialize the SQLite database... Please check your database settings in the config.yml file! SHUTDOWN...");
+ ConsoleLogger.showError("If this error persists, please report it to the developer! SHUTDOWN...");
+ throw e;
}
}
- private Connection getConnection() throws SQLException, EOFException {
- return this.ds.getConnection();
+ @Override
+ public DataSourceType getType() {
+ return DataSourceType.SQLITEHIKARI;
}
- private synchronized void connect()
- throws ClassNotFoundException, SQLException, EOFException {
- /*
- * Class.forName("org.sqlite.JDBC"); ConsoleLogger.info(
- * "SQLite driver loaded"); this.con =
- * DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/" + database
- * + ".db");
- */
- Properties props = new Properties();
- props.setProperty("dataSourceClassName", "org.sqlite.SQLiteDataSource");
- HikariConfig config = new HikariConfig(props);
- config.setPoolName("AuthMeSQLiteLPool");
+ private synchronized void setConnectionArguments() throws RuntimeException {
+ HikariConfig config = new HikariConfig();
+ config.setPoolName("AuthMeSQLitePool");
+ config.setDriverClassName("org.sqlite.JDBC"); // RuntimeException
+ config.setJdbcUrl("jdbc:sqlite:plugins/AuthMe/" + database + ".db");
+ config.setConnectionTestQuery("SELECT 1");
+ config.setMaxLifetime(180000); // 3 Min
+ config.setIdleTimeout(60000); // 1 Min
+ config.setMaximumPoolSize(50); // 50 (including idle connections)
ds = new HikariDataSource(config);
- ConsoleLogger.info("Connection pool ready");
+ ConsoleLogger.info("Connection arguments loaded, Hikari ConnectionPool ready!");
}
- private synchronized void setup() throws SQLException, EOFException {
+ private synchronized void reloadArguments()
+ throws ClassNotFoundException, IllegalArgumentException {
+ if (ds != null) {
+ ds.close();
+ }
+ setConnectionArguments();
+ ConsoleLogger.info("Hikari ConnectionPool arguments reloaded!");
+ }
+
+ private synchronized Connection getConnection() throws SQLException {
+ return ds.getConnection();
+ }
+
+ private synchronized void setupConnection() throws SQLException {
Connection con = null;
Statement st = null;
ResultSet rs = null;
@@ -166,14 +156,6 @@ public class SQLite_HIKARI implements DataSource {
ConsoleLogger.info("SQLite Setup finished");
}
- private void close(Connection con) {
- try {
- if (con != null)
- con.close();
- } catch (Exception e) {
- }
- }
-
@Override
public synchronized boolean isAuthAvailable(String user) {
Connection con = null;
@@ -185,7 +167,7 @@ public class SQLite_HIKARI implements DataSource {
pst.setString(1, user);
rs = pst.executeQuery();
return rs.next();
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
@@ -218,7 +200,7 @@ public class SQLite_HIKARI implements DataSource {
} else {
return null;
}
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return null;
} finally {
@@ -230,8 +212,8 @@ public class SQLite_HIKARI implements DataSource {
@Override
public synchronized boolean saveAuth(PlayerAuth auth) {
- PreparedStatement pst = null;
Connection con = null;
+ PreparedStatement pst = null;
try {
con = getConnection();
if (columnSalt.isEmpty() && auth.getSalt().isEmpty()) {
@@ -252,7 +234,7 @@ public class SQLite_HIKARI implements DataSource {
pst.setString(6, auth.getRealName());
pst.executeUpdate();
}
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
@@ -272,7 +254,7 @@ public class SQLite_HIKARI implements DataSource {
pst.setString(1, auth.getHash());
pst.setString(2, auth.getNickname());
pst.executeUpdate();
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
@@ -294,7 +276,7 @@ public class SQLite_HIKARI implements DataSource {
pst.setString(3, auth.getRealName());
pst.setString(4, auth.getNickname());
pst.executeUpdate();
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
@@ -313,7 +295,7 @@ public class SQLite_HIKARI implements DataSource {
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + ";");
pst.setLong(1, until);
return pst.executeUpdate();
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return 0;
} finally {
@@ -327,7 +309,7 @@ public class SQLite_HIKARI implements DataSource {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
- List list = new ArrayList();
+ List list = new ArrayList<>();
try {
con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + ";");
@@ -337,9 +319,9 @@ public class SQLite_HIKARI implements DataSource {
list.add(rs.getString(columnName));
}
return list;
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
- return new ArrayList();
+ return new ArrayList<>();
} finally {
close(rs);
close(pst);
@@ -349,14 +331,14 @@ public class SQLite_HIKARI implements DataSource {
@Override
public synchronized boolean removeAuth(String user) {
- PreparedStatement pst = null;
Connection con = null;
+ PreparedStatement pst = null;
try {
con = getConnection();
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;");
pst.setString(1, user);
pst.executeUpdate();
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
@@ -368,8 +350,8 @@ public class SQLite_HIKARI implements DataSource {
@Override
public boolean updateQuitLoc(PlayerAuth auth) {
- PreparedStatement pst = null;
Connection con = null;
+ PreparedStatement pst = null;
try {
con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + lastlocX + "=?, " + lastlocY + "=?, " + lastlocZ + "=?, " + lastlocWorld + "=? WHERE " + columnName + "=?;");
@@ -379,7 +361,7 @@ public class SQLite_HIKARI implements DataSource {
pst.setString(4, auth.getWorld());
pst.setString(5, auth.getNickname());
pst.executeUpdate();
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
@@ -391,9 +373,9 @@ public class SQLite_HIKARI implements DataSource {
@Override
public int getIps(String ip) {
+ Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
- Connection con = null;
int countIp = 0;
try {
con = getConnection();
@@ -404,7 +386,7 @@ public class SQLite_HIKARI implements DataSource {
countIp++;
}
return countIp;
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return 0;
} finally {
@@ -416,15 +398,15 @@ public class SQLite_HIKARI implements DataSource {
@Override
public boolean updateEmail(PlayerAuth auth) {
- PreparedStatement pst = null;
Connection con = null;
+ PreparedStatement pst = null;
try {
con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnEmail + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getEmail());
pst.setString(2, auth.getNickname());
pst.executeUpdate();
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
@@ -447,7 +429,7 @@ public class SQLite_HIKARI implements DataSource {
pst.setString(1, auth.getSalt());
pst.setString(2, auth.getNickname());
pst.executeUpdate();
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
@@ -457,57 +439,12 @@ public class SQLite_HIKARI implements DataSource {
return true;
}
- @Override
- public synchronized void close() {
- try {
- if (ds != null)
- ds.close();
- } catch (Exception e) {
- }
- }
-
- @Override
- public void reload() {
- try {
- connect();
- setup();
- } catch (Exception e) {
- ConsoleLogger.showError(e.getMessage());
- if (Settings.isStopEnabled) {
- ConsoleLogger.showError("Can't reconnect to SQLite database... SHUTDOWN...");
- AuthMe.getInstance().getServer().shutdown();
- }
- if (!Settings.isStopEnabled)
- AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
- }
- }
-
- private void close(Statement st) {
- if (st != null) {
- try {
- st.close();
- } catch (SQLException ex) {
- ConsoleLogger.showError(ex.getMessage());
- }
- }
- }
-
- private void close(ResultSet rs) {
- if (rs != null) {
- try {
- rs.close();
- } catch (SQLException ex) {
- ConsoleLogger.showError(ex.getMessage());
- }
- }
- }
-
@Override
public List getAllAuthsByName(PlayerAuth auth) {
+ Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
- Connection con = null;
- List countIp = new ArrayList();
+ List countIp = new ArrayList<>();
try {
con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
@@ -517,11 +454,11 @@ public class SQLite_HIKARI implements DataSource {
countIp.add(rs.getString(columnName));
}
return countIp;
- } catch (NullPointerException ex) {
- return new ArrayList();
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
- return new ArrayList();
+ return new ArrayList<>();
+ } catch (NullPointerException npe) {
+ return new ArrayList<>();
} finally {
close(rs);
close(pst);
@@ -531,10 +468,10 @@ public class SQLite_HIKARI implements DataSource {
@Override
public List getAllAuthsByIp(String ip) {
+ Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
- Connection con = null;
- List countIp = new ArrayList();
+ List countIp = new ArrayList<>();
try {
con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;");
@@ -544,11 +481,11 @@ public class SQLite_HIKARI implements DataSource {
countIp.add(rs.getString(columnName));
}
return countIp;
- } catch (NullPointerException ex) {
- return new ArrayList();
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
- return new ArrayList();
+ return new ArrayList<>();
+ } catch (NullPointerException npe) {
+ return new ArrayList<>();
} finally {
close(rs);
close(pst);
@@ -558,10 +495,10 @@ public class SQLite_HIKARI implements DataSource {
@Override
public List getAllAuthsByEmail(String email) {
+ Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
- Connection con = null;
- List countEmail = new ArrayList();
+ List countEmail = new ArrayList<>();
try {
con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnEmail + "=?;");
@@ -571,11 +508,11 @@ public class SQLite_HIKARI implements DataSource {
countEmail.add(rs.getString(columnName));
}
return countEmail;
- } catch (NullPointerException ex) {
- return new ArrayList();
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
- return new ArrayList();
+ return new ArrayList<>();
+ } catch (NullPointerException npe) {
+ return new ArrayList<>();
} finally {
close(rs);
close(pst);
@@ -585,8 +522,8 @@ public class SQLite_HIKARI implements DataSource {
@Override
public void purgeBanned(List banned) {
- PreparedStatement pst = null;
Connection con = null;
+ PreparedStatement pst = null;
try {
con = getConnection();
for (String name : banned) {
@@ -594,7 +531,7 @@ public class SQLite_HIKARI implements DataSource {
pst.setString(1, name);
pst.executeUpdate();
}
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
} finally {
close(pst);
@@ -602,16 +539,11 @@ public class SQLite_HIKARI implements DataSource {
}
}
- @Override
- public DataSourceType getType() {
- return DataSourceType.SQLITE;
- }
-
@Override
public boolean isLogged(String user) {
+ Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
- Connection con = null;
try {
con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;");
@@ -619,7 +551,7 @@ public class SQLite_HIKARI implements DataSource {
rs = pst.executeQuery();
if (rs.next())
return (rs.getInt(columnLogged) == 1);
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
@@ -632,28 +564,26 @@ public class SQLite_HIKARI implements DataSource {
@Override
public void setLogged(String user) {
- PreparedStatement pst = null;
Connection con = null;
+ PreparedStatement pst = null;
try {
con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE LOWER(" + columnName + ")=?;");
pst.setInt(1, 1);
pst.setString(2, user);
pst.executeUpdate();
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
- return;
} finally {
close(pst);
close(con);
}
- return;
}
@Override
public void setUnlogged(String user) {
- PreparedStatement pst = null;
Connection con = null;
+ PreparedStatement pst = null;
if (user != null)
try {
con = getConnection();
@@ -661,42 +591,38 @@ public class SQLite_HIKARI implements DataSource {
pst.setInt(1, 0);
pst.setString(2, user);
pst.executeUpdate();
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
- return;
} finally {
close(pst);
close(con);
}
- return;
}
@Override
public void purgeLogged() {
- PreparedStatement pst = null;
Connection con = null;
+ PreparedStatement pst = null;
try {
con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnLogged + "=? WHERE " + columnLogged + "=?;");
pst.setInt(1, 0);
pst.setInt(2, 1);
pst.executeUpdate();
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
- return;
} finally {
close(pst);
close(con);
}
- return;
}
@Override
public int getAccountsRegistered() {
- int result = 0;
- PreparedStatement pst = null;
- ResultSet rs = null;
Connection con = null;
+ PreparedStatement pst = null;
+ ResultSet rs;
+ int result = 0;
try {
con = getConnection();
pst = con.prepareStatement("SELECT COUNT(*) FROM " + tableName + ";");
@@ -704,7 +630,7 @@ public class SQLite_HIKARI implements DataSource {
if (rs != null && rs.next()) {
result = rs.getInt(1);
}
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return result;
} finally {
@@ -716,36 +642,34 @@ public class SQLite_HIKARI implements DataSource {
@Override
public void updateName(String oldone, String newone) {
- PreparedStatement pst = null;
Connection con = null;
+ PreparedStatement pst = null;
try {
con = getConnection();
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnName + "=? WHERE " + columnName + "=?;");
pst.setString(1, newone);
pst.setString(2, oldone);
pst.executeUpdate();
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
- return;
} finally {
close(pst);
close(con);
}
- return;
}
@Override
public List getAllAuths() {
- List auths = new ArrayList();
- PreparedStatement pst = null;
- ResultSet rs = null;
Connection con = null;
+ PreparedStatement pst = null;
+ ResultSet rs;
+ List auths = new ArrayList<>();
try {
con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + ";");
rs = pst.executeQuery();
while (rs.next()) {
- PlayerAuth pAuth = null;
+ PlayerAuth pAuth;
if (rs.getString(columnIp).isEmpty()) {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "127.0.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} else {
@@ -755,10 +679,9 @@ public class SQLite_HIKARI implements DataSource {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
}
}
- if (pAuth != null)
- auths.add(pAuth);
+ auths.add(pAuth);
}
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return auths;
} finally {
@@ -770,16 +693,16 @@ public class SQLite_HIKARI implements DataSource {
@Override
public List getLoggedPlayers() {
- List auths = new ArrayList();
- PreparedStatement pst = null;
- ResultSet rs = null;
Connection con = null;
+ PreparedStatement pst = null;
+ ResultSet rs;
+ List auths = new ArrayList<>();
try {
con = getConnection();
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLogged + "=1;");
rs = pst.executeQuery();
while (rs.next()) {
- PlayerAuth pAuth = null;
+ PlayerAuth pAuth;
if (rs.getString(columnIp).isEmpty()) {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "127.0.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
} else {
@@ -789,16 +712,45 @@ public class SQLite_HIKARI implements DataSource {
pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName));
}
}
- if (pAuth != null)
- auths.add(pAuth);
+ auths.add(pAuth);
}
- } catch (Exception ex) {
+ } catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
- return auths;
} finally {
close(pst);
close(con);
}
return auths;
}
+
+ @Override
+ public void reload() {
+ try {
+ reloadArguments();
+ } catch (Exception e) {
+ ConsoleLogger.showError(e.getMessage());
+ ConsoleLogger.showError("Can't reconnect to SQLite database... Please check your SQLite informations ! SHUTDOWN...");
+ if (Settings.isStopEnabled) {
+ AuthMe.getInstance().getServer().shutdown();
+ }
+ if (!Settings.isStopEnabled)
+ AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
+ }
+ }
+
+ @Override
+ public synchronized void close() {
+ if (ds != null)
+ ds.close();
+ }
+
+ private void close(AutoCloseable o) {
+ if (o != null) {
+ try {
+ o.close();
+ } catch (Exception ex) {
+ ConsoleLogger.showError(ex.getMessage());
+ }
+ }
+ }
}
diff --git a/src/main/java/fr/xephi/authme/events/StoreInventoryEvent.java b/src/main/java/fr/xephi/authme/events/StoreInventoryEvent.java
index c91523d8..e8a78806 100644
--- a/src/main/java/fr/xephi/authme/events/StoreInventoryEvent.java
+++ b/src/main/java/fr/xephi/authme/events/StoreInventoryEvent.java
@@ -1,12 +1,11 @@
package fr.xephi.authme.events;
+import fr.xephi.authme.cache.backup.DataFileCache;
+import fr.xephi.authme.cache.backup.JsonCache;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
-import fr.xephi.authme.cache.backup.FileCache;
-
/**
- *
* This event is call just before write inventory content to cache
*
* @author Xephi59
@@ -23,12 +22,13 @@ public class StoreInventoryEvent extends CustomEvent {
this.armor = player.getInventory().getArmorContents();
}
- public StoreInventoryEvent(Player player, FileCache fileCache) {
+ public StoreInventoryEvent(Player player, JsonCache jsonCache) {
this.player = player;
- try {
- this.inventory = fileCache.readCache(player).getInventory();
- this.armor = fileCache.readCache(player).getArmour();
- } catch (Exception e) {
+ DataFileCache cache = jsonCache.readCache(player);
+ if (cache != null) {
+ this.inventory = cache.getInventory();
+ this.armor = cache.getArmour();
+ } else {
this.inventory = player.getInventory().getContents();
this.armor = player.getInventory().getArmorContents();
}
diff --git a/src/main/java/fr/xephi/authme/listener/AuthMeBlockListener.java b/src/main/java/fr/xephi/authme/listener/AuthMeBlockListener.java
index c6bf45ed..678fbca2 100644
--- a/src/main/java/fr/xephi/authme/listener/AuthMeBlockListener.java
+++ b/src/main/java/fr/xephi/authme/listener/AuthMeBlockListener.java
@@ -1,16 +1,13 @@
package fr.xephi.authme.listener;
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.Utils;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.Utils;
-import fr.xephi.authme.cache.auth.PlayerCache;
-import fr.xephi.authme.settings.Settings;
-
public class AuthMeBlockListener implements Listener {
public AuthMe instance;
@@ -22,51 +19,17 @@ public class AuthMeBlockListener implements Listener {
@EventHandler(ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
- if (event.getPlayer() == null) {
+ if (Utils.checkAuth(event.getPlayer()))
return;
- }
-
- Player player = event.getPlayer();
- String name = player.getName().toLowerCase();
-
- if (Utils.getInstance().isUnrestricted(player)) {
- return;
- }
-
- if (PlayerCache.getInstance().isAuthenticated(name)) {
- return;
- }
-
- if (!instance.database.isAuthAvailable(name)) {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- }
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
- if (event.getPlayer() == null) {
- return;
- }
-
Player player = event.getPlayer();
- String name = player.getName().toLowerCase();
-
- if (Utils.getInstance().isUnrestricted(player)) {
+ if (player == null || Utils.checkAuth(player)) {
return;
}
-
- if (PlayerCache.getInstance().isAuthenticated(name)) {
- return;
- }
-
- if (!instance.database.isAuthAvailable(name)) {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- }
event.setCancelled(true);
}
diff --git a/src/main/java/fr/xephi/authme/listener/AuthMeChestShopListener.java b/src/main/java/fr/xephi/authme/listener/AuthMeChestShopListener.java
index c26f1886..476f2586 100644
--- a/src/main/java/fr/xephi/authme/listener/AuthMeChestShopListener.java
+++ b/src/main/java/fr/xephi/authme/listener/AuthMeChestShopListener.java
@@ -1,17 +1,12 @@
package fr.xephi.authme.listener;
-import org.bukkit.entity.Player;
-import org.bukkit.event.EventHandler;
-import org.bukkit.event.EventPriority;
-import org.bukkit.event.Listener;
-
import com.Acrobot.ChestShop.Events.PreTransactionEvent;
import com.Acrobot.ChestShop.Events.PreTransactionEvent.TransactionOutcome;
-
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils;
-import fr.xephi.authme.cache.auth.PlayerCache;
-import fr.xephi.authme.settings.Settings;
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.EventPriority;
+import org.bukkit.event.Listener;
public class AuthMeChestShopListener implements Listener {
@@ -23,26 +18,8 @@ public class AuthMeChestShopListener implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPreTransaction(PreTransactionEvent event) {
- if (event.getClient() == null) {
+ if (Utils.checkAuth(event.getClient()))
return;
- }
-
- Player player = event.getClient();
- String name = player.getName().toLowerCase();
-
- if (Utils.getInstance().isUnrestricted(player)) {
- return;
- }
-
- if (PlayerCache.getInstance().isAuthenticated(name)) {
- return;
- }
-
- if (!plugin.database.isAuthAvailable(name)) {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- }
event.setCancelled(TransactionOutcome.OTHER);
}
}
diff --git a/src/main/java/fr/xephi/authme/listener/AuthMeEntityListener.java b/src/main/java/fr/xephi/authme/listener/AuthMeEntityListener.java
index db4bf5f6..da4b43ea 100644
--- a/src/main/java/fr/xephi/authme/listener/AuthMeEntityListener.java
+++ b/src/main/java/fr/xephi/authme/listener/AuthMeEntityListener.java
@@ -1,22 +1,14 @@
package fr.xephi.authme.listener;
-import org.bukkit.entity.Entity;
-import org.bukkit.entity.Player;
-import org.bukkit.event.EventHandler;
-import org.bukkit.event.EventPriority;
-import org.bukkit.event.Listener;
-import org.bukkit.event.entity.EntityDamageByEntityEvent;
-import org.bukkit.event.entity.EntityDamageEvent;
-import org.bukkit.event.entity.EntityInteractEvent;
-import org.bukkit.event.entity.EntityRegainHealthEvent;
-import org.bukkit.event.entity.EntityTargetEvent;
-import org.bukkit.event.entity.FoodLevelChangeEvent;
-
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils;
-import fr.xephi.authme.cache.auth.PlayerCache;
-import fr.xephi.authme.plugin.manager.CombatTagComunicator;
-import fr.xephi.authme.settings.Settings;
+import org.bukkit.entity.Entity;
+import org.bukkit.entity.Player;
+import org.bukkit.entity.Projectile;
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.EventPriority;
+import org.bukkit.event.Listener;
+import org.bukkit.event.entity.*;
public class AuthMeEntityListener implements Listener {
@@ -29,32 +21,13 @@ public class AuthMeEntityListener implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onEntityDamage(EntityDamageEvent event) {
Entity entity = event.getEntity();
-
- if (!(entity instanceof Player)) {
+ if (entity == null || !(entity instanceof Player)) {
return;
}
- if (Utils.getInstance().isUnrestricted((Player) entity)) {
- return;
- }
-
- if (instance.citizens.isNPC(entity))
- return;
-
Player player = (Player) entity;
- String name = player.getName().toLowerCase();
-
- if (CombatTagComunicator.isNPC(player))
+ if (Utils.checkAuth(player)) {
return;
-
- if (PlayerCache.getInstance().isAuthenticated(name)) {
- return;
- }
-
- if (!instance.database.isAuthAvailable(name)) {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
}
player.setFireTicks(0);
event.setDamage(0.0);
@@ -63,28 +36,15 @@ public class AuthMeEntityListener implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onEntityTarget(EntityTargetEvent event) {
- if (event.getTarget() == null)
- return;
Entity entity = event.getTarget();
- if (!(entity instanceof Player)) {
+ if (entity == null || !(entity instanceof Player)) {
return;
}
- if (instance.citizens.isNPC(entity))
- return;
-
- Player player = (Player) entity;
- String name = player.getName().toLowerCase();
-
- if (PlayerCache.getInstance().isAuthenticated(name)) {
+ if (Utils.checkAuth((Player) entity)) {
return;
}
- if (!instance.database.isAuthAvailable(name)) {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- }
event.setTarget(null);
event.setCancelled(true);
}
@@ -92,75 +52,41 @@ public class AuthMeEntityListener implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onDmg(EntityDamageByEntityEvent event) {
Entity entity = event.getDamager();
-
if (entity == null || !(entity instanceof Player)) {
return;
}
Player player = (Player) entity;
- String name = player.getName().toLowerCase();
-
- if (PlayerCache.getInstance().isAuthenticated(name)) {
+ if (Utils.checkAuth(player)) {
return;
}
- if (!instance.database.isAuthAvailable(name)) {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- }
-
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onFoodLevelChange(FoodLevelChangeEvent event) {
Entity entity = event.getEntity();
- if (!(entity instanceof Player)) {
+ if (entity == null || !(entity instanceof Player)) {
return;
}
- if (instance.citizens.isNPC(entity))
+ if (Utils.checkAuth((Player) entity)) {
return;
-
- Player player = (Player) entity;
- String name = player.getName().toLowerCase();
-
- if (PlayerCache.getInstance().isAuthenticated(name)) {
- return;
- }
-
- if (!instance.database.isAuthAvailable(name)) {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
}
event.setCancelled(true);
-
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
- public void EntityRegainHealthEvent(EntityRegainHealthEvent event) {
+ public void entityRegainHealthEvent(EntityRegainHealthEvent event) {
Entity entity = event.getEntity();
- if (!(entity instanceof Player)) {
+ if (entity == null || !(entity instanceof Player)) {
return;
}
- if (instance.citizens.isNPC(entity))
+ if (Utils.checkAuth((Player) entity)) {
return;
-
- Player player = (Player) entity;
- String name = player.getName().toLowerCase();
-
- if (PlayerCache.getInstance().isAuthenticated(name)) {
- return;
- }
-
- if (!instance.database.isAuthAvailable(name)) {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
}
event.setAmount(0.0);
@@ -169,57 +95,63 @@ public class AuthMeEntityListener implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onEntityInteract(EntityInteractEvent event) {
- if (!(event.getEntity() instanceof Player)) {
+ Entity entity = event.getEntity();
+ if (entity == null || !(entity instanceof Player)) {
return;
}
- Player player = (Player) event.getEntity();
- String name = player.getName().toLowerCase();
-
- if (Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) {
+ if (Utils.checkAuth((Player) entity)) {
return;
}
- if (instance.citizens.isNPC(player))
- return;
-
- if (PlayerCache.getInstance().isAuthenticated(player.getName())) {
- return;
- }
-
- if (!instance.database.isAuthAvailable(name)) {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- }
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onLowestEntityInteract(EntityInteractEvent event) {
- if (!(event.getEntity() instanceof Player)) {
+ Entity entity = event.getEntity();
+ if (entity == null || !(entity instanceof Player)) {
return;
}
- Player player = (Player) event.getEntity();
- String name = player.getName().toLowerCase();
-
- if (Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) {
+ if (Utils.checkAuth((Player) entity)) {
return;
}
- if (instance.citizens.isNPC(player))
- return;
-
- if (PlayerCache.getInstance().isAuthenticated(player.getName())) {
- return;
- }
-
- if (!instance.database.isAuthAvailable(name)) {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- }
event.setCancelled(true);
}
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onProjectileLaunch(ProjectileLaunchEvent event) {
+ Projectile projectile = event.getEntity();
+ if (projectile == null)
+ return;
+
+ Entity shooter = (Entity) projectile.getShooter();
+ if (shooter == null || !(shooter instanceof Player)) {
+ return;
+ }
+
+ if (Utils.checkAuth((Player) shooter)) {
+ return;
+ }
+
+ event.setCancelled(true);
+ }
+
+ @EventHandler
+ public void onShoot(EntityShootBowEvent event) {
+ Entity entity = event.getEntity();
+ if (entity == null || !(entity instanceof Player)) {
+ return;
+ }
+
+ Player player = (Player) entity;
+ if (Utils.checkAuth(player)) {
+ return;
+ }
+
+ event.setCancelled(true);
+ }
+
}
diff --git a/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java b/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java
index fda470e6..882ddcbd 100644
--- a/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java
+++ b/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java
@@ -1,20 +1,20 @@
package fr.xephi.authme.listener;
-import java.io.ByteArrayOutputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.regex.PatternSyntaxException;
-
+import com.google.common.io.ByteArrayDataOutput;
+import com.google.common.io.ByteStreams;
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.ConsoleLogger;
+import fr.xephi.authme.Utils;
+import fr.xephi.authme.cache.auth.PlayerAuth;
+import fr.xephi.authme.cache.auth.PlayerCache;
+import fr.xephi.authme.cache.limbo.LimboCache;
+import fr.xephi.authme.cache.limbo.LimboPlayer;
+import fr.xephi.authme.datasource.DataSource;
+import fr.xephi.authme.settings.Messages;
+import fr.xephi.authme.settings.Settings;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
-import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
@@ -24,65 +24,51 @@ import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
-import org.bukkit.event.player.AsyncPlayerChatEvent;
-import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
-import org.bukkit.event.player.PlayerBedEnterEvent;
-import org.bukkit.event.player.PlayerCommandPreprocessEvent;
-import org.bukkit.event.player.PlayerDropItemEvent;
-import org.bukkit.event.player.PlayerGameModeChangeEvent;
-import org.bukkit.event.player.PlayerInteractEntityEvent;
-import org.bukkit.event.player.PlayerInteractEvent;
-import org.bukkit.event.player.PlayerJoinEvent;
-import org.bukkit.event.player.PlayerKickEvent;
-import org.bukkit.event.player.PlayerLoginEvent;
-import org.bukkit.event.player.PlayerMoveEvent;
-import org.bukkit.event.player.PlayerPickupItemEvent;
-import org.bukkit.event.player.PlayerQuitEvent;
-import org.bukkit.event.player.PlayerRespawnEvent;
+import org.bukkit.event.player.*;
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.ConsoleLogger;
-import fr.xephi.authme.Utils;
-import fr.xephi.authme.cache.auth.PlayerAuth;
-import fr.xephi.authme.cache.auth.PlayerCache;
-import fr.xephi.authme.cache.limbo.LimboCache;
-import fr.xephi.authme.cache.limbo.LimboPlayer;
-import fr.xephi.authme.datasource.DataSource;
-import fr.xephi.authme.plugin.manager.CombatTagComunicator;
-import fr.xephi.authme.settings.Messages;
-import fr.xephi.authme.settings.Settings;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.regex.PatternSyntaxException;
public class AuthMePlayerListener implements Listener {
- public static ConcurrentHashMap gameMode = new ConcurrentHashMap();
- public static ConcurrentHashMap joinMessage = new ConcurrentHashMap();
+ public static ConcurrentHashMap gameMode = new ConcurrentHashMap<>();
+ public static ConcurrentHashMap joinMessage = new ConcurrentHashMap<>();
private Messages m = Messages.getInstance();
public AuthMe plugin;
- public static ConcurrentHashMap causeByAuthMe = new ConcurrentHashMap();
- private List antibot = new ArrayList();
+ public static ConcurrentHashMap causeByAuthMe = new ConcurrentHashMap<>();
+ private List antibot = new ArrayList<>();
public AuthMePlayerListener(AuthMe plugin) {
this.plugin = plugin;
}
+ private void handleChat(AsyncPlayerChatEvent event) {
+ Player player = event.getPlayer();
+ if (!Utils.checkAuth(player)) {
+ String cmd = event.getMessage().split(" ")[0];
+ if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) {
+ event.setCancelled(true);
+ }
+ if (plugin.database.isAuthAvailable(player.getName().toLowerCase())) {
+ m.send(player, "login_msg");
+ } else {
+ if (Settings.emailRegistration) {
+ m.send(player, "reg_email_msg");
+ } else {
+ m.send(player, "reg_msg");
+ }
+ }
+ }
+ }
+
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
- if (event.getPlayer() == null)
+ if (Utils.checkAuth(event.getPlayer()))
return;
- Player player = event.getPlayer();
- String name = player.getName().toLowerCase();
-
- if (Utils.getInstance().isUnrestricted(player))
- return;
-
- if (PlayerCache.getInstance().isAuthenticated(name))
- return;
-
- if (!plugin.database.isAuthAvailable(name))
- if (!Settings.isForcedRegistrationEnabled)
- return;
-
String msg = event.getMessage();
if (msg.equalsIgnoreCase("/worldedit cui"))
return;
@@ -101,246 +87,39 @@ public class AuthMePlayerListener implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
public void onPlayerNormalChat(AsyncPlayerChatEvent event) {
- if (event.getPlayer() == null)
- return;
-
- final Player player = event.getPlayer();
- final String name = player.getName().toLowerCase();
-
- if (Utils.getInstance().isUnrestricted(player))
- return;
-
- if (PlayerCache.getInstance().isAuthenticated(name))
- return;
-
- String cmd = event.getMessage().split(" ")[0];
-
- if (plugin.database.isAuthAvailable(name)) {
- m.send(player, "login_msg");
- } else {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- if (Settings.emailRegistration) {
- m.send(player, "reg_email_msg");
- return;
- } else {
- m.send(player, "reg_msg");
- return;
- }
- }
-
- if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) {
- event.setCancelled(true);
- return;
- }
+ handleChat(event);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onPlayerHighChat(AsyncPlayerChatEvent event) {
- if (event.getPlayer() == null)
- return;
-
- final Player player = event.getPlayer();
- final String name = player.getName().toLowerCase();
-
- if (Utils.getInstance().isUnrestricted(player))
- return;
-
- if (PlayerCache.getInstance().isAuthenticated(name))
- return;
-
- String cmd = event.getMessage().split(" ")[0];
-
- if (plugin.database.isAuthAvailable(name)) {
- m.send(player, "login_msg");
- } else {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- if (Settings.emailRegistration) {
- m.send(player, "reg_email_msg");
- return;
- } else {
- m.send(player, "reg_msg");
- return;
- }
- }
-
- if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) {
- event.setCancelled(true);
- return;
- }
+ handleChat(event);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onPlayerChat(AsyncPlayerChatEvent event) {
- if (event.getPlayer() == null)
- return;
-
- final Player player = event.getPlayer();
- final String name = player.getName().toLowerCase();
-
- if (Utils.getInstance().isUnrestricted(player))
- return;
-
- if (PlayerCache.getInstance().isAuthenticated(name))
- return;
-
- String cmd = event.getMessage().split(" ")[0];
-
- if (plugin.database.isAuthAvailable(name)) {
- m.send(player, "login_msg");
- } else {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- if (Settings.emailRegistration) {
- m.send(player, "reg_email_msg");
- return;
- } else {
- m.send(player, "reg_msg");
- return;
- }
- }
-
- if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) {
- event.setCancelled(true);
- return;
- }
+ handleChat(event);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onPlayerHighestChat(AsyncPlayerChatEvent event) {
- if (event.getPlayer() == null)
- return;
-
- final Player player = event.getPlayer();
- final String name = player.getName().toLowerCase();
-
- if (Utils.getInstance().isUnrestricted(player))
- return;
-
- if (PlayerCache.getInstance().isAuthenticated(name))
- return;
-
- String cmd = event.getMessage().split(" ")[0];
-
- if (plugin.database.isAuthAvailable(name)) {
- m.send(player, "login_msg");
- } else {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- if (Settings.emailRegistration) {
- m.send(player, "reg_email_msg");
- return;
- } else {
- m.send(player, "reg_msg");
- return;
- }
- }
-
- if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) {
- event.setCancelled(true);
- return;
- }
+ handleChat(event);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
- public void onPlayerEarlyChat(final AsyncPlayerChatEvent event) {
- if (event.getPlayer() == null)
- return;
-
- final Player player = event.getPlayer();
- final String name = player.getName().toLowerCase();
-
- if (Utils.getInstance().isUnrestricted(player))
- return;
-
- if (PlayerCache.getInstance().isAuthenticated(name)) {
- return;
- }
-
- String cmd = event.getMessage().split(" ")[0];
-
- if (plugin.database.isAuthAvailable(name)) {
- m.send(player, "login_msg");
- } else {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- if (Settings.emailRegistration) {
- m.send(player, "reg_email_msg");
- return;
- } else {
- m.send(player, "reg_msg");
- return;
- }
- }
-
- if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) {
- event.setCancelled(true);
- return;
- }
+ public void onPlayerEarlyChat(AsyncPlayerChatEvent event) {
+ handleChat(event);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOW)
public void onPlayerLowChat(AsyncPlayerChatEvent event) {
- if (event.getPlayer() == null)
- return;
-
- final Player player = event.getPlayer();
- final String name = player.getName().toLowerCase();
-
- if (Utils.getInstance().isUnrestricted(player))
- return;
-
- if (PlayerCache.getInstance().isAuthenticated(name))
- return;
-
- String cmd = event.getMessage().split(" ")[0];
-
- if (plugin.database.isAuthAvailable(name)) {
- m.send(player, "login_msg");
- } else {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- if (Settings.emailRegistration) {
- m.send(player, "reg_email_msg");
- } else {
- m.send(player, "reg_msg");
- }
- }
-
- if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) {
- event.setCancelled(true);
- return;
- }
+ handleChat(event);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onPlayerMove(PlayerMoveEvent event) {
- if (event.getPlayer() == null) {
- return;
- }
-
Player player = event.getPlayer();
- String name = player.getName().toLowerCase();
-
- if (plugin.getCitizensCommunicator().isNPC(player) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) {
+ if (Utils.checkAuth(player))
return;
- }
-
- if (PlayerCache.getInstance().isAuthenticated(name)) {
- return;
- }
-
- if (!Settings.isForcedRegistrationEnabled) {
- if (!plugin.database.isAuthAvailable(name))
- return;
- }
if (!Settings.isMovementAllowed) {
if (!event.getFrom().getBlock().equals(event.getTo().getBlock()))
@@ -362,7 +141,6 @@ public class AuthMePlayerListener implements Listener {
}
if ((spawn.distance(player.getLocation()) > radius)) {
event.getPlayer().teleport(spawn);
- return;
}
}
}
@@ -401,16 +179,14 @@ public class AuthMePlayerListener implements Listener {
}
@EventHandler(priority = EventPriority.HIGHEST)
- public void onPlayerJoin(PlayerJoinEvent e) {
- final PlayerJoinEvent event = e;
-
+ public void onPlayerJoin(final PlayerJoinEvent event) {
if (event.getPlayer() == null) {
return;
}
// Shedule login task so works after the prelogin
// (Fix found by Koolaid5000)
- Bukkit.getScheduler().runTask(plugin, new Runnable(){
+ Bukkit.getScheduler().runTask(plugin, new Runnable() {
@Override
public void run() {
Player player = event.getPlayer();
@@ -419,20 +195,20 @@ public class AuthMePlayerListener implements Listener {
plugin.management.performJoin(player);
// Remove the join message while the player isn't logging in
- if ((Settings.enableProtection || Settings.delayJoinMessage) && name != null && event.getJoinMessage() != null) {
+ if ((Settings.enableProtection || Settings.delayJoinMessage) && event.getJoinMessage() != null) {
joinMessage.put(name, event.getJoinMessage());
event.setJoinMessage(null);
}
}
- });
+ });
}
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.HIGHEST)
- public void onPreLogin(AsyncPlayerPreLoginEvent event){
+ public void onPreLogin(AsyncPlayerPreLoginEvent event) {
final String name = event.getName().toLowerCase();
final Player player = Bukkit.getServer().getPlayer(name);
-
+
if (player == null)
return;
@@ -443,18 +219,17 @@ public class AuthMePlayerListener implements Listener {
event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
if (LimboCache.getInstance().hasLimboPlayer(name))
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
-
+
@Override
public void run() {
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(player.getName().toLowerCase());
if (limbo != null && PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
- Utils.getInstance().addNormal(player, limbo.getGroup());
+ Utils.addNormal(player, limbo.getGroup());
LimboCache.getInstance().deleteLimboPlayer(player.getName().toLowerCase());
}
}
-
+
});
- return;
}
}
@@ -466,7 +241,7 @@ public class AuthMePlayerListener implements Listener {
final String name = player.getName().toLowerCase();
boolean isAuthAvailable = plugin.database.isAuthAvailable(name);
- if (plugin.getCitizensCommunicator().isNPC(player) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) {
+ if (Utils.isNPC(player) || Utils.isUnrestricted(player)) {
return;
}
@@ -474,7 +249,7 @@ public class AuthMePlayerListener implements Listener {
return;
if (!Settings.countriesBlacklist.isEmpty()) {
- String code = plugin.getCountryCode(event.getAddress().getHostAddress());
+ String code = Utils.getCountryCode(event.getAddress().getHostAddress());
if (((code == null) || (Settings.countriesBlacklist.contains(code) && !isAuthAvailable)) && !plugin.authmePermissible(player, "authme.bypassantibot")) {
event.setKickMessage(m.send("country_banned")[0]);
event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
@@ -482,7 +257,7 @@ public class AuthMePlayerListener implements Listener {
}
}
if (Settings.enableProtection && !Settings.countries.isEmpty()) {
- String code = plugin.getCountryCode(event.getAddress().getHostAddress());
+ String code = Utils.getCountryCode(event.getAddress().getHostAddress());
if (((code == null) || (!Settings.countries.contains(code) && !isAuthAvailable)) && !plugin.authmePermissible(player, "authme.bypassantibot")) {
event.setKickMessage(m.send("country_banned")[0]);
event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
@@ -491,7 +266,7 @@ public class AuthMePlayerListener implements Listener {
}
if (Settings.isKickNonRegisteredEnabled && !Settings.antiBotInAction) {
- if (!plugin.database.isAuthAvailable(name)) {
+ if (!isAuthAvailable) {
event.setKickMessage(m.send("reg_only")[0]);
event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
return;
@@ -499,14 +274,14 @@ public class AuthMePlayerListener implements Listener {
}
if (Settings.antiBotInAction) {
- if (!plugin.database.isAuthAvailable(name)) {
+ if (!isAuthAvailable) {
event.setKickMessage("AntiBot service in action! You actually need to be registered!");
event.setResult(PlayerLoginEvent.Result.KICK_OTHER);
return;
}
}
- if (plugin.database.isAuthAvailable(name) && plugin.database.getType() != DataSource.DataSourceType.FILE) {
+ if (isAuthAvailable && plugin.database.getType() != DataSource.DataSourceType.FILE) {
PlayerAuth auth = plugin.database.getAuth(name);
if (auth.getRealName() != null && !auth.getRealName().isEmpty() && !auth.getRealName().equalsIgnoreCase("Player") && !auth.getRealName().equals(player.getName())) {
event.setKickMessage(m.send("same_nick")[0]);
@@ -556,14 +331,9 @@ public class AuthMePlayerListener implements Listener {
if (event.getResult() == PlayerLoginEvent.Result.ALLOWED) {
checkAntiBotMod(player);
if (Settings.bungee) {
- final ByteArrayOutputStream b = new ByteArrayOutputStream();
- DataOutputStream out = new DataOutputStream(b);
-
- try {
- out.writeUTF("IP");
- } catch (IOException e) {
- }
- player.sendPluginMessage(plugin, "BungeeCord", b.toByteArray());
+ ByteArrayDataOutput out = ByteStreams.newDataOutput();
+ out.writeUTF("IP");
+ player.sendPluginMessage(plugin, "BungeeCord", out.toByteArray());
}
return;
}
@@ -575,31 +345,18 @@ public class AuthMePlayerListener implements Listener {
return;
}
- int playersOnline = 0;
- try {
- if (Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).getReturnType() == Collection.class)
- playersOnline = ((Collection>) Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).invoke(null, new Object[0])).size();
- else playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).invoke(null, new Object[0])).length;
- } catch (NoSuchMethodException ex) {
- } // can never happen
- catch (InvocationTargetException ex) {
- } // can also never happen
- catch (IllegalAccessException ex) {
- } // can still never happen
+ int playersOnline = Utils.getOnlinePlayers().size();
if (playersOnline > plugin.getServer().getMaxPlayers()) {
event.allow();
- return;
} else {
- final Player pl = plugin.generateKickPlayer(plugin.getServer().getOnlinePlayers());
+ final Player pl = plugin.generateKickPlayer(Utils.getOnlinePlayers());
if (pl != null) {
pl.kickPlayer(m.send("kick_forvip")[0]);
event.allow();
- return;
} else {
ConsoleLogger.info("The player " + player.getName() + " tryed to join, but the server was full");
event.setKickMessage(m.send("kick_fullserver")[0]);
event.setResult(PlayerLoginEvent.Result.KICK_FULL);
- return;
}
}
}
@@ -615,7 +372,7 @@ public class AuthMePlayerListener implements Listener {
plugin.management.performQuit(player, false);
- if (plugin.database.getAuth(name) != null && !PlayerCache.getInstance().isAuthenticated(name) && Settings.enableProtection)
+ if (plugin.database.isAuthAvailable(name) && !PlayerCache.getInstance().isAuthenticated(name) && Settings.enableProtection)
event.setQuitMessage(null);
}
@@ -625,94 +382,42 @@ public class AuthMePlayerListener implements Listener {
return;
}
- Player player = event.getPlayer();
-
if ((!Settings.isForceSingleSessionEnabled) && (event.getReason().contains(m.getString("same_nick")))) {
event.setCancelled(true);
return;
}
+ Player player = event.getPlayer();
plugin.management.performQuit(player, true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onPlayerPickupItem(PlayerPickupItemEvent event) {
- if (event.getPlayer() == null) {
+ if (Utils.checkAuth(event.getPlayer()))
return;
- }
-
- Player player = event.getPlayer();
- String name = player.getName().toLowerCase();
-
- if (Utils.getInstance().isUnrestricted(player)) {
- return;
- }
-
- if (plugin.getCitizensCommunicator().isNPC(player))
- return;
-
- if (PlayerCache.getInstance().isAuthenticated(name)) {
- return;
- }
-
- if (!plugin.database.isAuthAvailable(name)) {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- }
-
event.setCancelled(true);
}
- @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
+ @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onPlayerInteract(PlayerInteractEvent event) {
- if (event.getPlayer() == null)
- return;
-
Player player = event.getPlayer();
- String name = player.getName().toLowerCase();
-
- if (Utils.getInstance().isUnrestricted(player)) {
+ if (player == null || Utils.checkAuth(player))
return;
- }
-
- if (plugin.getCitizensCommunicator().isNPC(player))
- return;
-
- if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
- return;
- }
-
- if (!plugin.database.isAuthAvailable(name)) {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- }
- if (event.getClickedBlock() != null && event.getClickedBlock().getType() != Material.AIR)
- event.setUseInteractedBlock(org.bukkit.event.Event.Result.DENY);
- event.setUseItemInHand(org.bukkit.event.Event.Result.DENY);
event.setCancelled(true);
}
- @EventHandler(priority = EventPriority.HIGHEST)
+ @EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
+ public void onPlayerConsumeItem(PlayerItemConsumeEvent event) {
+ if (Utils.checkAuth(event.getPlayer()))
+ return;
+ event.setCancelled(true);
+ }
+
+ @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onPlayerInventoryOpen(InventoryOpenEvent event) {
- if (event.getPlayer() == null)
- return;
final Player player = (Player) event.getPlayer();
- String name = player.getName().toLowerCase();
- if (Utils.getInstance().isUnrestricted(player)) {
+ if (Utils.checkAuth(player))
return;
- }
- if (plugin.getCitizensCommunicator().isNPC(player))
- return;
- if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
- return;
- }
- if (!plugin.database.isAuthAvailable(name)) {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- }
event.setCancelled(true);
/*
@@ -724,7 +429,6 @@ public class AuthMePlayerListener implements Listener {
@Override
public void run() {
player.closeInventory();
- ;
}
}, 1);
@@ -736,219 +440,115 @@ public class AuthMePlayerListener implements Listener {
return;
if (!(event.getWhoClicked() instanceof Player))
return;
- Player player = (Player) event.getWhoClicked();
- String name = player.getName().toLowerCase();
-
- if (Utils.getInstance().isUnrestricted(player)) {
+ if (Utils.checkAuth((Player) event.getWhoClicked()))
return;
- }
-
- if (plugin.getCitizensCommunicator().isNPC(player))
- return;
-
- if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
- return;
- }
-
- if (!plugin.database.isAuthAvailable(name)) {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- }
- event.setResult(org.bukkit.event.Event.Result.DENY);
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void playerHitPlayerEvent(EntityDamageByEntityEvent event) {
Entity damager = event.getDamager();
- if (!(damager instanceof Player)){
+ if (!(damager instanceof Player)) {
return;
}
-
- Player player = (Player) damager;
- String name = player.getName().toLowerCase();
-
- if (Utils.getInstance().isUnrestricted(player)) {
+ if (Utils.checkAuth((Player) damager))
return;
- }
-
- if (plugin.getCitizensCommunicator().isNPC(player)) {
- return;
- }
-
- if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
- return;
- }
-
- if (!plugin.database.isAuthAvailable(name) && !Settings.isForcedRegistrationEnabled) {
- return;
- }
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
- if (event.getPlayer() == null) {
- return;
- }
-
Player player = event.getPlayer();
- String name = player.getName().toLowerCase();
-
- if (plugin.getCitizensCommunicator().isNPC(player) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) {
+ if (player == null || Utils.checkAuth(player))
return;
- }
+ event.setCancelled(true);
+ }
- if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
+ @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
+ public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent event) {
+ Player player = event.getPlayer();
+ if (player == null || Utils.checkAuth(player))
return;
- }
-
- if (!plugin.database.isAuthAvailable(name)) {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- }
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerDropItem(PlayerDropItemEvent event) {
- if (event.getPlayer() == null) {
+ if (Utils.checkAuth(event.getPlayer()))
return;
- }
- Player player = event.getPlayer();
- String name = player.getName().toLowerCase();
-
- if (Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) {
- return;
- }
-
- if (plugin.getCitizensCommunicator().isNPC(player))
- return;
-
- if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
- return;
- }
-
- if (!plugin.database.isAuthAvailable(name)) {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- }
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerBedEnter(PlayerBedEnterEvent event) {
- if (event.getPlayer() == null) {
+ if (Utils.checkAuth(event.getPlayer()))
return;
- }
- Player player = event.getPlayer();
- String name = player.getName().toLowerCase();
-
- if (Utils.getInstance().isUnrestricted(player)) {
- return;
- }
-
- if (PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) {
- return;
- }
-
- if (!plugin.database.isAuthAvailable(name)) {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- }
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onSignChange(SignChangeEvent event) {
- if (event.getPlayer() == null) {
+ if (Utils.checkAuth(event.getPlayer()))
return;
- }
- Player player = event.getPlayer();
- String name = player.getName().toLowerCase();
- if (Utils.getInstance().isUnrestricted(player)) {
- return;
- }
- if (PlayerCache.getInstance().isAuthenticated(name)) {
- return;
- }
- if (!plugin.database.isAuthAvailable(name)) {
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- }
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerRespawn(PlayerRespawnEvent event) {
- if (event.getPlayer() == null) {
- return;
- }
-
Player player = event.getPlayer();
+ if (player == null || Utils.checkAuth(player))
+ return;
String name = player.getName().toLowerCase();
-
- if (Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player))
- return;
-
- if (plugin.getCitizensCommunicator().isNPC(player))
- return;
-
- if (PlayerCache.getInstance().isAuthenticated(name))
- return;
-
- if (!plugin.database.isAuthAvailable(name))
- if (!Settings.isForcedRegistrationEnabled)
- return;
-
Location spawn = plugin.getSpawnLocation(player);
if (Settings.isSaveQuitLocationEnabled && plugin.database.isAuthAvailable(name)) {
final PlayerAuth auth = new PlayerAuth(name, spawn.getX(), spawn.getY(), spawn.getZ(), spawn.getWorld().getName(), player.getName());
- try {
- plugin.database.updateQuitLoc(auth);
- } catch (NullPointerException npe) {
- }
+ plugin.database.updateQuitLoc(auth);
}
- if (spawn != null && spawn.getWorld() != null)
+ if (spawn != null && spawn.getWorld() != null) {
event.setRespawnLocation(spawn);
+ }
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) {
- if (event.getPlayer() == null)
- return;
-
Player player = event.getPlayer();
-
+ if (player == null)
+ return;
if (plugin.authmePermissible(player, "authme.bypassforcesurvival"))
return;
+ if (Utils.checkAuth(player))
+ return;
String name = player.getName().toLowerCase();
-
- if (Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player))
- return;
-
- if (plugin.getCitizensCommunicator().isNPC(player))
- return;
-
- if (PlayerCache.getInstance().isAuthenticated(name))
- return;
-
- if (!plugin.database.isAuthAvailable(name))
- if (!Settings.isForcedRegistrationEnabled)
- return;
-
if (causeByAuthMe.containsKey(name)) {
causeByAuthMe.remove(name);
return;
}
+ event.setCancelled(true);
+ }
+ @EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
+ public void onPlayerShear(PlayerShearEntityEvent event) {
+ Player player = event.getPlayer();
+ if (player == null || Utils.checkAuth(player))
+ return;
+ event.setCancelled(true);
+ }
+
+ @EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
+ public void onPlayerFish(PlayerFishEvent event) {
+ Player player = event.getPlayer();
+ if (player == null || Utils.checkAuth(player))
+ return;
+ event.setCancelled(true);
+ }
+
+ @EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL)
+ public void onPlayerEditBook(PlayerEditBookEvent event) {
+ Player player = event.getPlayer();
+ if (player == null || Utils.checkAuth(player))
+ return;
event.setCancelled(true);
}
}
diff --git a/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java b/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java
index 4f0b2ed5..d13e8738 100644
--- a/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java
+++ b/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java
@@ -1,5 +1,10 @@
package fr.xephi.authme.listener;
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.ConsoleLogger;
+import fr.xephi.authme.Utils;
+import fr.xephi.authme.settings.Messages;
+import fr.xephi.authme.settings.Settings;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
@@ -7,11 +12,6 @@ import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.event.server.ServerListPingEvent;
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.ConsoleLogger;
-import fr.xephi.authme.settings.Messages;
-import fr.xephi.authme.settings.Settings;
-
public class AuthMeServerListener implements Listener {
public AuthMe plugin;
@@ -28,10 +28,10 @@ public class AuthMeServerListener implements Listener {
if (Settings.countries.isEmpty())
return;
if (!Settings.countriesBlacklist.isEmpty()) {
- if (Settings.countriesBlacklist.contains(plugin.getCountryCode(event.getAddress().getHostAddress())))
+ if (Settings.countriesBlacklist.contains(Utils.getCountryCode(event.getAddress().getHostAddress())))
event.setMotd(m.send("country_banned")[0]);
}
- if (Settings.countries.contains(plugin.getCountryCode(event.getAddress().getHostAddress()))) {
+ if (Settings.countries.contains(Utils.getCountryCode(event.getAddress().getHostAddress()))) {
event.setMotd(plugin.getServer().getMotd());
} else {
event.setMotd(m.send("country_banned")[0]);
@@ -57,16 +57,12 @@ public class AuthMeServerListener implements Listener {
return;
}
if (pluginName.equalsIgnoreCase("ChestShop")) {
- plugin.ChestShop = 0;
+ plugin.legacyChestShop = false;
ConsoleLogger.info("ChestShop has been disabled, unhook!");
}
- if (pluginName.equalsIgnoreCase("CombatTag")) {
- plugin.CombatTag = false;
- ConsoleLogger.info("CombatTag has been disabled, unhook!");
- }
- if (pluginName.equalsIgnoreCase("Citizens")) {
- plugin.isCitizensActive = false;
- ConsoleLogger.info("Citizens has been disabled, unhook!");
+ if (pluginName.equalsIgnoreCase("CombatTagPlus")) {
+ plugin.combatTagPlus = null;
+ ConsoleLogger.info("CombatTagPlus has been disabled, unhook!");
}
if (pluginName.equalsIgnoreCase("Vault")) {
plugin.permission = null;
@@ -83,10 +79,8 @@ public class AuthMeServerListener implements Listener {
plugin.checkMultiverse();
if (pluginName.equalsIgnoreCase("ChestShop"))
plugin.checkChestShop();
- if (pluginName.equalsIgnoreCase("CombatTag"))
- plugin.checkCombatTag();
- if (pluginName.equalsIgnoreCase("Citizens"))
- plugin.checkCitizens();
+ if (pluginName.equalsIgnoreCase("CombatTagPlus"))
+ plugin.checkCombatTagPlus();
if (pluginName.equalsIgnoreCase("Vault"))
plugin.checkVault();
}
diff --git a/src/main/java/fr/xephi/authme/modules/Module.java b/src/main/java/fr/xephi/authme/modules/Module.java
index 6011097a..ab30e5ef 100644
--- a/src/main/java/fr/xephi/authme/modules/Module.java
+++ b/src/main/java/fr/xephi/authme/modules/Module.java
@@ -1,28 +1,24 @@
package fr.xephi.authme.modules;
-import fr.xephi.authme.AuthMe;
+public abstract class Module {
-public interface Module {
-
- public String getName();
-
- public AuthMe getInstanceOfAuthMe();
-
- public Module getInstance();
-
- public enum ModuleType {
+ enum ModuleType {
MANAGER,
MYSQL,
REDIS,
ACTIONS,
CONVERTERS,
EMAILS,
- CUSTOM;
+ CUSTOM
}
- public ModuleType getType();
+ public abstract String getName();
- public boolean load();
+ public abstract ModuleType getType();
- public boolean unload();
+ public void load() {
+ }
+
+ public void unload() {
+ }
}
diff --git a/src/main/java/fr/xephi/authme/modules/ModuleManager.java b/src/main/java/fr/xephi/authme/modules/ModuleManager.java
index fc1d07f6..32d4d1fa 100644
--- a/src/main/java/fr/xephi/authme/modules/ModuleManager.java
+++ b/src/main/java/fr/xephi/authme/modules/ModuleManager.java
@@ -1,63 +1,80 @@
package fr.xephi.authme.modules;
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.ConsoleLogger;
+import fr.xephi.authme.settings.Settings;
+
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
+import java.util.Iterator;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.ConsoleLogger;
+public class ModuleManager {
-public class ModuleManager implements Module {
-
- private AuthMe plugin;
- private ModuleManager instance;
- private List modules = new ArrayList();
+ private List modules = new ArrayList<>();
public ModuleManager(AuthMe plugin) {
- this.plugin = plugin;
}
- @Override
- public String getName() {
- return "AuthMe Module Manager";
+ public boolean isModuleEnabled(String name) {
+ for (Module m : modules) {
+ if (m.getName().equalsIgnoreCase(name))
+ return true;
+ }
+ return false;
}
- @Override
- public AuthMe getInstanceOfAuthMe() {
- return this.plugin;
+ public boolean isModuleEnabled(Module.ModuleType type) {
+ for (Module m : modules) {
+ if (m.getType() == type)
+ return true;
+ }
+ return false;
}
- @Override
- public Module getInstance() {
- if (this.instance == null)
- instance = new ModuleManager(AuthMe.getInstance());
- return instance;
+ public Module getModule(String name) {
+ for (Module m : modules) {
+ if (m.getName().equalsIgnoreCase(name))
+ return m;
+ }
+ return null;
}
- @Override
- public ModuleType getType() {
- return (Module.ModuleType.MANAGER);
+ public Module getModule(Module.ModuleType type) {
+ for (Module m : modules) {
+ if (m.getType() == type)
+ return m;
+ }
+ return null;
}
- @Override
- public boolean load() {
- File dir = new File(plugin.getDataFolder() + File.separator + "modules");
- if (dir == null || !dir.exists() || !dir.isDirectory() || dir.listFiles() == null || dir.listFiles().length <= 0)
- return false;
- for (File pathToJar : dir.listFiles()) {
+ public int loadModules() {
+ File dir = Settings.MODULE_FOLDER;
+ int count = 0;
+ if (!dir.isDirectory()) {
+ dir.mkdirs();
+ return count;
+ }
+
+ File[] files = dir.listFiles();
+ if (files == null) {
+ return count;
+ }
+ for (File pathToJar : files) {
JarFile jarFile = null;
+ URLClassLoader cl = null;
try {
jarFile = new JarFile(pathToJar);
- Enumeration> e = jarFile.entries();
- URL[] urls = { new URL("jar:file:" + pathToJar.getAbsolutePath() + "!/") };
- URLClassLoader cl = URLClassLoader.newInstance(urls);
+ URL[] urls = {new URL("jar:file:" + pathToJar.getAbsolutePath() + "!/")};
+ cl = URLClassLoader.newInstance(urls);
+ Enumeration> e = jarFile.entries();
while (e.hasMoreElements()) {
JarEntry je = (JarEntry) e.nextElement();
if (je.isDirectory() || !je.getName().endsWith("Main.class")) {
@@ -66,35 +83,53 @@ public class ModuleManager implements Module {
String className = je.getName().substring(0, je.getName().length() - 6);
className = className.replace('/', '.');
Class> c = cl.loadClass(className);
+ if (!Module.class.isAssignableFrom(c)) {
+ continue;
+ }
+
Module mod = (Module) c.newInstance();
mod.load();
modules.add(mod);
+ count++;
break;
-
}
+
} catch (Exception ex) {
+ ConsoleLogger.writeStackTrace(ex);
ConsoleLogger.showError("Cannot load " + pathToJar.getName() + " jar file !");
} finally {
- if (jarFile != null)
- try {
+ try {
+ if (jarFile != null) {
jarFile.close();
- } catch (IOException e) {
}
+ if (cl != null) {
+ cl.close();
+ }
+ } catch (IOException ignored) {
+ }
}
}
- return true;
+ return count;
}
- @Override
- public boolean unload() {
- try {
- for (Module mod : modules) {
- mod.unload();
- modules.remove(mod);
+ public void unloadModule(String name) {
+ Iterator it = modules.iterator();
+ while (it.hasNext()) {
+ Module m = it.next();
+ if (m.getName().equalsIgnoreCase(name)) {
+ m.unload();
+ it.remove();
+ return;
}
- } catch (Exception e) {
}
- return true;
+ }
+
+ public void unloadModules() {
+ Iterator it = modules.iterator();
+ while (it.hasNext()) {
+ it.next().unload();
+ it.remove();
+ }
}
}
diff --git a/src/main/java/fr/xephi/authme/plugin/manager/BungeeCordMessage.java b/src/main/java/fr/xephi/authme/plugin/manager/BungeeCordMessage.java
index b1014077..59814738 100644
--- a/src/main/java/fr/xephi/authme/plugin/manager/BungeeCordMessage.java
+++ b/src/main/java/fr/xephi/authme/plugin/manager/BungeeCordMessage.java
@@ -1,14 +1,11 @@
package fr.xephi.authme.plugin.manager;
-import java.io.ByteArrayInputStream;
-import java.io.DataInputStream;
-import java.io.IOException;
-
+import com.google.common.io.ByteArrayDataInput;
+import com.google.common.io.ByteStreams;
+import fr.xephi.authme.AuthMe;
import org.bukkit.entity.Player;
import org.bukkit.plugin.messaging.PluginMessageListener;
-import fr.xephi.authme.AuthMe;
-
public class BungeeCordMessage implements PluginMessageListener {
public AuthMe plugin;
@@ -19,19 +16,16 @@ public class BungeeCordMessage implements PluginMessageListener {
@Override
public void onPluginMessageReceived(String channel, Player player,
- byte[] message) {
+ byte[] message) {
if (!channel.equals("BungeeCord")) {
return;
}
- try {
- final DataInputStream in = new DataInputStream(new ByteArrayInputStream(message));
- String subchannel = in.readUTF();
- if (subchannel.equals("IP")) { // We need only the IP channel
- String ip = in.readUTF();
- plugin.realIp.put(player.getName().toLowerCase(), ip);
- // Put the IP (only the ip not the port) in the hashmap
- }
- } catch (IOException ex) {
+ ByteArrayDataInput in = ByteStreams.newDataInput(message);
+ String subChannel = in.readUTF();
+ if (subChannel.equals("IP")) { // We need only the IP channel
+ String ip = in.readUTF();
+ // Put the IP (only the ip not the port) in the hashMap
+ plugin.realIp.put(player.getName().toLowerCase(), ip);
}
}
diff --git a/src/main/java/fr/xephi/authme/plugin/manager/CitizensCommunicator.java b/src/main/java/fr/xephi/authme/plugin/manager/CitizensCommunicator.java
deleted file mode 100644
index d09a5fcd..00000000
--- a/src/main/java/fr/xephi/authme/plugin/manager/CitizensCommunicator.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package fr.xephi.authme.plugin.manager;
-
-import org.bukkit.entity.Entity;
-
-import fr.xephi.authme.AuthMe;
-import net.citizensnpcs.api.CitizensAPI;
-
-public class CitizensCommunicator {
-
- public AuthMe instance;
-
- public CitizensCommunicator(AuthMe instance) {
- this.instance = instance;
- }
-
- public boolean isNPC(final Entity player) {
- if (!this.instance.isCitizensActive)
- return false;
- try {
- return CitizensAPI.getNPCRegistry().isNPC(player);
- } catch (NoClassDefFoundError ncdfe) {
- return false;
- } catch (Exception npe) {
- return false;
- }
- }
-}
diff --git a/src/main/java/fr/xephi/authme/plugin/manager/CombatTagComunicator.java b/src/main/java/fr/xephi/authme/plugin/manager/CombatTagComunicator.java
deleted file mode 100644
index ac80a632..00000000
--- a/src/main/java/fr/xephi/authme/plugin/manager/CombatTagComunicator.java
+++ /dev/null
@@ -1,49 +0,0 @@
-package fr.xephi.authme.plugin.manager;
-
-import org.bukkit.Bukkit;
-import org.bukkit.entity.Entity;
-import org.bukkit.entity.Player;
-import org.bukkit.plugin.Plugin;
-
-import com.trc202.CombatTag.CombatTag;
-import com.trc202.CombatTagApi.CombatTagApi;
-
-import fr.xephi.authme.AuthMe;
-import net.minelink.ctplus.CombatTagPlus;
-
-public abstract class CombatTagComunicator {
-
- public static CombatTagApi combatApi;
-
- /**
- * Returns if the entity is an NPC
- *
- * @param player
- * @return true if the player is an NPC
- */
- public static boolean isNPC(Entity player) {
- if (!AuthMe.getInstance().CombatTag)
- return false;
- try {
- if (Bukkit.getServer().getPluginManager().getPlugin("CombatTag") != null) {
- combatApi = new CombatTagApi((CombatTag) Bukkit.getServer().getPluginManager().getPlugin("CombatTag"));
- try {
- combatApi.getClass().getMethod("isNPC");
- } catch (Exception e) {
- return false;
- }
- return combatApi.isNPC(player);
- } else {
- Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("CombatTagPlus");
- return (plugin != null && plugin instanceof CombatTagPlus && player instanceof Player && ((CombatTagPlus) plugin).getNpcPlayerHelper().isNpc((Player) player));
- }
- } catch (ClassCastException ex) {
- return false;
- } catch (NullPointerException npe) {
- return false;
- } catch (NoClassDefFoundError ncdfe) {
- return false;
- }
- }
-
-}
diff --git a/src/main/java/fr/xephi/authme/process/Management.java b/src/main/java/fr/xephi/authme/process/Management.java
index 479790e5..209e12a9 100644
--- a/src/main/java/fr/xephi/authme/process/Management.java
+++ b/src/main/java/fr/xephi/authme/process/Management.java
@@ -30,8 +30,7 @@ public class Management {
this.pm = plugin.getServer().getPluginManager();
}
- public void performLogin(final Player player, final String password,
- final boolean forceLogin) {
+ public void performLogin(final Player player, final String password, final boolean forceLogin) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
@@ -41,8 +40,7 @@ public class Management {
});
}
- public void performRegister(final Player player, final String password,
- final String email) {
+ public void performRegister(final Player player, final String password, final String email) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
diff --git a/src/main/java/fr/xephi/authme/process/join/AsyncronousJoin.java b/src/main/java/fr/xephi/authme/process/join/AsyncronousJoin.java
index 3a3e8e1f..4df4928e 100644
--- a/src/main/java/fr/xephi/authme/process/join/AsyncronousJoin.java
+++ b/src/main/java/fr/xephi/authme/process/join/AsyncronousJoin.java
@@ -1,5 +1,25 @@
package fr.xephi.authme.process.join;
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.ConsoleLogger;
+import fr.xephi.authme.Utils;
+import fr.xephi.authme.Utils.GroupType;
+import fr.xephi.authme.cache.auth.PlayerAuth;
+import fr.xephi.authme.cache.auth.PlayerCache;
+import fr.xephi.authme.cache.backup.DataFileCache;
+import fr.xephi.authme.cache.backup.JsonCache;
+import fr.xephi.authme.cache.limbo.LimboCache;
+import fr.xephi.authme.cache.limbo.LimboPlayer;
+import fr.xephi.authme.datasource.DataSource;
+import fr.xephi.authme.events.FirstSpawnTeleportEvent;
+import fr.xephi.authme.events.ProtectInventoryEvent;
+import fr.xephi.authme.events.SpawnTeleportEvent;
+import fr.xephi.authme.listener.AuthMePlayerListener;
+import fr.xephi.authme.settings.Messages;
+import fr.xephi.authme.settings.Settings;
+import fr.xephi.authme.settings.Spawn;
+import fr.xephi.authme.task.MessageTask;
+import fr.xephi.authme.task.TimeoutTask;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
@@ -12,43 +32,20 @@ import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.ConsoleLogger;
-import fr.xephi.authme.Utils;
-import fr.xephi.authme.Utils.groupType;
-import fr.xephi.authme.cache.auth.PlayerAuth;
-import fr.xephi.authme.cache.auth.PlayerCache;
-import fr.xephi.authme.cache.backup.DataFileCache;
-import fr.xephi.authme.cache.backup.FileCache;
-import fr.xephi.authme.cache.limbo.LimboCache;
-import fr.xephi.authme.cache.limbo.LimboPlayer;
-import fr.xephi.authme.datasource.DataSource;
-import fr.xephi.authme.events.FirstSpawnTeleportEvent;
-import fr.xephi.authme.events.ProtectInventoryEvent;
-import fr.xephi.authme.events.SpawnTeleportEvent;
-import fr.xephi.authme.listener.AuthMePlayerListener;
-import fr.xephi.authme.plugin.manager.CombatTagComunicator;
-import fr.xephi.authme.settings.Messages;
-import fr.xephi.authme.settings.Settings;
-import fr.xephi.authme.settings.Spawn;
-import fr.xephi.authme.task.MessageTask;
-import fr.xephi.authme.task.TimeoutTask;
-
public class AsyncronousJoin {
protected Player player;
protected DataSource database;
protected AuthMe plugin;
protected String name;
- private Utils utils = Utils.getInstance();
private Messages m = Messages.getInstance();
- private FileCache playerBackup;
+ private JsonCache playerBackup;
public AsyncronousJoin(Player player, AuthMe plugin, DataSource database) {
this.player = player;
this.plugin = plugin;
this.database = database;
- this.playerBackup = new FileCache(plugin);
+ this.playerBackup = new JsonCache(plugin);
this.name = player.getName().toLowerCase();
}
@@ -58,15 +55,12 @@ public class AsyncronousJoin {
AuthMePlayerListener.gameMode.putIfAbsent(name, player.getGameMode());
BukkitScheduler sched = plugin.getServer().getScheduler();
- if (plugin.getCitizensCommunicator().isNPC(player) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) {
+ if (Utils.isNPC(player) || Utils.isUnrestricted(player)) {
return;
}
if (plugin.ess != null && Settings.disableSocialSpy) {
- try {
- plugin.ess.getUser(player.getName().toLowerCase()).setSocialSpyEnabled(false);
- } catch (NoSuchMethodError e) {
- }
+ plugin.ess.getUser(player).setSocialSpyEnabled(false);
}
final String ip = plugin.getIP(player);
@@ -100,7 +94,8 @@ public class AsyncronousJoin {
}
}
final Location spawnLoc = plugin.getSpawnLocation(player);
- if (database.isAuthAvailable(name)) {
+ final boolean isAuthAvailable = database.isAuthAvailable(name);
+ if (isAuthAvailable) {
if (Settings.isForceSurvivalModeEnabled && !Settings.forceOnlyAfterLogin) {
sched.scheduleSyncDelayedTask(plugin, new Runnable() {
@@ -132,52 +127,10 @@ public class AsyncronousJoin {
}
placePlayerSafely(player, spawnLoc);
LimboCache.getInstance().updateLimboPlayer(player);
- try {
- DataFileCache dataFile = new DataFileCache(LimboCache.getInstance().getLimboPlayer(name).getInventory(), LimboCache.getInstance().getLimboPlayer(name).getArmour());
- playerBackup.createCache(player, dataFile, LimboCache.getInstance().getLimboPlayer(name).getGroup(), LimboCache.getInstance().getLimboPlayer(name).getOperator(), LimboCache.getInstance().getLimboPlayer(name).isFlying());
- } catch (Exception e) {
- ConsoleLogger.showError("Error on creating an inventory cache for " + name + ", maybe inventory wipe in preparation...");
- }
- } else {
- if (Settings.isForceSurvivalModeEnabled && !Settings.forceOnlyAfterLogin) {
- sched.scheduleSyncDelayedTask(plugin, new Runnable() {
-
- @Override
- public void run() {
- AuthMePlayerListener.causeByAuthMe.putIfAbsent(name, true);
- Utils.forceGM(player);
- }
-
- });
- }
- if (!Settings.unRegisteredGroup.isEmpty()) {
- utils.setGroup(player, Utils.groupType.UNREGISTERED);
- }
- if (!Settings.isForcedRegistrationEnabled) {
- return;
- }
- if (!Settings.noTeleport)
- if (!needFirstspawn() && Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) {
- sched.scheduleSyncDelayedTask(plugin, new Runnable() {
-
- @Override
- public void run() {
- SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnLoc, PlayerCache.getInstance().isAuthenticated(name));
- plugin.getServer().getPluginManager().callEvent(tpEvent);
- if (!tpEvent.isCancelled()) {
- if (player.isOnline() && tpEvent.getTo() != null) {
- if (tpEvent.getTo().getWorld() != null)
- player.teleport(tpEvent.getTo());
- }
- }
- }
-
- });
- }
-
- }
- if (Settings.protectInventoryBeforeLogInEnabled) {
- try {
+ DataFileCache dataFile = new DataFileCache(LimboCache.getInstance().getLimboPlayer(name).getInventory(), LimboCache.getInstance().getLimboPlayer(name).getArmour());
+ playerBackup.createCache(player, dataFile);
+ // protect inventory
+ if (Settings.protectInventoryBeforeLogInEnabled) {
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(player.getName().toLowerCase());
ProtectInventoryEvent ev = new ProtectInventoryEvent(player, limbo.getInventory(), limbo.getArmour());
plugin.getServer().getPluginManager().callEvent(ev);
@@ -196,14 +149,49 @@ public class AsyncronousJoin {
});
}
- } catch (NullPointerException ex) {
}
+ } else {
+ if (Settings.isForceSurvivalModeEnabled && !Settings.forceOnlyAfterLogin) {
+ sched.scheduleSyncDelayedTask(plugin, new Runnable() {
+
+ @Override
+ public void run() {
+ AuthMePlayerListener.causeByAuthMe.putIfAbsent(name, true);
+ Utils.forceGM(player);
+ }
+
+ });
+ }
+ if (!Settings.unRegisteredGroup.isEmpty()) {
+ Utils.setGroup(player, Utils.GroupType.UNREGISTERED);
+ }
+ if (!Settings.isForcedRegistrationEnabled) {
+ return;
+ }
+ if (!Settings.noTeleport)
+ if (!needFirstspawn() && Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) {
+ sched.scheduleSyncDelayedTask(plugin, new Runnable() {
+ @Override
+ public void run() {
+ SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnLoc, PlayerCache.getInstance().isAuthenticated(name));
+ plugin.getServer().getPluginManager().callEvent(tpEvent);
+ if (!tpEvent.isCancelled()) {
+ if (player.isOnline() && tpEvent.getTo() != null) {
+ if (tpEvent.getTo().getWorld() != null)
+ player.teleport(tpEvent.getTo());
+ }
+ }
+ }
+
+ });
+ }
+
}
String[] msg;
if (Settings.emailRegistration) {
- msg = database.isAuthAvailable(name) ? m.send("login_msg") : m.send("reg_email_msg");
+ msg = isAuthAvailable ? m.send("login_msg") : m.send("reg_email_msg");
} else {
- msg = database.isAuthAvailable(name) ? m.send("login_msg") : m.send("reg_msg");
+ msg = isAuthAvailable ? m.send("login_msg") : m.send("reg_msg");
}
int time = Settings.getRegistrationTimeout * 20;
int msgInterval = Settings.getWarnMessageInterval;
@@ -215,10 +203,10 @@ public class AsyncronousJoin {
}
if (!LimboCache.getInstance().hasLimboPlayer(name))
LimboCache.getInstance().addLimboPlayer(player);
- if (database.isAuthAvailable(name)) {
- utils.setGroup(player, groupType.NOTLOGGEDIN);
+ if (isAuthAvailable) {
+ Utils.setGroup(player, GroupType.NOTLOGGEDIN);
} else {
- utils.setGroup(player, groupType.UNREGISTERED);
+ Utils.setGroup(player, GroupType.UNREGISTERED);
}
sched.scheduleSyncDelayedTask(plugin, new Runnable() {
@@ -235,10 +223,14 @@ public class AsyncronousJoin {
player.performCommand("motd");
if (Settings.applyBlindEffect)
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
+ if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
+ player.setWalkSpeed(0.0f);
+ player.setFlySpeed(0.0f);
+ }
}
});
- if (Settings.isSessionsEnabled && database.isAuthAvailable(name) && (PlayerCache.getInstance().isAuthenticated(name) || database.isLogged(name))) {
+ if (Settings.isSessionsEnabled && isAuthAvailable && (PlayerCache.getInstance().isAuthenticated(name) || database.isLogged(name))) {
if (plugin.sessions.containsKey(name))
plugin.sessions.get(name).cancel();
plugin.sessions.remove(name);
@@ -260,32 +252,31 @@ public class AsyncronousJoin {
}
private boolean needFirstspawn() {
- if (database.isAuthAvailable(player.getName().toLowerCase()) && player.hasPlayedBefore())
+ if (player.hasPlayedBefore())
return false;
- else {
- if (Spawn.getInstance().getFirstSpawn() == null || Spawn.getInstance().getFirstSpawn().getWorld() == null)
- return false;
- FirstSpawnTeleportEvent tpEvent = new FirstSpawnTeleportEvent(player, player.getLocation(), Spawn.getInstance().getFirstSpawn());
- plugin.getServer().getPluginManager().callEvent(tpEvent);
- if (!tpEvent.isCancelled()) {
- if (player.isOnline() && tpEvent.getTo() != null && tpEvent.getTo().getWorld() != null) {
- final Location fLoc = tpEvent.getTo();
- Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
+ if (Spawn.getInstance().getFirstSpawn() == null || Spawn.getInstance().getFirstSpawn().getWorld() == null)
+ return false;
+ FirstSpawnTeleportEvent tpEvent = new FirstSpawnTeleportEvent(player, player.getLocation(), Spawn.getInstance().getFirstSpawn());
+ plugin.getServer().getPluginManager().callEvent(tpEvent);
+ if (!tpEvent.isCancelled()) {
+ if (player.isOnline() && tpEvent.getTo() != null && tpEvent.getTo().getWorld() != null) {
+ final Location fLoc = tpEvent.getTo();
+ Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
- @Override
- public void run() {
- player.teleport(fLoc);
- }
+ @Override
+ public void run() {
+ player.teleport(fLoc);
+ }
- });
- }
+ });
}
- return true;
}
+ return true;
+
}
private void placePlayerSafely(final Player player,
- final Location spawnLoc) {
+ final Location spawnLoc) {
Location loc = null;
if (spawnLoc == null)
return;
@@ -293,7 +284,7 @@ public class AsyncronousJoin {
return;
if (Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName())))
return;
- if (!database.isAuthAvailable(player.getName().toLowerCase()) || !player.hasPlayedBefore())
+ if (!player.hasPlayedBefore())
return;
Block b = player.getLocation().getBlock();
if (b.getType() == Material.PORTAL || b.getType() == Material.ENDER_PORTAL) {
diff --git a/src/main/java/fr/xephi/authme/process/login/AsyncronousLogin.java b/src/main/java/fr/xephi/authme/process/login/AsyncronousLogin.java
index 302203b7..e25c8457 100644
--- a/src/main/java/fr/xephi/authme/process/login/AsyncronousLogin.java
+++ b/src/main/java/fr/xephi/authme/process/login/AsyncronousLogin.java
@@ -1,14 +1,8 @@
package fr.xephi.authme.process.login;
-import java.util.Date;
-import java.util.List;
-
-import org.bukkit.Bukkit;
-import org.bukkit.entity.Player;
-import org.bukkit.scheduler.BukkitTask;
-
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
+import fr.xephi.authme.Utils;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.limbo.LimboCache;
@@ -20,6 +14,12 @@ import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.MessageTask;
+import org.bukkit.Bukkit;
+import org.bukkit.entity.Player;
+import org.bukkit.scheduler.BukkitTask;
+
+import java.util.Date;
+import java.util.List;
public class AsyncronousLogin {
@@ -34,7 +34,7 @@ public class AsyncronousLogin {
private Messages m = Messages.getInstance();
public AsyncronousLogin(Player player, String password, boolean forceLogin,
- AuthMe plugin, DataSource data) {
+ AuthMe plugin, DataSource data) {
this.player = player;
this.password = password;
name = player.getName().toLowerCase();
@@ -63,13 +63,9 @@ public class AsyncronousLogin {
player.sendMessage(s.replace("THE_CAPTCHA", plugin.cap.get(name)).replace("", plugin.cap.get(name)));
}
return true;
- } else
- if (plugin.captcha.containsKey(name) && plugin.captcha.get(name) >= Settings.maxLoginTry) {
- try {
- plugin.captcha.remove(name);
- plugin.cap.remove(name);
- } catch (NullPointerException npe) {
- }
+ } else if (plugin.captcha.containsKey(name) && plugin.captcha.get(name) >= Settings.maxLoginTry) {
+ plugin.captcha.remove(name);
+ plugin.cap.remove(name);
}
}
return false;
@@ -197,7 +193,6 @@ public class AsyncronousLogin {
});
} else {
m.send(player, "wrong_pwd");
- return;
}
} else {
ConsoleLogger.showError("Player " + name + " wasn't online during login process, aborted... ");
@@ -220,17 +215,17 @@ public class AsyncronousLogin {
if (auths.size() == 1) {
return;
}
- String message = "[AuthMe] ";
+ StringBuilder message = new StringBuilder("[AuthMe] ");
// String uuidaccounts =
// "[AuthMe] PlayerNames has %size% links to this UUID : ";
int i = 0;
for (String account : auths) {
i++;
- message = message + account;
+ message.append(account);
if (i != auths.size()) {
- message = message + ", ";
+ message.append(", ");
} else {
- message = message + ".";
+ message.append(".");
}
}
/*
@@ -239,10 +234,10 @@ public class AsyncronousLogin {
* uuidaccounts = uuidaccounts + ", "; } else { uuidaccounts =
* uuidaccounts + "."; } }
*/
- for (Player player : plugin.getServer().getOnlinePlayers()) {
+ for (Player player : Utils.getOnlinePlayers()) {
if (plugin.authmePermissible(player, "authme.seeOtherAccounts")) {
player.sendMessage("[AuthMe] The player " + auth.getNickname() + " has " + auths.size() + " accounts");
- player.sendMessage(message);
+ player.sendMessage(message.toString());
// player.sendMessage(uuidaccounts.replace("%size%",
// ""+uuidlist.size()));
}
diff --git a/src/main/java/fr/xephi/authme/process/login/ProcessSyncronousPlayerLogin.java b/src/main/java/fr/xephi/authme/process/login/ProcessSyncronousPlayerLogin.java
index 276a8c23..28f9a861 100644
--- a/src/main/java/fr/xephi/authme/process/login/ProcessSyncronousPlayerLogin.java
+++ b/src/main/java/fr/xephi/authme/process/login/ProcessSyncronousPlayerLogin.java
@@ -9,9 +9,9 @@ import org.bukkit.potion.PotionEffectType;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils;
-import fr.xephi.authme.Utils.groupType;
+import fr.xephi.authme.Utils.GroupType;
import fr.xephi.authme.cache.auth.PlayerAuth;
-import fr.xephi.authme.cache.backup.FileCache;
+import fr.xephi.authme.cache.backup.JsonCache;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.cache.limbo.LimboPlayer;
import fr.xephi.authme.datasource.DataSource;
@@ -31,7 +31,7 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
private AuthMe plugin;
private DataSource database;
private PluginManager pm;
- private FileCache playerCache;
+ private JsonCache playerCache;
public ProcessSyncronousPlayerLogin(Player player, AuthMe plugin,
DataSource data) {
@@ -42,7 +42,7 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
this.name = player.getName().toLowerCase();
this.limbo = LimboCache.getInstance().getLimboPlayer(name);
this.auth = database.getAuth(name);
- this.playerCache = new FileCache(plugin);
+ this.playerCache = new JsonCache(plugin);
}
public LimboPlayer getLimbo() {
@@ -63,7 +63,7 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
}
protected void packQuitLocation() {
- Utils.getInstance().packCoords(auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ(), auth.getWorld(), player);
+ Utils.packCoords(auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ(), auth.getWorld(), player);
}
protected void teleportBackFromSpawn() {
@@ -103,7 +103,7 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
for (String command : Settings.forceCommands) {
try {
player.performCommand(command.replace("%p", player.getName()));
- } catch (Exception e) {
+ } catch (Exception ignored) {
}
}
for (String command : Settings.forceCommandsAsConsole) {
@@ -125,20 +125,13 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
* world inventory !
*/
player.setGameMode(limbo.getGameMode());
- if (!Settings.forceOnlyAfterLogin) {
- // Inventory - Make it after restore GameMode , cause we need to
- // restore the
- // right inventory in the right gamemode
- if (Settings.protectInventoryBeforeLogInEnabled && player.hasPlayedBefore()) {
- restoreInventory();
- }
- } else {
- // Inventory - Make it before force the survival GameMode to
- // cancel all
- // inventory problem
- if (Settings.protectInventoryBeforeLogInEnabled && player.hasPlayedBefore()) {
- restoreInventory();
- }
+ // Inventory - Make it after restore GameMode , cause we need to
+ // restore the
+ // right inventory in the right gamemode
+ if (Settings.protectInventoryBeforeLogInEnabled && player.hasPlayedBefore()) {
+ restoreInventory();
+ }
+ if (Settings.forceOnlyAfterLogin) {
player.setGameMode(GameMode.SURVIVAL);
}
@@ -166,7 +159,7 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
Utils.forceGM(player);
// Restore Permission Group
- Utils.getInstance().setGroup(player, groupType.LOGGEDIN);
+ Utils.setGroup(player, GroupType.LOGGEDIN);
// Cleanup no longer used temporary data
LimboCache.getInstance().deleteLimboPlayer(name);
@@ -177,7 +170,7 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
// We can now display the join message
if (AuthMePlayerListener.joinMessage.containsKey(name) && AuthMePlayerListener.joinMessage.get(name) != null && !AuthMePlayerListener.joinMessage.get(name).isEmpty()) {
- for (Player p : Bukkit.getServer().getOnlinePlayers()) {
+ for (Player p : Utils.getOnlinePlayers()) {
if (p.isOnline())
p.sendMessage(AuthMePlayerListener.joinMessage.get(name));
}
@@ -186,6 +179,10 @@ public class ProcessSyncronousPlayerLogin implements Runnable {
if (Settings.applyBlindEffect)
player.removePotionEffect(PotionEffectType.BLINDNESS);
+ if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
+ player.setWalkSpeed(0.2f);
+ player.setFlySpeed(0.1f);
+ }
// The Loginevent now fires (as intended) after everything is processed
Bukkit.getServer().getPluginManager().callEvent(new LoginEvent(player, true));
diff --git a/src/main/java/fr/xephi/authme/process/logout/AsyncronousLogout.java b/src/main/java/fr/xephi/authme/process/logout/AsyncronousLogout.java
index d9931171..d1f890ad 100644
--- a/src/main/java/fr/xephi/authme/process/logout/AsyncronousLogout.java
+++ b/src/main/java/fr/xephi/authme/process/logout/AsyncronousLogout.java
@@ -6,11 +6,11 @@ import org.bukkit.scheduler.BukkitScheduler;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.Utils;
-import fr.xephi.authme.Utils.groupType;
+import fr.xephi.authme.Utils.GroupType;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.backup.DataFileCache;
-import fr.xephi.authme.cache.backup.FileCache;
+import fr.xephi.authme.cache.backup.JsonCache;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.AuthMeTeleportEvent;
@@ -25,8 +25,7 @@ public class AsyncronousLogout {
protected DataSource database;
protected boolean canLogout = true;
private Messages m = Messages.getInstance();
- private Utils utils = Utils.getInstance();
- private FileCache playerBackup;
+ private JsonCache playerBackup;
public AsyncronousLogout(Player player, AuthMe plugin,
DataSource database) {
@@ -34,7 +33,7 @@ public class AsyncronousLogout {
this.plugin = plugin;
this.database = database;
this.name = player.getName().toLowerCase();
- this.playerBackup = new FileCache(plugin);
+ this.playerBackup = new JsonCache(plugin);
}
private void preLogout() {
@@ -79,14 +78,13 @@ public class AsyncronousLogout {
if (LimboCache.getInstance().hasLimboPlayer(name))
LimboCache.getInstance().deleteLimboPlayer(name);
LimboCache.getInstance().addLimboPlayer(player);
- utils.setGroup(player, groupType.NOTLOGGEDIN);
+ Utils.setGroup(player, GroupType.NOTLOGGEDIN);
if (Settings.protectInventoryBeforeLogInEnabled) {
player.getInventory().clear();
// create cache file for handling lost of inventories on unlogged in
// status
DataFileCache playerData = new DataFileCache(LimboCache.getInstance().getLimboPlayer(name).getInventory(), LimboCache.getInstance().getLimboPlayer(name).getArmour());
- if (playerData != null)
- playerBackup.createCache(player, playerData, LimboCache.getInstance().getLimboPlayer(name).getGroup(), LimboCache.getInstance().getLimboPlayer(name).getOperator(), LimboCache.getInstance().getLimboPlayer(name).isFlying());
+ playerBackup.createCache(player, playerData);
}
sched.scheduleSyncDelayedTask(plugin, new ProcessSyncronousPlayerLogout(p, plugin));
}
diff --git a/src/main/java/fr/xephi/authme/process/logout/ProcessSyncronousPlayerLogout.java b/src/main/java/fr/xephi/authme/process/logout/ProcessSyncronousPlayerLogout.java
index 4cac3864..7c199201 100644
--- a/src/main/java/fr/xephi/authme/process/logout/ProcessSyncronousPlayerLogout.java
+++ b/src/main/java/fr/xephi/authme/process/logout/ProcessSyncronousPlayerLogout.java
@@ -43,22 +43,23 @@ public class ProcessSyncronousPlayerLogout implements Runnable {
}
BukkitTask msgT = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("login_msg"), interval));
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT);
- try {
- if (player.isInsideVehicle())
- player.getVehicle().eject();
- } catch (NullPointerException npe) {
- }
+ if (player.isInsideVehicle() && player.getVehicle() != null)
+ player.getVehicle().eject();
if (Settings.applyBlindEffect)
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
player.setOp(false);
if (!Settings.isMovementAllowed) {
player.setAllowFlight(true);
player.setFlying(true);
+ if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
+ player.setFlySpeed(0.0f);
+ player.setWalkSpeed(0.0f);
+ }
}
// Player is now logout... Time to fire event !
Bukkit.getServer().getPluginManager().callEvent(new LogoutEvent(player));
m.send(player, "logout");
- ConsoleLogger.info(player.getDisplayName() + " logged out");
+ ConsoleLogger.info(player.getName() + " logged out");
}
}
diff --git a/src/main/java/fr/xephi/authme/process/quit/AsyncronousQuit.java b/src/main/java/fr/xephi/authme/process/quit/AsyncronousQuit.java
index dd84fdc8..da594606 100644
--- a/src/main/java/fr/xephi/authme/process/quit/AsyncronousQuit.java
+++ b/src/main/java/fr/xephi/authme/process/quit/AsyncronousQuit.java
@@ -15,7 +15,6 @@ import fr.xephi.authme.cache.limbo.LimboPlayer;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.RestoreInventoryEvent;
import fr.xephi.authme.listener.AuthMePlayerListener;
-import fr.xephi.authme.plugin.manager.CombatTagComunicator;
import fr.xephi.authme.settings.Settings;
public class AsyncronousQuit {
@@ -23,7 +22,6 @@ public class AsyncronousQuit {
protected AuthMe plugin;
protected DataSource database;
protected Player player;
- protected Utils utils = Utils.getInstance();
private String name;
private ItemStack[] armor = null;
private ItemStack[] inv = null;
@@ -44,7 +42,7 @@ public class AsyncronousQuit {
public void process() {
if (player == null)
return;
- if (plugin.getCitizensCommunicator().isNPC(player) || Utils.getInstance().isUnrestricted(player) || CombatTagComunicator.isNPC(player)) {
+ if (Utils.isNPC(player) || Utils.isUnrestricted(player)) {
return;
}
@@ -67,7 +65,7 @@ public class AsyncronousQuit {
armor = limbo.getArmour();
}
if (limbo.getGroup() != null && !limbo.getGroup().equals(""))
- utils.addNormal(player, limbo.getGroup());
+ Utils.addNormal(player, limbo.getGroup());
needToChange = true;
isOp = limbo.getOperator();
isFlying = limbo.isFlying();
diff --git a/src/main/java/fr/xephi/authme/process/register/AsyncronousRegister.java b/src/main/java/fr/xephi/authme/process/register/AsyncronousRegister.java
index 72f14459..255c696d 100644
--- a/src/main/java/fr/xephi/authme/process/register/AsyncronousRegister.java
+++ b/src/main/java/fr/xephi/authme/process/register/AsyncronousRegister.java
@@ -112,7 +112,7 @@ public class AsyncronousRegister {
return;
}
}
- PlayerAuth auth = null;
+ PlayerAuth auth;
try {
final String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, password, name);
auth = new PlayerAuth(name, hashnew, getIp(), 0, (int) player.getLocation().getX(), (int) player.getLocation().getY(), (int) player.getLocation().getZ(), player.getLocation().getWorld().getName(), email, player.getName());
@@ -130,12 +130,11 @@ public class AsyncronousRegister {
plugin.mail.main(auth, password);
ProcessSyncronousEmailRegister syncronous = new ProcessSyncronousEmailRegister(player, plugin);
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, syncronous);
- return;
}
protected void passwordRegister() {
- PlayerAuth auth = null;
- String hash = "";
+ PlayerAuth auth;
+ String hash;
try {
hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name);
} catch (NoSuchAlgorithmException e) {
@@ -159,6 +158,5 @@ public class AsyncronousRegister {
plugin.otherAccounts.addPlayer(player.getUniqueId());
ProcessSyncronousPasswordRegister syncronous = new ProcessSyncronousPasswordRegister(player, plugin);
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, syncronous);
- return;
}
}
diff --git a/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousEmailRegister.java b/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousEmailRegister.java
index 96a200c2..280daa29 100644
--- a/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousEmailRegister.java
+++ b/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousEmailRegister.java
@@ -31,7 +31,7 @@ public class ProcessSyncronousEmailRegister implements Runnable {
public void run() {
LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
if (!Settings.getRegisteredGroup.isEmpty()) {
- Utils.getInstance().setGroup(player, Utils.groupType.REGISTERED);
+ Utils.setGroup(player, Utils.GroupType.REGISTERED);
}
m.send(player, "vb_nonActiv");
int time = Settings.getRegistrationTimeout * 20;
@@ -39,12 +39,12 @@ public class ProcessSyncronousEmailRegister implements Runnable {
BukkitScheduler sched = plugin.getServer().getScheduler();
if (time != 0 && limbo != null) {
- limbo.getTimeoutTaskId().cancel();
+ limbo.getTimeoutTaskId().cancel();
BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), time);
limbo.setTimeoutTaskId(id);
}
if (limbo != null){
- limbo.getMessageTaskId().cancel();
+ limbo.getMessageTaskId().cancel();
BukkitTask nwMsg = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("login_msg"), msgInterval));
limbo.setMessageTaskId(nwMsg);
}
diff --git a/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousPasswordRegister.java b/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousPasswordRegister.java
index c8b64ed6..5a7a1353 100644
--- a/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousPasswordRegister.java
+++ b/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousPasswordRegister.java
@@ -1,13 +1,5 @@
package fr.xephi.authme.process.register;
-import org.bukkit.Bukkit;
-import org.bukkit.GameMode;
-import org.bukkit.Location;
-import org.bukkit.entity.Player;
-import org.bukkit.potion.PotionEffectType;
-import org.bukkit.scheduler.BukkitScheduler;
-import org.bukkit.scheduler.BukkitTask;
-
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.Utils;
@@ -21,6 +13,13 @@ import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.MessageTask;
import fr.xephi.authme.task.TimeoutTask;
+import org.bukkit.Bukkit;
+import org.bukkit.GameMode;
+import org.bukkit.Location;
+import org.bukkit.entity.Player;
+import org.bukkit.potion.PotionEffectType;
+import org.bukkit.scheduler.BukkitScheduler;
+import org.bukkit.scheduler.BukkitTask;
public class ProcessSyncronousPasswordRegister implements Runnable {
@@ -39,7 +38,7 @@ public class ProcessSyncronousPasswordRegister implements Runnable {
for (String command : Settings.forceRegisterCommands) {
try {
player.performCommand(command.replace("%p", player.getName()));
- } catch (Exception e) {
+ } catch (Exception ignored) {
}
}
for (String command : Settings.forceRegisterCommandsAsConsole) {
@@ -71,10 +70,8 @@ public class ProcessSyncronousPasswordRegister implements Runnable {
}
BukkitTask msgT = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("login_msg"), interval));
LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT);
- try {
- if (player.isInsideVehicle())
- player.getVehicle().eject();
- } catch (NullPointerException npe) {
+ if (player.isInsideVehicle() && player.getVehicle() != null) {
+ player.getVehicle().eject();
}
}
@@ -108,7 +105,7 @@ public class ProcessSyncronousPasswordRegister implements Runnable {
}
if (!Settings.getRegisteredGroup.isEmpty()) {
- Utils.getInstance().setGroup(player, Utils.groupType.REGISTERED);
+ Utils.setGroup(player, Utils.GroupType.REGISTERED);
}
m.send(player, "registered");
if (!Settings.getmailAccount.isEmpty())
@@ -119,8 +116,12 @@ public class ProcessSyncronousPasswordRegister implements Runnable {
}
if (Settings.applyBlindEffect)
player.removePotionEffect(PotionEffectType.BLINDNESS);
- // The Loginevent now fires (as intended) after everything is processed
- Bukkit.getServer().getPluginManager().callEvent(new LoginEvent(player, true));
+ if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
+ player.setWalkSpeed(0.2f);
+ player.setFlySpeed(0.1f);
+ }
+ // The LoginEvent now fires (as intended) after everything is processed
+ plugin.getServer().getPluginManager().callEvent(new LoginEvent(player, true));
player.saveData();
if (!Settings.noConsoleSpam)
@@ -132,7 +133,7 @@ public class ProcessSyncronousPasswordRegister implements Runnable {
return;
}
- // Request Login after Registation
+ // Request Login after Registration
if (Settings.forceRegLogin) {
forceLogin(player);
return;
@@ -142,7 +143,7 @@ public class ProcessSyncronousPasswordRegister implements Runnable {
if (Settings.useWelcomeMessage)
if (Settings.broadcastWelcomeMessage) {
for (String s : Settings.welcomeMsg) {
- Bukkit.getServer().broadcastMessage(plugin.replaceAllInfos(s, player));
+ plugin.getServer().broadcastMessage(plugin.replaceAllInfos(s, player));
}
} else {
for (String s : Settings.welcomeMsg) {
diff --git a/src/main/java/fr/xephi/authme/security/HashAlgorithm.java b/src/main/java/fr/xephi/authme/security/HashAlgorithm.java
index 312b6df0..935c9c1c 100644
--- a/src/main/java/fr/xephi/authme/security/HashAlgorithm.java
+++ b/src/main/java/fr/xephi/authme/security/HashAlgorithm.java
@@ -25,6 +25,7 @@ public enum HashAlgorithm {
SHA512(fr.xephi.authme.security.crypts.SHA512.class),
DOUBLEMD5(fr.xephi.authme.security.crypts.DOUBLEMD5.class),
PBKDF2(fr.xephi.authme.security.crypts.CryptPBKDF2.class),
+ PBKDF2DJANGO(fr.xephi.authme.security.crypts.CryptPBKDF2Django.class),
WORDPRESS(fr.xephi.authme.security.crypts.WORDPRESS.class),
ROYALAUTH(fr.xephi.authme.security.crypts.ROYALAUTH.class),
CRAZYCRYPT1(fr.xephi.authme.security.crypts.CRAZYCRYPT1.class),
diff --git a/src/main/java/fr/xephi/authme/security/PasswordSecurity.java b/src/main/java/fr/xephi/authme/security/PasswordSecurity.java
index 305b89b6..a95a848d 100644
--- a/src/main/java/fr/xephi/authme/security/PasswordSecurity.java
+++ b/src/main/java/fr/xephi/authme/security/PasswordSecurity.java
@@ -1,24 +1,23 @@
package fr.xephi.authme.security;
-import java.math.BigInteger;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.security.SecureRandom;
-import java.util.HashMap;
-
-import org.bukkit.Bukkit;
-
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.events.PasswordEncryptionEvent;
import fr.xephi.authme.security.crypts.BCRYPT;
import fr.xephi.authme.security.crypts.EncryptionMethod;
import fr.xephi.authme.settings.Settings;
+import org.bukkit.Bukkit;
+
+import java.math.BigInteger;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.util.HashMap;
public class PasswordSecurity {
private static SecureRandom rnd = new SecureRandom();
- public static HashMap userSalt = new HashMap();
+ public static HashMap userSalt = new HashMap<>();
public static String createSalt(int length)
throws NoSuchAlgorithmException {
@@ -31,15 +30,13 @@ public class PasswordSecurity {
}
public static String getHash(HashAlgorithm alg, String password,
- String playerName) throws NoSuchAlgorithmException {
+ String playerName) throws NoSuchAlgorithmException {
EncryptionMethod method;
try {
if (alg != HashAlgorithm.CUSTOM)
method = (EncryptionMethod) alg.getclasse().newInstance();
else method = null;
- } catch (InstantiationException e) {
- throw new NoSuchAlgorithmException("Problem with this hash algorithm");
- } catch (IllegalAccessException e) {
+ } catch (InstantiationException | IllegalAccessException e) {
throw new NoSuchAlgorithmException("Problem with this hash algorithm");
}
String salt = "";
@@ -85,6 +82,7 @@ public class PasswordSecurity {
salt = BCRYPT.gensalt(8);
userSalt.put(playerName, salt);
break;
+ case PBKDF2DJANGO:
case PBKDF2:
salt = createSalt(12);
userSalt.put(playerName, salt);
@@ -127,43 +125,39 @@ public class PasswordSecurity {
}
public static boolean comparePasswordWithHash(String password, String hash,
- String playerName) throws NoSuchAlgorithmException {
+ String playerName) throws NoSuchAlgorithmException {
HashAlgorithm algo = Settings.getPasswordHash;
EncryptionMethod method;
try {
if (algo != HashAlgorithm.CUSTOM)
method = (EncryptionMethod) algo.getclasse().newInstance();
- else method = null;
- } catch (InstantiationException e) {
- throw new NoSuchAlgorithmException("Problem with this hash algorithm");
- } catch (IllegalAccessException e) {
- throw new NoSuchAlgorithmException("Problem with this hash algorithm");
- }
- PasswordEncryptionEvent event = new PasswordEncryptionEvent(method, playerName);
- Bukkit.getPluginManager().callEvent(event);
- method = event.getMethod();
- if (method == null)
- throw new NoSuchAlgorithmException("Unknown hash algorithm");
+ else
+ method = null;
+
+ PasswordEncryptionEvent event = new PasswordEncryptionEvent(method, playerName);
+ Bukkit.getPluginManager().callEvent(event);
+ method = event.getMethod();
+
+ if (method == null)
+ throw new NoSuchAlgorithmException("Unknown hash algorithm");
- try {
if (method.comparePassword(hash, password, playerName))
return true;
- } catch (Exception e) {
- }
- if (Settings.supportOldPassword) {
- try {
+
+ if (Settings.supportOldPassword) {
if (compareWithAllEncryptionMethod(password, hash, playerName))
return true;
- } catch (Exception e) {
}
+ } catch (InstantiationException | IllegalAccessException e) {
+ throw new NoSuchAlgorithmException("Problem with this hash algorithm");
}
return false;
}
private static boolean compareWithAllEncryptionMethod(String password,
- String hash, String playerName) throws NoSuchAlgorithmException {
+ String hash, String playerName) throws NoSuchAlgorithmException {
for (HashAlgorithm algo : HashAlgorithm.values()) {
- if (algo != HashAlgorithm.CUSTOM)
+ if (algo != HashAlgorithm.CUSTOM) {
try {
EncryptionMethod method = (EncryptionMethod) algo.getclasse().newInstance();
if (method.comparePassword(hash, password, playerName)) {
@@ -176,8 +170,9 @@ public class PasswordSecurity {
}
return true;
}
- } catch (Exception e) {
+ } catch (Exception ignored) {
}
+ }
}
return false;
}
diff --git a/src/main/java/fr/xephi/authme/security/crypts/BCRYPT.java b/src/main/java/fr/xephi/authme/security/crypts/BCRYPT.java
index 847e9951..7f420c00 100644
--- a/src/main/java/fr/xephi/authme/security/crypts/BCRYPT.java
+++ b/src/main/java/fr/xephi/authme/security/crypts/BCRYPT.java
@@ -69,17 +69,17 @@ public class BCRYPT implements EncryptionMethod {
private static final int BLOWFISH_NUM_ROUNDS = 16;
// Initial contents of key schedule
- private static final int P_orig[] = { 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b };
- private static final int S_orig[] = { 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a, 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7, 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0, 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 };
+ private static final int P_orig[] = {0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b};
+ private static final int S_orig[] = {0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a, 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7, 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0, 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6};
// bcrypt IV: "OrpheanBeholderScryDoubt"
- static private final int bf_crypt_ciphertext[] = { 0x4f727068, 0x65616e42, 0x65686f6c, 0x64657253, 0x63727944, 0x6f756274 };
+ static private final int bf_crypt_ciphertext[] = {0x4f727068, 0x65616e42, 0x65686f6c, 0x64657253, 0x63727944, 0x6f756274};
// Table for Base64 encoding
- static private final char base64_code[] = { '.', '/', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
+ static private final char base64_code[] = {'.', '/', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
// Table for Base64 decoding
- static private final byte index_64[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, -1, -1, -1, -1, -1, -1, -1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, -1, -1, -1, -1, -1, -1, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, -1, -1, -1, -1, -1 };
+ static private final byte index_64[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, -1, -1, -1, -1, -1, -1, -1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, -1, -1, -1, -1, -1, -1, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, -1, -1, -1, -1, -1};
// Expanded Blowfish key
private int P[];
@@ -90,13 +90,10 @@ public class BCRYPT implements EncryptionMethod {
* scheme. Note that this is *not* compatible with the standard MIME-base64
* encoding.
*
- * @param d
- * the byte array to encode
- * @param len
- * the number of bytes to encode
+ * @param d the byte array to encode
+ * @param len the number of bytes to encode
* @return base64-encoded string
- * @exception IllegalArgumentException
- * if the length is invalid
+ * @throws IllegalArgumentException if the length is invalid
*/
private static String encode_base64(byte d[], int len)
throws IllegalArgumentException {
@@ -134,9 +131,8 @@ public class BCRYPT implements EncryptionMethod {
/**
* Look up the 3 bits base64-encoded by the specified character,
* range-checking againt conversion table
- *
- * @param x
- * the base64-encoded value
+ *
+ * @param x the base64-encoded value
* @return the decoded value of x
*/
private static byte char64(char x) {
@@ -149,14 +145,11 @@ public class BCRYPT implements EncryptionMethod {
* Decode a string encoded using bcrypt's base64 scheme to a byte array.
* Note that this is *not* compatible with the standard MIME-base64
* encoding.
- *
- * @param s
- * the string to decode
- * @param maxolen
- * the maximum number of bytes to decode
+ *
+ * @param s the string to decode
+ * @param maxolen the maximum number of bytes to decode
* @return an array containing the decoded bytes
- * @throws IllegalArgumentException
- * if maxolen is invalid
+ * @throws IllegalArgumentException if maxolen is invalid
*/
private static byte[] decode_base64(String s, int maxolen)
throws IllegalArgumentException {
@@ -201,17 +194,15 @@ public class BCRYPT implements EncryptionMethod {
/**
* Blowfish encipher a single 64-bit block encoded as two 32-bit halves
- *
- * @param lr
- * an array containing the two 32-bit half blocks
- * @param off
- * the position in the array of the blocks
+ *
+ * @param lr an array containing the two 32-bit half blocks
+ * @param off the position in the array of the blocks
*/
private final void encipher(int lr[], int off) {
int i, n, l = lr[off], r = lr[off + 1];
l ^= P[0];
- for (i = 0; i <= BLOWFISH_NUM_ROUNDS - 2;) {
+ for (i = 0; i <= BLOWFISH_NUM_ROUNDS - 2; ) {
// Feistel substitution on left word
n = S[(l >> 24) & 0xff];
n += S[0x100 | ((l >> 16) & 0xff)];
@@ -232,12 +223,10 @@ public class BCRYPT implements EncryptionMethod {
/**
* Cycically extract a word of key material
- *
- * @param data
- * the string to extract the data from
- * @param offp
- * a "pointer" (as a one-entry array) to the current offset into
- * data
+ *
+ * @param data the string to extract the data from
+ * @param offp a "pointer" (as a one-entry array) to the current offset into
+ * data
* @return the next word of material from data
*/
private static int streamtoword(byte data[], int offp[]) {
@@ -264,14 +253,13 @@ public class BCRYPT implements EncryptionMethod {
/**
* Key the Blowfish cipher
- *
- * @param key
- * an array containing the key
+ *
+ * @param key an array containing the key
*/
private void key(byte key[]) {
int i;
- int koffp[] = { 0 };
- int lr[] = { 0, 0 };
+ int koffp[] = {0};
+ int lr[] = {0, 0};
int plen = P.length, slen = S.length;
for (i = 0; i < plen; i++)
@@ -294,16 +282,14 @@ public class BCRYPT implements EncryptionMethod {
* Perform the "enhanced key schedule" step described by Provos and Mazieres
* in "A Future-Adaptable Password Scheme"
* http://www.openbsd.org/papers/bcrypt-paper.ps
- *
- * @param data
- * salt information
- * @param key
- * password information
+ *
+ * @param data salt information
+ * @param key password information
*/
private void ekskey(byte data[], byte key[]) {
int i;
- int koffp[] = { 0 }, doffp[] = { 0 };
- int lr[] = { 0, 0 };
+ int koffp[] = {0}, doffp[] = {0};
+ int lr[] = {0, 0};
int plen = P.length, slen = S.length;
for (i = 0; i < plen; i++)
@@ -328,14 +314,11 @@ public class BCRYPT implements EncryptionMethod {
/**
* Perform the central password hashing step in the bcrypt scheme
- *
- * @param password
- * the password to hash
- * @param salt
- * the binary salt to hash with the password
- * @param log_rounds
- * the binary logarithm of the number of rounds of hashing to
- * apply
+ *
+ * @param password the password to hash
+ * @param salt the binary salt to hash with the password
+ * @param log_rounds the binary logarithm of the number of rounds of hashing to
+ * apply
* @return an array containing the binary hashed password
*/
private byte[] crypt_raw(byte password[], byte salt[], int log_rounds) {
@@ -374,11 +357,9 @@ public class BCRYPT implements EncryptionMethod {
/**
* Hash a password using the OpenBSD bcrypt scheme
- *
- * @param password
- * the password to hash
- * @param salt
- * the salt to hash with (perhaps generated using BCrypt.gensalt)
+ *
+ * @param password the password to hash
+ * @param salt the salt to hash with (perhaps generated using BCrypt.gensalt)
* @return the hashed password
*/
public static String hashpw(String password, String salt) {
@@ -432,12 +413,10 @@ public class BCRYPT implements EncryptionMethod {
/**
* Generate a salt for use with the BCrypt.hashpw() method
- *
- * @param log_rounds
- * the log2 of the number of rounds of hashing to apply - the
- * work factor therefore increases as 2**log_rounds.
- * @param random
- * an instance of SecureRandom to use
+ *
+ * @param log_rounds the log2 of the number of rounds of hashing to apply - the
+ * work factor therefore increases as 2**log_rounds.
+ * @param random an instance of SecureRandom to use
* @return an encoded salt value
*/
public static String gensalt(int log_rounds, SecureRandom random) {
@@ -457,10 +436,9 @@ public class BCRYPT implements EncryptionMethod {
/**
* Generate a salt for use with the BCrypt.hashpw() method
- *
- * @param log_rounds
- * the log2 of the number of rounds of hashing to apply - the
- * work factor therefore increases as 2**log_rounds.
+ *
+ * @param log_rounds the log2 of the number of rounds of hashing to apply - the
+ * work factor therefore increases as 2**log_rounds.
* @return an encoded salt value
*/
public static String gensalt(int log_rounds) {
@@ -470,7 +448,7 @@ public class BCRYPT implements EncryptionMethod {
/**
* Generate a salt for use with the BCrypt.hashpw() method, selecting a
* reasonable default for the number of hashing rounds to apply
- *
+ *
* @return an encoded salt value
*/
public static String gensalt() {
@@ -479,11 +457,9 @@ public class BCRYPT implements EncryptionMethod {
/**
* Check that a plaintext password matches a previously hashed one
- *
- * @param plaintext
- * the plaintext password to verify
- * @param hashed
- * the previously-hashed password
+ *
+ * @param plaintext the plaintext password to verify
+ * @param hashed the previously-hashed password
* @return true if the passwords match, false otherwise
*/
public static boolean checkpw(String plaintext, String hashed) {
@@ -494,12 +470,9 @@ public class BCRYPT implements EncryptionMethod {
* Check that a text password matches a previously hashed one with the
* specified number of rounds using recursion
*
- * @param text
- * plaintext or hashed text
- * @param hashed
- * the previously-hashed password
- * @param rounds
- * number of rounds to hash the password
+ * @param text plaintext or hashed text
+ * @param hashed the previously-hashed password
+ * @param rounds number of rounds to hash the password
* @return
*/
public static boolean checkpw(String text, String hashed, int rounds) {
@@ -528,7 +501,7 @@ public class BCRYPT implements EncryptionMethod {
@Override
public boolean comparePassword(String hash, String password,
- String playerName) throws NoSuchAlgorithmException {
+ String playerName) throws NoSuchAlgorithmException {
return checkpw(password, hash);
}
diff --git a/src/main/java/fr/xephi/authme/security/crypts/CryptPBKDF2.java b/src/main/java/fr/xephi/authme/security/crypts/CryptPBKDF2.java
index e6fb9bc5..2914e47c 100644
--- a/src/main/java/fr/xephi/authme/security/crypts/CryptPBKDF2.java
+++ b/src/main/java/fr/xephi/authme/security/crypts/CryptPBKDF2.java
@@ -28,4 +28,4 @@ public class CryptPBKDF2 implements EncryptionMethod {
return engine.verifyKey(password);
}
-}
+}
\ No newline at end of file
diff --git a/src/main/java/fr/xephi/authme/security/crypts/CryptPBKDF2Django.java b/src/main/java/fr/xephi/authme/security/crypts/CryptPBKDF2Django.java
new file mode 100644
index 00000000..c1e119a3
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/security/crypts/CryptPBKDF2Django.java
@@ -0,0 +1,32 @@
+package fr.xephi.authme.security.crypts;
+
+import fr.xephi.authme.security.pbkdf2.PBKDF2Engine;
+import fr.xephi.authme.security.pbkdf2.PBKDF2Parameters;
+
+import javax.xml.bind.DatatypeConverter;
+import java.security.NoSuchAlgorithmException;
+
+public class CryptPBKDF2Django implements EncryptionMethod {
+
+ @Override
+ public String getHash(String password, String salt, String name)
+ throws NoSuchAlgorithmException {
+ String result = "pbkdf2_sha256$15000$" + salt + "$";
+ PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", salt.getBytes(), 15000);
+ PBKDF2Engine engine = new PBKDF2Engine(params);
+
+ return result + String.valueOf(DatatypeConverter.printBase64Binary(engine.deriveKey(password, 32)));
+ }
+
+ @Override
+ public boolean comparePassword(String hash, String password,
+ String playerName) throws NoSuchAlgorithmException {
+ String[] line = hash.split("\\$");
+ String salt = line[2];
+ byte[] derivedKey = DatatypeConverter.parseBase64Binary(line[3]);
+ PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", salt.getBytes(), 15000, derivedKey);
+ PBKDF2Engine engine = new PBKDF2Engine(params);
+ return engine.verifyKey(password);
+ }
+
+}
diff --git a/src/main/java/fr/xephi/authme/security/crypts/PHPBB.java b/src/main/java/fr/xephi/authme/security/crypts/PHPBB.java
index fc2f1896..cc5d4dc3 100644
--- a/src/main/java/fr/xephi/authme/security/crypts/PHPBB.java
+++ b/src/main/java/fr/xephi/authme/security/crypts/PHPBB.java
@@ -10,29 +10,24 @@ import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
- *
* @author stefano
*/
public class PHPBB implements EncryptionMethod {
- private static final int PHP_VERSION = 4;
private String itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public String phpbb_hash(String password, String salt) {
String random_state = salt;
- String random = "";
+ StringBuilder random = new StringBuilder();
int count = 6;
- if (random.length() < count) {
- random = "";
- for (int i = 0; i < count; i += 16) {
- random_state = md5(salt + random_state);
- random += pack(md5(random_state));
- }
- random = random.substring(0, count);
+ for (int i = 0; i < count; i += 16) {
+ random_state = md5(salt + random_state);
+ random.append(pack(md5(random_state)));
}
- String hash = _hash_crypt_private(password, _hash_gensalt_private(random, itoa64));
- if (hash.length() == 34)
+ String hash = _hash_crypt_private(password, _hash_gensalt_private(random.substring(0, count), itoa64));
+ if (hash.length() == 34) {
return hash;
+ }
return md5(password);
}
@@ -40,14 +35,13 @@ public class PHPBB implements EncryptionMethod {
return _hash_gensalt_private(input, itoa64, 6);
}
- @SuppressWarnings("unused")
private String _hash_gensalt_private(String input, String itoa64,
- int iteration_count_log2) {
+ int iteration_count_log2) {
if (iteration_count_log2 < 4 || iteration_count_log2 > 31) {
iteration_count_log2 = 8;
}
String output = "$H$";
- output += itoa64.charAt(Math.min(iteration_count_log2 + ((PHP_VERSION >= 5) ? 5 : 3), 30));
+ output += itoa64.charAt(Math.min(iteration_count_log2 + 3, 30)); // PHP_VERSION >= 5 ? 5 : 3
output += _hash_encode64(input, 6);
return output;
}
@@ -56,24 +50,24 @@ public class PHPBB implements EncryptionMethod {
* Encode hash
*/
private String _hash_encode64(String input, int count) {
- String output = "";
+ StringBuilder output = new StringBuilder();
int i = 0;
do {
int value = input.charAt(i++);
- output += itoa64.charAt(value & 0x3f);
+ output.append(itoa64.charAt(value & 0x3f));
if (i < count)
value |= input.charAt(i) << 8;
- output += itoa64.charAt((value >> 6) & 0x3f);
+ output.append(itoa64.charAt((value >> 6) & 0x3f));
if (i++ >= count)
break;
if (i < count)
value |= input.charAt(i) << 16;
- output += itoa64.charAt((value >> 12) & 0x3f);
+ output.append(itoa64.charAt((value >> 12) & 0x3f));
if (i++ >= count)
break;
- output += itoa64.charAt((value >> 18) & 0x3f);
+ output.append(itoa64.charAt((value >> 18) & 0x3f));
} while (i < count);
- return output;
+ return output.toString();
}
String _hash_crypt_private(String password, String setting) {
@@ -109,9 +103,7 @@ public class PHPBB implements EncryptionMethod {
MessageDigest md5er = MessageDigest.getInstance("MD5");
byte[] hash = md5er.digest(bytes);
return bytes2hex(hash);
- } catch (GeneralSecurityException e) {
- throw new RuntimeException(e);
- } catch (UnsupportedEncodingException e) {
+ } catch (GeneralSecurityException | UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
@@ -126,9 +118,9 @@ public class PHPBB implements EncryptionMethod {
}
private static String bytes2hex(byte[] bytes) {
- StringBuffer r = new StringBuffer(32);
- for (int i = 0; i < bytes.length; i++) {
- String x = Integer.toHexString(bytes[i] & 0xff);
+ StringBuilder r = new StringBuilder(32);
+ for (byte b : bytes) {
+ String x = Integer.toHexString(b & 0xff);
if (x.length() < 2)
r.append("0");
r.append(x);
@@ -137,7 +129,7 @@ public class PHPBB implements EncryptionMethod {
}
static String pack(String hex) {
- StringBuffer buf = new StringBuffer();
+ StringBuilder buf = new StringBuilder();
for (int i = 0; i < hex.length(); i += 2) {
char c1 = hex.charAt(i);
char c2 = hex.charAt(i + 1);
@@ -155,7 +147,7 @@ public class PHPBB implements EncryptionMethod {
@Override
public boolean comparePassword(String hash, String password,
- String playerName) throws NoSuchAlgorithmException {
+ String playerName) throws NoSuchAlgorithmException {
return phpbb_check_hash(password, hash);
}
}
diff --git a/src/main/java/fr/xephi/authme/security/crypts/WORDPRESS.java b/src/main/java/fr/xephi/authme/security/crypts/WORDPRESS.java
index 59871d7d..c0ba2ffe 100644
--- a/src/main/java/fr/xephi/authme/security/crypts/WORDPRESS.java
+++ b/src/main/java/fr/xephi/authme/security/crypts/WORDPRESS.java
@@ -8,13 +8,12 @@ import java.util.Arrays;
public class WORDPRESS implements EncryptionMethod {
- private static String itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
- private int iterationCountLog2 = 8;
+ private static final String itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private SecureRandom randomGen = new SecureRandom();
private String encode64(byte[] src, int count) {
int i, value;
- String output = "";
+ StringBuilder output = new StringBuilder();
i = 0;
if (src.length < count) {
@@ -26,24 +25,24 @@ public class WORDPRESS implements EncryptionMethod {
do {
value = src[i] + (src[i] < 0 ? 256 : 0);
++i;
- output += itoa64.charAt(value & 63);
+ output.append(itoa64.charAt(value & 63));
if (i < count) {
value |= (src[i] + (src[i] < 0 ? 256 : 0)) << 8;
}
- output += itoa64.charAt((value >> 6) & 63);
+ output.append(itoa64.charAt((value >> 6) & 63));
if (i++ >= count) {
break;
}
if (i < count) {
value |= (src[i] + (src[i] < 0 ? 256 : 0)) << 16;
}
- output += itoa64.charAt((value >> 12) & 63);
+ output.append(itoa64.charAt((value >> 12) & 63));
if (i++ >= count) {
break;
}
- output += itoa64.charAt((value >> 18) & 63);
+ output.append(itoa64.charAt((value >> 18) & 63));
} while (i < count);
- return output;
+ return output.toString();
}
private String crypt(String password, String setting) {
@@ -86,7 +85,8 @@ public class WORDPRESS implements EncryptionMethod {
private String gensaltPrivate(byte[] input) {
String output = "$P$";
- output += itoa64.charAt(Math.min(this.iterationCountLog2 + 5, 30));
+ int iterationCountLog2 = 8;
+ output += itoa64.charAt(Math.min(iterationCountLog2 + 5, 30));
output += encode64(input, 6);
return output;
}
diff --git a/src/main/java/fr/xephi/authme/settings/CustomConfiguration.java b/src/main/java/fr/xephi/authme/settings/CustomConfiguration.java
index 7d02487f..d9db941e 100644
--- a/src/main/java/fr/xephi/authme/settings/CustomConfiguration.java
+++ b/src/main/java/fr/xephi/authme/settings/CustomConfiguration.java
@@ -1,21 +1,16 @@
package fr.xephi.authme.settings;
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStreamWriter;
-import java.io.Writer;
-import java.nio.charset.StandardCharsets;
-
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.ConsoleLogger;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
-import fr.xephi.authme.ConsoleLogger;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.StandardCopyOption;
public class CustomConfiguration extends YamlConfiguration {
@@ -23,7 +18,6 @@ public class CustomConfiguration extends YamlConfiguration {
public CustomConfiguration(File file) {
this.configFile = file;
-
load();
}
@@ -43,7 +37,7 @@ public class CustomConfiguration extends YamlConfiguration {
public boolean reLoad() {
boolean out = true;
if (!configFile.exists()) {
- out = loadRessource(configFile);
+ out = loadResource(configFile);
}
if (out)
load();
@@ -58,28 +52,28 @@ public class CustomConfiguration extends YamlConfiguration {
}
}
- public boolean loadRessource(File file) {
- boolean out = true;
+ public File getConfigFile() {
+ return configFile;
+ }
+
+ public boolean loadResource(File file) {
if (!file.exists()) {
try {
- String charset = System.getProperty("file.encoding");
- String newline = System.getProperty("line.separator");
- InputStream fis = getClass().getResourceAsStream("/" + file.getName());
- BufferedReader reader = new BufferedReader(new InputStreamReader(fis, StandardCharsets.UTF_8));
- String str;
- Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
- while ((str = reader.readLine()) != null) {
- writer.append(str).append(newline);
+ if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
+ return false;
+ }
+ int i = file.getPath().indexOf("AuthMe");
+ if (i > -1) {
+ String path = file.getPath().substring(i + 6).replace('\\', '/');
+ InputStream is = AuthMe.class.getResourceAsStream(path);
+ Files.copy(is, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
+ return true;
}
- writer.flush();
- writer.close();
- reader.close();
- fis.close();
} catch (Exception e) {
+ ConsoleLogger.writeStackTrace(e);
ConsoleLogger.showError("Failed to load config from JAR");
- out = false;
}
}
- return out;
+ return false;
}
}
diff --git a/src/main/java/fr/xephi/authme/settings/Messages.java b/src/main/java/fr/xephi/authme/settings/Messages.java
index 75db7b7c..81c6a038 100644
--- a/src/main/java/fr/xephi/authme/settings/Messages.java
+++ b/src/main/java/fr/xephi/authme/settings/Messages.java
@@ -1,13 +1,8 @@
package fr.xephi.authme.settings;
-import java.io.File;
-import java.io.InputStream;
-
-import org.bukkit.command.CommandSender;
-import org.bukkit.configuration.file.YamlConfiguration;
-
-import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
+import org.bukkit.command.CommandSender;
+import java.io.File;
public class Messages extends CustomConfiguration {
@@ -16,70 +11,18 @@ public class Messages extends CustomConfiguration {
public Messages(File file, String lang) {
super(file);
- loadDefaults(file);
- loadFile();
- saveDefaults(file);
+ load();
singleton = this;
this.lang = lang;
}
- /**
- * Loads a file from the plugin jar and sets as default
- *
- * @param filename
- * The filename to open
- */
- @SuppressWarnings("deprecation")
- public final void loadDefaults(File file) {
- InputStream stream = AuthMe.getInstance().getResource(file.getName());
- if (stream == null)
- return;
-
- setDefaults(YamlConfiguration.loadConfiguration(stream));
- }
-
- /**
- * Saves the configuration to disk
- *
- * @return True if saved successfully
- */
- public final boolean saved(File file) {
- try {
- save(file);
- return true;
- } catch (Exception ex) {
- return false;
- }
- }
-
- /**
- * Saves current configuration (plus defaults) to disk.
- *
- * If defaults and configuration are empty, saves blank file.
- *
- * @return True if saved successfully
- */
- public final boolean saveDefaults(File file) {
- options().copyDefaults(true);
- options().copyHeader(true);
- boolean success = saved(file);
- options().copyDefaults(false);
- options().copyHeader(false);
- return success;
- }
-
- private void loadFile() {
- load();
- save();
- }
-
public void send(CommandSender sender, String msg) {
if (!Settings.messagesLanguage.equalsIgnoreCase(singleton.lang))
singleton.reloadMessages();
String loc = (String) singleton.get(msg);
if (loc == null) {
loc = "Error with Translation files, please contact the admin for verify or update translation";
- ConsoleLogger.showError("Error with the " + msg + " translation, verify in your " + Settings.MESSAGE_FILE + "_" + Settings.messagesLanguage + ".yml !");
+ ConsoleLogger.showError("Error with the " + msg + " translation, verify in your " + getConfigFile() + " !");
}
for (String l : loc.split("&n")) {
sender.sendMessage(l.replace("&", "\u00a7"));
@@ -87,15 +30,12 @@ public class Messages extends CustomConfiguration {
}
public String[] send(String msg) {
- if (!Settings.messagesLanguage.equalsIgnoreCase(singleton.lang))
+ if (!Settings.messagesLanguage.equalsIgnoreCase(singleton.lang)) {
singleton.reloadMessages();
- String s = null;
- try {
- s = (String) singleton.get(msg);
- } catch (Exception e) {
}
+ String s = (String) singleton.get(msg);
if (s == null) {
- ConsoleLogger.showError("Error with the " + msg + " translation, verify in your " + Settings.MESSAGE_FILE + "_" + Settings.messagesLanguage + ".yml !");
+ ConsoleLogger.showError("Error with the " + msg + " translation, verify in your " + getConfigFile() + " !");
String[] loc = new String[1];
loc[0] = "Error with " + msg + " translation; Please contact the admin for verify or update translation files";
return (loc);
@@ -106,7 +46,7 @@ public class Messages extends CustomConfiguration {
for (a = 0; a < i; a++) {
loc[a] = ((String) this.get(msg)).split("&n")[a].replace("&", "\u00a7");
}
- if (loc == null || loc.length == 0) {
+ if (loc.length == 0) {
loc[0] = "Error with " + msg + " translation; Please contact the admin for verify or update translation files";
}
return loc;
@@ -114,13 +54,13 @@ public class Messages extends CustomConfiguration {
public static Messages getInstance() {
if (singleton == null) {
- singleton = new Messages(new File(Settings.MESSAGE_FILE + "_" + Settings.messagesLanguage + ".yml"), Settings.messagesLanguage);
+ singleton = new Messages(Settings.messageFile, Settings.messagesLanguage);
}
return singleton;
}
public void reloadMessages() {
- singleton = new Messages(new File(Settings.MESSAGE_FILE + "_" + Settings.messagesLanguage + ".yml"), Settings.messagesLanguage);
+ singleton = new Messages(Settings.messageFile, Settings.messagesLanguage);
}
}
diff --git a/src/main/java/fr/xephi/authme/settings/Settings.java b/src/main/java/fr/xephi/authme/settings/Settings.java
index 54dcf2c1..f3f437be 100644
--- a/src/main/java/fr/xephi/authme/settings/Settings.java
+++ b/src/main/java/fr/xephi/authme/settings/Settings.java
@@ -1,59 +1,54 @@
package fr.xephi.authme.settings;
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.bukkit.configuration.MemoryConfiguration;
-import org.bukkit.configuration.file.YamlConfiguration;
-
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.datasource.DataSource.DataSourceType;
import fr.xephi.authme.security.HashAlgorithm;
+import org.bukkit.configuration.file.YamlConfiguration;
+
+import java.io.*;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
public final class Settings extends YamlConfiguration {
+ private AuthMe plugin;
+
// This is not an option!
public static Boolean antiBotInAction = false;
- public static String PLUGIN_FOLDER = "." + File.separator + "plugins" + File.separator + "AuthMe";
- public static final String CACHE_FOLDER = Settings.PLUGIN_FOLDER + File.separator + "cache";
- public static final String AUTH_FILE = Settings.PLUGIN_FOLDER + File.separator + "auths.db";
- public static final String MESSAGE_FILE = Settings.PLUGIN_FOLDER + File.separator + "messages";
- public static final String SETTINGS_FILE = Settings.PLUGIN_FOLDER + File.separator + "config.yml";
- public static List allowCommands = null;
- public static List getJoinPermissions = null;
- public static List getUnrestrictedName = null;
- private static List getRestrictedIp;
- public static List getMySQLOtherUsernameColumn = null;
- public static List getForcedWorlds = null;
- public static List countries = null;
- public static List countriesBlacklist = null;
- public static List forceCommands = null;
- public static List forceCommandsAsConsole = null;
- public static List forceRegisterCommands = null;
- public static List forceRegisterCommandsAsConsole = null;
- private AuthMe plugin;
- private final File file;
+ public static final File PLUGIN_FOLDER = AuthMe.getInstance().getDataFolder();
+ public static final File MODULE_FOLDER = new File(PLUGIN_FOLDER, "modules");
+ public static final File CACHE_FOLDER = new File(PLUGIN_FOLDER, "cache");
+ public static final File AUTH_FILE = new File(PLUGIN_FOLDER, "auths.db");
+ public static final File SETTINGS_FILE = new File(PLUGIN_FOLDER, "config.yml");
+ public static final File LOG_FILE = new File(PLUGIN_FOLDER, "authme.log");
+
+ public static File messageFile;
+ public static List allowCommands;
+ public static List