Code Refactor - Whitespace Refactor

This commit is contained in:
Xephi
2014-08-08 23:14:56 +02:00
parent ec7ac60340
commit afc1ea9111
114 changed files with 8277 additions and 7103 deletions
@@ -9,7 +9,6 @@ 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;
@@ -17,24 +16,23 @@ public class CacheDataSource implements DataSource {
private HashMap<String, PlayerAuth> cache = new HashMap<String, PlayerAuth>();
public CacheDataSource(AuthMe plugin, DataSource source) {
this.plugin = plugin;
this.plugin = plugin;
this.source = source;
}
@Override
public synchronized boolean isAuthAvailable(String user) {
if (cache.containsKey(user.toLowerCase())) return true;
return source.isAuthAvailable(user.toLowerCase());
if (cache.containsKey(user.toLowerCase())) return true;
return source.isAuthAvailable(user.toLowerCase());
}
@Override
public synchronized PlayerAuth getAuth(String user) {
if(cache.containsKey(user.toLowerCase())) {
if (cache.containsKey(user.toLowerCase())) {
return cache.get(user.toLowerCase());
} else {
PlayerAuth auth = source.getAuth(user.toLowerCase());
if (auth != null)
cache.put(user.toLowerCase(), auth);
if (auth != null) cache.put(user.toLowerCase(), auth);
return auth;
}
}
@@ -51,8 +49,8 @@ public class CacheDataSource implements DataSource {
@Override
public synchronized boolean updatePassword(PlayerAuth auth) {
if (source.updatePassword(auth)) {
if (cache.containsKey(auth.getNickname().toLowerCase()))
cache.get(auth.getNickname()).setHash(auth.getHash());
if (cache.containsKey(auth.getNickname().toLowerCase())) cache.get(
auth.getNickname()).setHash(auth.getHash());
return true;
}
return false;
@@ -61,10 +59,10 @@ public class CacheDataSource implements DataSource {
@Override
public boolean updateSession(PlayerAuth auth) {
if (source.updateSession(auth)) {
if (cache.containsKey(auth.getNickname().toLowerCase())) {
cache.get(auth.getNickname()).setIp(auth.getIp());
cache.get(auth.getNickname()).setLastLogin(auth.getLastLogin());
}
if (cache.containsKey(auth.getNickname().toLowerCase())) {
cache.get(auth.getNickname()).setIp(auth.getIp());
cache.get(auth.getNickname()).setLastLogin(auth.getLastLogin());
}
return true;
}
return false;
@@ -73,12 +71,12 @@ public class CacheDataSource implements DataSource {
@Override
public boolean updateQuitLoc(PlayerAuth auth) {
if (source.updateQuitLoc(auth)) {
if (cache.containsKey(auth.getNickname().toLowerCase())) {
cache.get(auth.getNickname()).setQuitLocX(auth.getQuitLocX());
cache.get(auth.getNickname()).setQuitLocY(auth.getQuitLocY());
cache.get(auth.getNickname()).setQuitLocZ(auth.getQuitLocZ());
cache.get(auth.getNickname()).setWorld(auth.getWorld());
}
if (cache.containsKey(auth.getNickname().toLowerCase())) {
cache.get(auth.getNickname()).setQuitLocX(auth.getQuitLocX());
cache.get(auth.getNickname()).setQuitLocY(auth.getQuitLocY());
cache.get(auth.getNickname()).setQuitLocZ(auth.getQuitLocZ());
cache.get(auth.getNickname()).setWorld(auth.getWorld());
}
return true;
}
return false;
@@ -94,7 +92,7 @@ public class CacheDataSource implements DataSource {
int cleared = source.purgeDatabase(until);
if (cleared > 0) {
for (PlayerAuth auth : cache.values()) {
if(auth.getLastLogin() < until) {
if (auth.getLastLogin() < until) {
cache.remove(auth.getNickname());
}
}
@@ -107,7 +105,7 @@ public class CacheDataSource implements DataSource {
List<String> cleared = source.autoPurgeDatabase(until);
if (cleared.size() > 0) {
for (PlayerAuth auth : cache.values()) {
if(auth.getLastLogin() < until) {
if (auth.getLastLogin() < until) {
cache.remove(auth.getNickname());
}
}
@@ -131,88 +129,88 @@ public class CacheDataSource implements DataSource {
@Override
public void reload() {
cache.clear();
source.reload();
for (Player player : plugin.getServer().getOnlinePlayers()) {
String user = player.getName().toLowerCase();
if (PlayerCache.getInstance().isAuthenticated(user)) {
try {
cache.clear();
source.reload();
for (Player player : plugin.getServer().getOnlinePlayers()) {
String user = player.getName().toLowerCase();
if (PlayerCache.getInstance().isAuthenticated(user)) {
try {
PlayerAuth auth = source.getAuth(user);
cache.put(user, auth);
} catch (NullPointerException npe) {
}
} catch (NullPointerException npe) {
}
}
}
}
}
}
@Override
public synchronized boolean updateEmail(PlayerAuth auth) {
if(source.updateEmail(auth)) {
if (cache.containsKey(auth.getNickname().toLowerCase()))
cache.get(auth.getNickname()).setEmail(auth.getEmail());
return true;
}
return false;
}
@Override
public synchronized boolean updateEmail(PlayerAuth auth) {
if (source.updateEmail(auth)) {
if (cache.containsKey(auth.getNickname().toLowerCase())) cache.get(
auth.getNickname()).setEmail(auth.getEmail());
return true;
}
return false;
}
@Override
public synchronized boolean updateSalt(PlayerAuth auth) {
if(source.updateSalt(auth)) {
if (cache.containsKey(auth.getNickname().toLowerCase()))
cache.get(auth.getNickname()).setSalt(auth.getSalt());
return true;
}
return false;
}
@Override
public synchronized boolean updateSalt(PlayerAuth auth) {
if (source.updateSalt(auth)) {
if (cache.containsKey(auth.getNickname().toLowerCase())) cache.get(
auth.getNickname()).setSalt(auth.getSalt());
return true;
}
return false;
}
@Override
public synchronized List<String> getAllAuthsByName(PlayerAuth auth) {
return source.getAllAuthsByName(auth);
}
@Override
public synchronized List<String> getAllAuthsByName(PlayerAuth auth) {
return source.getAllAuthsByName(auth);
}
@Override
public synchronized List<String> getAllAuthsByIp(String ip) {
return source.getAllAuthsByIp(ip);
}
@Override
public synchronized List<String> getAllAuthsByIp(String ip) {
return source.getAllAuthsByIp(ip);
}
@Override
public synchronized List<String> getAllAuthsByEmail(String email) {
return source.getAllAuthsByEmail(email);
}
@Override
public synchronized List<String> getAllAuthsByEmail(String email) {
return source.getAllAuthsByEmail(email);
}
@Override
public synchronized void purgeBanned(List<String> banned) {
source.purgeBanned(banned);
for (PlayerAuth auth : cache.values()) {
if (banned.contains(auth.getNickname())) {
cache.remove(auth.getNickname());
}
}
}
@Override
public synchronized void purgeBanned(List<String> banned) {
source.purgeBanned(banned);
for (PlayerAuth auth : cache.values()) {
if (banned.contains(auth.getNickname())) {
cache.remove(auth.getNickname());
}
}
}
@Override
public DataSourceType getType() {
return source.getType();
}
@Override
public DataSourceType getType() {
return source.getType();
}
@Override
public boolean isLogged(String user) {
return source.isLogged(user);
}
@Override
public boolean isLogged(String user) {
return source.isLogged(user);
}
@Override
public void setLogged(String user) {
source.setLogged(user);
}
@Override
public void setLogged(String user) {
source.setLogged(user);
}
@Override
public void setUnlogged(String user) {
source.setUnlogged(user);
}
@Override
public void setUnlogged(String user) {
source.setUnlogged(user);
}
@Override
public void purgeLogged() {
source.purgeLogged();
}
@Override
public void purgeLogged() {
source.purgeLogged();
}
}
@@ -4,7 +4,6 @@ import java.util.List;
import fr.xephi.authme.cache.auth.PlayerAuth;
public interface DataSource {
public enum DataSourceType {
@@ -23,7 +22,7 @@ public interface DataSource {
boolean updatePassword(PlayerAuth auth);
int purgeDatabase(long until);
List<String> autoPurgeDatabase(long until);
boolean removeAuth(String user);
@@ -47,15 +46,15 @@ public interface DataSource {
void reload();
void purgeBanned(List<String> banned);
DataSourceType getType();
boolean isLogged(String user);
void setLogged(String user);
void setUnlogged(String user);
void purgeLogged();
}
@@ -17,36 +17,35 @@ import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.settings.PlayersLogs;
import fr.xephi.authme.settings.Settings;
public class FlatFileThread extends Thread implements DataSource {
/* file layout:
*
* PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:LASTPOSX:LASTPOSY:LASTPOSZ:LASTPOSWORLD:EMAIL
*
/*
* file layout:
*
* PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:LASTPOSX:LASTPOSY:LASTPOSZ:
* LASTPOSWORLD:EMAIL
*
* Old but compatible:
* PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:LASTPOSX:LASTPOSY:LASTPOSZ:LASTPOSWORLD
* PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS
* PLAYERNAME:HASHSUM:IP
* PLAYERNAME:HASHSUM
*
* PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:LASTPOSX:LASTPOSY
* :LASTPOSZ:LASTPOSWORLD PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS
* PLAYERNAME:HASHSUM:IP PLAYERNAME:HASHSUM
*/
private File source;
public void run() {
source = new File(Settings.AUTH_FILE);
try {
source.createNewFile();
} catch (IOException e) {
source.createNewFile();
} catch (IOException e) {
ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) {
ConsoleLogger.showError("Can't use FLAT FILE... SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
}
if (!Settings.isStopEnabled)
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
ConsoleLogger.showError("Can't use FLAT FILE... SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
}
if (!Settings.isStopEnabled) AuthMe.getInstance().getServer()
.getPluginManager().disablePlugin(AuthMe.getInstance());
return;
}
}
}
@Override
@@ -86,7 +85,11 @@ public class FlatFileThread extends Thread implements DataSource {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(source, true));
bw.write(auth.getNickname() + ":" + auth.getHash() + ":" + auth.getIp() + ":" + auth.getLastLogin() + ":" + auth.getQuitLocX() + ":" + auth.getQuitLocY() + ":" + auth.getQuitLocZ() + ":" + auth.getWorld() + ":" + auth.getEmail() + "\n");
bw.write(auth.getNickname() + ":" + auth.getHash() + ":"
+ auth.getIp() + ":" + auth.getLastLogin() + ":"
+ auth.getQuitLocX() + ":" + auth.getQuitLocY() + ":"
+ auth.getQuitLocZ() + ":" + auth.getWorld() + ":"
+ auth.getEmail() + "\n");
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
@@ -114,28 +117,51 @@ public class FlatFileThread extends Thread implements DataSource {
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args[0].equals(auth.getNickname())) {
switch (args.length) {
case 4: {
newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), 0, 0, 0, "world", "your@email.com", API.getPlayerRealName(args[0]));
break;
}
case 7: {
newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), "world", "your@email.com", API.getPlayerRealName(args[0]));
break;
}
case 8: {
newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], "your@email.com", API.getPlayerRealName(args[0]));
break;
}
case 9: {
newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], args[8], API.getPlayerRealName(args[0]));
break;
}
default: {
newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], 0, 0, 0, 0, "world", "your@email.com", API.getPlayerRealName(args[0]));
break;
}
}
switch (args.length) {
case 4: {
newAuth = new PlayerAuth(args[0], auth.getHash(),
args[2], Long.parseLong(args[3]), 0, 0, 0,
"world", "your@email.com",
API.getPlayerRealName(args[0]));
break;
}
case 7: {
newAuth = new PlayerAuth(args[0], auth.getHash(),
args[2], Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), "world",
"your@email.com",
API.getPlayerRealName(args[0]));
break;
}
case 8: {
newAuth = new PlayerAuth(args[0], auth.getHash(),
args[2], Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
"your@email.com",
API.getPlayerRealName(args[0]));
break;
}
case 9: {
newAuth = new PlayerAuth(args[0], auth.getHash(),
args[2], Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
args[8], API.getPlayerRealName(args[0]));
break;
}
default: {
newAuth = new PlayerAuth(args[0], auth.getHash(),
args[2], 0, 0, 0, 0, "world",
"your@email.com",
API.getPlayerRealName(args[0]));
break;
}
}
break;
}
}
@@ -172,26 +198,49 @@ public class FlatFileThread extends Thread implements DataSource {
String[] args = line.split(":");
if (args[0].equals(auth.getNickname())) {
switch (args.length) {
case 4: {
newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), 0, 0, 0, "world", "your@email.com", API.getPlayerRealName(args[0]));
break;
}
case 7: {
newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), "world", "your@email.com", API.getPlayerRealName(args[0]));
break;
}
case 8: {
newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], "your@email.com", API.getPlayerRealName(args[0]));
break;
}
case 9: {
newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], args[8], API.getPlayerRealName(args[0]));
break;
}
default: {
newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), 0, 0, 0, "world", "your@email.com", API.getPlayerRealName(args[0]));
break;
}
case 4: {
newAuth = new PlayerAuth(args[0], args[1],
auth.getIp(), auth.getLastLogin(), 0, 0, 0,
"world", "your@email.com",
API.getPlayerRealName(args[0]));
break;
}
case 7: {
newAuth = new PlayerAuth(args[0], args[1],
auth.getIp(), auth.getLastLogin(),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), "world",
"your@email.com",
API.getPlayerRealName(args[0]));
break;
}
case 8: {
newAuth = new PlayerAuth(args[0], args[1],
auth.getIp(), auth.getLastLogin(),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
"your@email.com",
API.getPlayerRealName(args[0]));
break;
}
case 9: {
newAuth = new PlayerAuth(args[0], args[1],
auth.getIp(), auth.getLastLogin(),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
args[8], API.getPlayerRealName(args[0]));
break;
}
default: {
newAuth = new PlayerAuth(args[0], args[1],
auth.getIp(), auth.getLastLogin(), 0, 0, 0,
"world", "your@email.com",
API.getPlayerRealName(args[0]));
break;
}
}
break;
}
@@ -215,9 +264,9 @@ public class FlatFileThread extends Thread implements DataSource {
return true;
}
@Override
public boolean updateQuitLoc(PlayerAuth auth) {
if (!isAuthAvailable(auth.getNickname())) {
@Override
public boolean updateQuitLoc(PlayerAuth auth) {
if (!isAuthAvailable(auth.getNickname())) {
return false;
}
PlayerAuth newAuth = null;
@@ -228,7 +277,11 @@ public class FlatFileThread extends Thread implements DataSource {
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args[0].equals(auth.getNickname())) {
newAuth = new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ(), auth.getWorld(), auth.getEmail(), API.getPlayerRealName(args[0]));
newAuth = new PlayerAuth(args[0], args[1], args[2],
Long.parseLong(args[3]), auth.getQuitLocX(),
auth.getQuitLocY(), auth.getQuitLocZ(),
auth.getWorld(), auth.getEmail(),
API.getPlayerRealName(args[0]));
break;
}
}
@@ -278,7 +331,7 @@ public class FlatFileThread extends Thread implements DataSource {
} catch (IOException ex) {
}
}
}
}
}
@Override
@@ -428,17 +481,40 @@ public class FlatFileThread extends Thread implements DataSource {
if (args[0].equals(user)) {
switch (args.length) {
case 2:
return new PlayerAuth(args[0], args[1], "198.18.0.1", 0, "your@email.com", API.getPlayerRealName(args[0]));
return new PlayerAuth(args[0], args[1],
"198.18.0.1", 0, "your@email.com",
API.getPlayerRealName(args[0]));
case 3:
return new PlayerAuth(args[0], args[1], args[2], 0, "your@email.com", API.getPlayerRealName(args[0]));
return new PlayerAuth(args[0], args[1], args[2], 0,
"your@email.com",
API.getPlayerRealName(args[0]));
case 4:
return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), "your@email.com", API.getPlayerRealName(args[0]));
return new PlayerAuth(args[0], args[1], args[2],
Long.parseLong(args[3]), "your@email.com",
API.getPlayerRealName(args[0]));
case 7:
return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), "unavailableworld", "your@email.com", API.getPlayerRealName(args[0]));
return new PlayerAuth(args[0], args[1], args[2],
Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]),
"unavailableworld", "your@email.com",
API.getPlayerRealName(args[0]));
case 8:
return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], "your@email.com", API.getPlayerRealName(args[0]));
return new PlayerAuth(args[0], args[1], args[2],
Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
"your@email.com",
API.getPlayerRealName(args[0]));
case 9:
return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], args[8], API.getPlayerRealName(args[0]));
return new PlayerAuth(args[0], args[1], args[2],
Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
args[8], API.getPlayerRealName(args[0]));
}
}
}
@@ -467,49 +543,54 @@ public class FlatFileThread extends Thread implements DataSource {
public void reload() {
}
@Override
public boolean updateEmail(PlayerAuth auth) {
if (!isAuthAvailable(auth.getNickname())) {
return false;
}
PlayerAuth newAuth = null;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(source));
String line = "";
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args[0].equals(auth.getNickname())) {
newAuth = new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], auth.getEmail(), API.getPlayerRealName(args[0]));
break;
}
}
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
}
}
}
removeAuth(auth.getNickname());
saveAuth(newAuth);
return true;
}
@Override
public boolean updateEmail(PlayerAuth auth) {
if (!isAuthAvailable(auth.getNickname())) {
return false;
}
PlayerAuth newAuth = null;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(source));
String line = "";
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args[0].equals(auth.getNickname())) {
newAuth = new PlayerAuth(args[0], args[1], args[2],
Long.parseLong(args[3]),
Double.parseDouble(args[4]),
Double.parseDouble(args[5]),
Double.parseDouble(args[6]), args[7],
auth.getEmail(), API.getPlayerRealName(args[0]));
break;
}
}
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return false;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
}
}
}
removeAuth(auth.getNickname());
saveAuth(newAuth);
return true;
}
@Override
public boolean updateSalt(PlayerAuth auth) {
return false;
}
@Override
public boolean updateSalt(PlayerAuth auth) {
return false;
}
@Override
public List<String> getAllAuthsByName(PlayerAuth auth) {
@Override
public List<String> getAllAuthsByName(PlayerAuth auth) {
BufferedReader br = null;
List<String> countIp = new ArrayList<String>();
try {
@@ -535,11 +616,11 @@ public class FlatFileThread extends Thread implements DataSource {
} catch (IOException ex) {
}
}
}
}
}
}
@Override
public List<String> getAllAuthsByIp(String ip) {
@Override
public List<String> getAllAuthsByIp(String ip) {
BufferedReader br = null;
List<String> countIp = new ArrayList<String>();
try {
@@ -566,10 +647,10 @@ public class FlatFileThread extends Thread implements DataSource {
}
}
}
}
}
@Override
public List<String> getAllAuthsByEmail(String email) {
@Override
public List<String> getAllAuthsByEmail(String email) {
BufferedReader br = null;
List<String> countEmail = new ArrayList<String>();
try {
@@ -596,10 +677,10 @@ public class FlatFileThread extends Thread implements DataSource {
}
}
}
}
}
@Override
public void purgeBanned(List<String> banned) {
@Override
public void purgeBanned(List<String> banned) {
BufferedReader br = null;
BufferedWriter bw = null;
ArrayList<String> lines = new ArrayList<String>();
@@ -609,11 +690,12 @@ public class FlatFileThread extends Thread implements DataSource {
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
try {
if (banned.contains(args[0])) {
lines.add(line);
}
} catch (NullPointerException npe) {}
catch (ArrayIndexOutOfBoundsException aioobe) {}
if (banned.contains(args[0])) {
lines.add(line);
}
} catch (NullPointerException npe) {
} catch (ArrayIndexOutOfBoundsException aioobe) {
}
}
bw = new BufferedWriter(new FileWriter(source));
for (String l : lines) {
@@ -640,30 +722,30 @@ public class FlatFileThread extends Thread implements DataSource {
}
}
return;
}
}
@Override
public DataSourceType getType() {
return DataSourceType.FILE;
}
@Override
public DataSourceType getType() {
return DataSourceType.FILE;
}
@Override
public boolean isLogged(String user) {
return PlayersLogs.getInstance().players.contains(user.toLowerCase());
}
@Override
public boolean isLogged(String user) {
return PlayersLogs.getInstance().players.contains(user.toLowerCase());
}
@Override
public void setLogged(String user) {
PlayersLogs.getInstance().addPlayer(user);
}
@Override
public void setLogged(String user) {
PlayersLogs.getInstance().addPlayer(user);
}
@Override
public void setUnlogged(String user) {
PlayersLogs.getInstance().removePlayer(user);
}
@Override
public void setUnlogged(String user) {
PlayersLogs.getInstance().removePlayer(user);
}
@Override
public void purgeLogged() {
PlayersLogs.getInstance().clear();
}
@Override
public void purgeLogged() {
PlayersLogs.getInstance().clear();
}
}
@@ -1,12 +1,14 @@
// Copyright 2007-2013 Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland
// Copyright 2007-2013 Christian d'Heureuse, Inventec Informatik AG, Zurich,
// Switzerland
// www.source-code.biz, www.inventec.ch/chdh
//
// This module is multi-licensed and may be used under the terms
// of any of the following licenses:
//
// EPL, Eclipse Public License, http://www.eclipse.org/legal
// LGPL, GNU Lesser General Public License, http://www.gnu.org/licenses/lgpl.html
// MPL, Mozilla Public License 1.1, http://www.mozilla.org/MPL
// EPL, Eclipse Public License, http://www.eclipse.org/legal
// LGPL, GNU Lesser General Public License,
// http://www.gnu.org/licenses/lgpl.html
// MPL, Mozilla Public License 1.1, http://www.mozilla.org/MPL
//
// Please contact the author if you need another license.
// This module is provided "as is", without warranties of any kind.
@@ -25,302 +27,406 @@ import javax.sql.ConnectionPoolDataSource;
import javax.sql.PooledConnection;
/**
* A lightweight standalone JDBC connection pool manager.
*
* <p>The public methods of this class are thread-safe.
*
* <p>Home page: <a href="http://www.source-code.biz/miniconnectionpoolmanager">www.source-code.biz/miniconnectionpoolmanager</a><br>
* Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland<br>
* Multi-licensed: EPL / LGPL / MPL.
*/
* A lightweight standalone JDBC connection pool manager.
*
* <p>
* The public methods of this class are thread-safe.
*
* <p>
* Home page: <a
* href="http://www.source-code.biz/miniconnectionpoolmanager">www.
* source-code.biz/miniconnectionpoolmanager</a><br>
* Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland<br>
* Multi-licensed: EPL / LGPL / MPL.
*/
public class MiniConnectionPoolManager {
private ConnectionPoolDataSource dataSource;
private int maxConnections;
private long timeoutMs;
private PrintWriter logWriter;
private Semaphore semaphore;
private PoolConnectionEventListener poolConnectionEventListener;
private ConnectionPoolDataSource dataSource;
private int maxConnections;
private long timeoutMs;
private PrintWriter logWriter;
private Semaphore semaphore;
private PoolConnectionEventListener poolConnectionEventListener;
// The following variables must only be accessed within synchronized blocks.
// @GuardedBy("this") could by used in the future.
private LinkedList<PooledConnection> recycledConnections; // list of inactive PooledConnections
private int activeConnections; // number of active (open) connections of this pool
private boolean isDisposed; // true if this connection pool has been disposed
private boolean doPurgeConnection; // flag to purge the connection currently beeing closed instead of recycling it
private PooledConnection connectionInTransition; // a PooledConnection which is currently within a PooledConnection.getConnection() call, or null
// The following variables must only be accessed within synchronized blocks.
// @GuardedBy("this") could by used in the future.
private LinkedList<PooledConnection> recycledConnections; // list of
// inactive
// PooledConnections
private int activeConnections; // number of active (open) connections of
// this pool
private boolean isDisposed; // true if this connection pool has been
// disposed
private boolean doPurgeConnection; // flag to purge the connection currently
// beeing closed instead of recycling it
private PooledConnection connectionInTransition; // a PooledConnection which
// is currently within a
// PooledConnection.getConnection()
// call, or null
/**
* Thrown in {@link #getConnection()} or {@link #getValidConnection()} when no free connection becomes
* available within <code>timeout</code> seconds.
*/
public static class TimeoutException extends RuntimeException {
private static final long serialVersionUID = 1;
public TimeoutException () {
super("Timeout while waiting for a free database connection."); }
public TimeoutException (String msg) {
super(msg); }}
/**
* Thrown in {@link #getConnection()} or {@link #getValidConnection()} when
* no free connection becomes available within <code>timeout</code> seconds.
*/
public static class TimeoutException extends RuntimeException {
private static final long serialVersionUID = 1;
/**
* Constructs a MiniConnectionPoolManager object with a timeout of 60 seconds.
*
* @param dataSource
* the data source for the connections.
* @param maxConnections
* the maximum number of connections.
*/
public MiniConnectionPoolManager (ConnectionPoolDataSource dataSource, int maxConnections) {
this(dataSource, maxConnections, 60); }
public TimeoutException() {
super("Timeout while waiting for a free database connection.");
}
/**
* Constructs a MiniConnectionPoolManager object.
*
* @param dataSource
* the data source for the connections.
* @param maxConnections
* the maximum number of connections.
* @param timeout
* the maximum time in seconds to wait for a free connection.
*/
public MiniConnectionPoolManager (ConnectionPoolDataSource dataSource, int maxConnections, int timeout) {
this.dataSource = dataSource;
this.maxConnections = maxConnections;
this.timeoutMs = timeout * 1000L;
try {
logWriter = dataSource.getLogWriter(); }
catch (SQLException e) {}
if (maxConnections < 1) {
throw new IllegalArgumentException("Invalid maxConnections value."); }
semaphore = new Semaphore(maxConnections,true);
recycledConnections = new LinkedList<PooledConnection>();
poolConnectionEventListener = new PoolConnectionEventListener(); }
public TimeoutException(String msg) {
super(msg);
}
}
/**
* Closes all unused pooled connections.
*/
public synchronized void dispose() throws SQLException {
if (isDisposed) {
return; }
isDisposed = true;
SQLException e = null;
while (!recycledConnections.isEmpty()) {
PooledConnection pconn = recycledConnections.remove();
try {
pconn.close(); }
catch (SQLException e2) {
if (e == null) {
e = e2; }}}
if (e != null) {
throw e; }}
/**
* Constructs a MiniConnectionPoolManager object with a timeout of 60
* seconds.
*
* @param dataSource
* the data source for the connections.
* @param maxConnections
* the maximum number of connections.
*/
public MiniConnectionPoolManager(ConnectionPoolDataSource dataSource,
int maxConnections) {
this(dataSource, maxConnections, 60);
}
/**
* Retrieves a connection from the connection pool.
*
* <p>If <code>maxConnections</code> connections are already in use, the method
* waits until a connection becomes available or <code>timeout</code> seconds elapsed.
* When the application is finished using the connection, it must close it
* in order to return it to the pool.
*
* @return
* a new <code>Connection</code> object.
* @throws TimeoutException
* when no connection becomes available within <code>timeout</code> seconds.
*/
public Connection getConnection() throws SQLException {
return getConnection2(timeoutMs); }
/**
* Constructs a MiniConnectionPoolManager object.
*
* @param dataSource
* the data source for the connections.
* @param maxConnections
* the maximum number of connections.
* @param timeout
* the maximum time in seconds to wait for a free connection.
*/
public MiniConnectionPoolManager(ConnectionPoolDataSource dataSource,
int maxConnections, int timeout) {
this.dataSource = dataSource;
this.maxConnections = maxConnections;
this.timeoutMs = timeout * 1000L;
try {
logWriter = dataSource.getLogWriter();
} catch (SQLException e) {
}
if (maxConnections < 1) {
throw new IllegalArgumentException("Invalid maxConnections value.");
}
semaphore = new Semaphore(maxConnections, true);
recycledConnections = new LinkedList<PooledConnection>();
poolConnectionEventListener = new PoolConnectionEventListener();
}
private Connection getConnection2 (long timeoutMs) throws SQLException {
// This routine is unsynchronized, because semaphore.tryAcquire() may block.
synchronized (this) {
if (isDisposed) {
throw new IllegalStateException("Connection pool has been disposed."); }}
try {
if (!semaphore.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS)) {
throw new TimeoutException(); }}
catch (InterruptedException e) {
throw new RuntimeException("Interrupted while waiting for a database connection.",e); }
boolean ok = false;
try {
Connection conn = getConnection3();
ok = true;
return conn; }
finally {
if (!ok) {
semaphore.release(); }}}
/**
* Closes all unused pooled connections.
*/
public synchronized void dispose() throws SQLException {
if (isDisposed) {
return;
}
isDisposed = true;
SQLException e = null;
while (!recycledConnections.isEmpty()) {
PooledConnection pconn = recycledConnections.remove();
try {
pconn.close();
} catch (SQLException e2) {
if (e == null) {
e = e2;
}
}
}
if (e != null) {
throw e;
}
}
private synchronized Connection getConnection3() throws SQLException {
if (isDisposed) {
throw new IllegalStateException("Connection pool has been disposed."); }
PooledConnection pconn;
if (!recycledConnections.isEmpty()) {
pconn = recycledConnections.remove(); }
else {
pconn = dataSource.getPooledConnection();
pconn.addConnectionEventListener(poolConnectionEventListener); }
Connection conn;
try {
// The JDBC driver may call ConnectionEventListener.connectionErrorOccurred()
// from within PooledConnection.getConnection(). To detect this within
// disposeConnection(), we temporarily set connectionInTransition.
connectionInTransition = pconn;
activeConnections++;
conn = pconn.getConnection(); }
finally {
connectionInTransition = null; }
assertInnerState();
return conn; }
/**
* Retrieves a connection from the connection pool.
*
* <p>
* If <code>maxConnections</code> connections are already in use, the method
* waits until a connection becomes available or <code>timeout</code>
* seconds elapsed. When the application is finished using the connection,
* it must close it in order to return it to the pool.
*
* @return a new <code>Connection</code> object.
* @throws TimeoutException
* when no connection becomes available within
* <code>timeout</code> seconds.
*/
public Connection getConnection() throws SQLException {
return getConnection2(timeoutMs);
}
/**
* Retrieves a connection from the connection pool and ensures that it is valid
* by calling {@link Connection#isValid(int)}.
*
* <p>If a connection is not valid, the method tries to get another connection
* until one is valid (or a timeout occurs).
*
* <p>Pooled connections may become invalid when e.g. the database server is
* restarted.
*
* <p>This method is slower than {@link #getConnection()} because the JDBC
* driver has to send an extra command to the database server to test the connection.
*
* <p>This method requires Java 1.6 or newer.
*
* @throws TimeoutException
* when no valid connection becomes available within <code>timeout</code> seconds.
*/
public Connection getValidConnection() {
long time = System.currentTimeMillis();
long timeoutTime = time + timeoutMs;
int triesWithoutDelay = getInactiveConnections() + 1;
while (true) {
Connection conn = getValidConnection2(time, timeoutTime);
if (conn != null) {
return conn; }
triesWithoutDelay--;
if (triesWithoutDelay <= 0) {
triesWithoutDelay = 0;
try {
Thread.sleep(250); }
catch (InterruptedException e) {
throw new RuntimeException("Interrupted while waiting for a valid database connection.", e); }}
time = System.currentTimeMillis();
if (time >= timeoutTime) {
throw new TimeoutException("Timeout while waiting for a valid database connection."); }}}
private Connection getConnection2(long timeoutMs) throws SQLException {
// This routine is unsynchronized, because semaphore.tryAcquire() may
// block.
synchronized (this) {
if (isDisposed) {
throw new IllegalStateException(
"Connection pool has been disposed.");
}
}
try {
if (!semaphore.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS)) {
throw new TimeoutException();
}
} catch (InterruptedException e) {
throw new RuntimeException(
"Interrupted while waiting for a database connection.", e);
}
boolean ok = false;
try {
Connection conn = getConnection3();
ok = true;
return conn;
} finally {
if (!ok) {
semaphore.release();
}
}
}
private Connection getValidConnection2 (long time, long timeoutTime) {
long rtime = Math.max(1, timeoutTime - time);
Connection conn;
try {
conn = getConnection2(rtime); }
catch (SQLException e) {
return null; }
rtime = timeoutTime - System.currentTimeMillis();
int rtimeSecs = Math.max(1, (int)((rtime+999)/1000));
try {
if (conn.isValid(rtimeSecs)) {
return conn; }}
catch (SQLException e) {}
// This Exception should never occur. If it nevertheless occurs, it's because of an error in the
// JDBC driver which we ignore and assume that the connection is not valid.
// When isValid() returns false, the JDBC driver should have already called connectionErrorOccurred()
// and the PooledConnection has been removed from the pool, i.e. the PooledConnection will
// not be added to recycledConnections when Connection.close() is called.
// But to be sure that this works even with a faulty JDBC driver, we call purgeConnection().
purgeConnection(conn);
return null; }
private synchronized Connection getConnection3() throws SQLException {
if (isDisposed) {
throw new IllegalStateException(
"Connection pool has been disposed.");
}
PooledConnection pconn;
if (!recycledConnections.isEmpty()) {
pconn = recycledConnections.remove();
} else {
pconn = dataSource.getPooledConnection();
pconn.addConnectionEventListener(poolConnectionEventListener);
}
Connection conn;
try {
// The JDBC driver may call
// ConnectionEventListener.connectionErrorOccurred()
// from within PooledConnection.getConnection(). To detect this
// within
// disposeConnection(), we temporarily set connectionInTransition.
connectionInTransition = pconn;
activeConnections++;
conn = pconn.getConnection();
} finally {
connectionInTransition = null;
}
assertInnerState();
return conn;
}
// Purges the PooledConnection associated with the passed Connection from the connection pool.
private synchronized void purgeConnection (Connection conn) {
try {
doPurgeConnection = true;
// (A potential problem of this program logic is that setting the doPurgeConnection flag
// has an effect only if the JDBC driver calls connectionClosed() synchronously within
// Connection.close().)
conn.close(); }
catch (SQLException e) {}
// ignore exception from close()
finally {
doPurgeConnection = false; }}
/**
* Retrieves a connection from the connection pool and ensures that it is
* valid by calling {@link Connection#isValid(int)}.
*
* <p>
* If a connection is not valid, the method tries to get another connection
* until one is valid (or a timeout occurs).
*
* <p>
* Pooled connections may become invalid when e.g. the database server is
* restarted.
*
* <p>
* This method is slower than {@link #getConnection()} because the JDBC
* driver has to send an extra command to the database server to test the
* connection.
*
* <p>
* This method requires Java 1.6 or newer.
*
* @throws TimeoutException
* when no valid connection becomes available within
* <code>timeout</code> seconds.
*/
public Connection getValidConnection() {
long time = System.currentTimeMillis();
long timeoutTime = time + timeoutMs;
int triesWithoutDelay = getInactiveConnections() + 1;
while (true) {
Connection conn = getValidConnection2(time, timeoutTime);
if (conn != null) {
return conn;
}
triesWithoutDelay--;
if (triesWithoutDelay <= 0) {
triesWithoutDelay = 0;
try {
Thread.sleep(250);
} catch (InterruptedException e) {
throw new RuntimeException(
"Interrupted while waiting for a valid database connection.",
e);
}
}
time = System.currentTimeMillis();
if (time >= timeoutTime) {
throw new TimeoutException(
"Timeout while waiting for a valid database connection.");
}
}
}
private synchronized void recycleConnection (PooledConnection pconn) {
if (isDisposed || doPurgeConnection) {
disposeConnection(pconn);
return; }
if (activeConnections <= 0) {
throw new AssertionError("AuthMeDatabaseError"); }
activeConnections--;
semaphore.release();
recycledConnections.add(pconn);
assertInnerState(); }
private Connection getValidConnection2(long time, long timeoutTime) {
long rtime = Math.max(1, timeoutTime - time);
Connection conn;
try {
conn = getConnection2(rtime);
} catch (SQLException e) {
return null;
}
rtime = timeoutTime - System.currentTimeMillis();
int rtimeSecs = Math.max(1, (int) ((rtime + 999) / 1000));
try {
if (conn.isValid(rtimeSecs)) {
return conn;
}
} catch (SQLException e) {
}
// This Exception should never occur. If it nevertheless occurs, it's
// because of an error in the
// JDBC driver which we ignore and assume that the connection is not
// valid.
// When isValid() returns false, the JDBC driver should have already
// called connectionErrorOccurred()
// and the PooledConnection has been removed from the pool, i.e. the
// PooledConnection will
// not be added to recycledConnections when Connection.close() is
// called.
// But to be sure that this works even with a faulty JDBC driver, we
// call purgeConnection().
purgeConnection(conn);
return null;
}
private synchronized void disposeConnection (PooledConnection pconn) {
pconn.removeConnectionEventListener(poolConnectionEventListener);
if (!recycledConnections.remove(pconn) && pconn != connectionInTransition) {
// If the PooledConnection is not in the recycledConnections list
// and is not currently within a PooledConnection.getConnection() call,
// we assume that the connection was active.
if (activeConnections <= 0) {
throw new AssertionError("AuthMeDatabaseError"); }
activeConnections--;
semaphore.release(); }
closeConnectionAndIgnoreException(pconn);
assertInnerState(); }
// Purges the PooledConnection associated with the passed Connection from
// the connection pool.
private synchronized void purgeConnection(Connection conn) {
try {
doPurgeConnection = true;
// (A potential problem of this program logic is that setting the
// doPurgeConnection flag
// has an effect only if the JDBC driver calls connectionClosed()
// synchronously within
// Connection.close().)
conn.close();
} catch (SQLException e) {
}
// ignore exception from close()
finally {
doPurgeConnection = false;
}
}
private void closeConnectionAndIgnoreException (PooledConnection pconn) {
try {
pconn.close(); }
catch (SQLException e) {
log("Error while closing database connection: "+e.toString()); }}
private synchronized void recycleConnection(PooledConnection pconn) {
if (isDisposed || doPurgeConnection) {
disposeConnection(pconn);
return;
}
if (activeConnections <= 0) {
throw new AssertionError("AuthMeDatabaseError");
}
activeConnections--;
semaphore.release();
recycledConnections.add(pconn);
assertInnerState();
}
private void log (String msg) {
String s = "MiniConnectionPoolManager: "+msg;
try {
if (logWriter == null) {
System.err.println(s); }
else {
logWriter.println(s); }}
catch (Exception e) {}}
private synchronized void disposeConnection(PooledConnection pconn) {
pconn.removeConnectionEventListener(poolConnectionEventListener);
if (!recycledConnections.remove(pconn)
&& pconn != connectionInTransition) {
// If the PooledConnection is not in the recycledConnections list
// and is not currently within a PooledConnection.getConnection()
// call,
// we assume that the connection was active.
if (activeConnections <= 0) {
throw new AssertionError("AuthMeDatabaseError");
}
activeConnections--;
semaphore.release();
}
closeConnectionAndIgnoreException(pconn);
assertInnerState();
}
private synchronized void assertInnerState() {
if (activeConnections < 0) {
throw new AssertionError("AuthMeDatabaseError"); }
if (activeConnections + recycledConnections.size() > maxConnections) {
throw new AssertionError("AuthMeDatabaseError"); }
if (activeConnections + semaphore.availablePermits() > maxConnections) {
throw new AssertionError("AuthMeDatabaseError"); }}
private void closeConnectionAndIgnoreException(PooledConnection pconn) {
try {
pconn.close();
} catch (SQLException e) {
log("Error while closing database connection: " + e.toString());
}
}
private class PoolConnectionEventListener implements ConnectionEventListener {
public void connectionClosed (ConnectionEvent event) {
PooledConnection pconn = (PooledConnection)event.getSource();
recycleConnection(pconn); }
public void connectionErrorOccurred (ConnectionEvent event) {
PooledConnection pconn = (PooledConnection)event.getSource();
disposeConnection(pconn); }}
private void log(String msg) {
String s = "MiniConnectionPoolManager: " + msg;
try {
if (logWriter == null) {
System.err.println(s);
} else {
logWriter.println(s);
}
} catch (Exception e) {
}
}
/**
* Returns the number of active (open) connections of this pool.
*
* <p>This is the number of <code>Connection</code> objects that have been
* issued by {@link #getConnection()}, for which <code>Connection.close()</code>
* has not yet been called.
*
* @return
* the number of active connections.
**/
public synchronized int getActiveConnections() {
return activeConnections; }
private synchronized void assertInnerState() {
if (activeConnections < 0) {
throw new AssertionError("AuthMeDatabaseError");
}
if (activeConnections + recycledConnections.size() > maxConnections) {
throw new AssertionError("AuthMeDatabaseError");
}
if (activeConnections + semaphore.availablePermits() > maxConnections) {
throw new AssertionError("AuthMeDatabaseError");
}
}
/**
* Returns the number of inactive (unused) connections in this pool.
*
* <p>This is the number of internally kept recycled connections,
* for which <code>Connection.close()</code> has been called and which
* have not yet been reused.
*
* @return
* the number of inactive connections.
**/
public synchronized int getInactiveConnections() {
return recycledConnections.size(); }
private class PoolConnectionEventListener implements
ConnectionEventListener {
public void connectionClosed(ConnectionEvent event) {
PooledConnection pconn = (PooledConnection) event.getSource();
recycleConnection(pconn);
}
} // end class MiniConnectionPoolManager
public void connectionErrorOccurred(ConnectionEvent event) {
PooledConnection pconn = (PooledConnection) event.getSource();
disposeConnection(pconn);
}
}
/**
* Returns the number of active (open) connections of this pool.
*
* <p>
* This is the number of <code>Connection</code> objects that have been
* issued by {@link #getConnection()}, for which
* <code>Connection.close()</code> has not yet been called.
*
* @return the number of active connections.
**/
public synchronized int getActiveConnections() {
return activeConnections;
}
/**
* Returns the number of inactive (unused) connections in this pool.
*
* <p>
* This is the number of internally kept recycled connections, for which
* <code>Connection.close()</code> has been called and which have not yet
* been reused.
*
* @return the number of inactive connections.
**/
public synchronized int getInactiveConnections() {
return recycledConnections.size();
}
} // end class MiniConnectionPoolManager
File diff suppressed because it is too large Load Diff
@@ -17,7 +17,6 @@ import fr.xephi.authme.datasource.MiniConnectionPoolManager.TimeoutException;
import fr.xephi.authme.settings.PlayersLogs;
import fr.xephi.authme.settings.Settings;
public class SQLiteThread extends Thread implements DataSource {
private String database;
@@ -53,33 +52,35 @@ public class SQLiteThread extends Thread implements DataSource {
this.columnID = Settings.getMySQLColumnId;
try {
this.connect();
this.setup();
} catch (ClassNotFoundException e) {
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();
ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
}
if (!Settings.isStopEnabled)
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
if (!Settings.isStopEnabled) AuthMe.getInstance().getServer()
.getPluginManager().disablePlugin(AuthMe.getInstance());
return;
} catch (SQLException e) {
} catch (SQLException e) {
ConsoleLogger.showError(e.getMessage());
if (Settings.isStopEnabled) {
ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
ConsoleLogger.showError("Can't use SQLITE... ! SHUTDOWN...");
AuthMe.getInstance().getServer().shutdown();
}
if (!Settings.isStopEnabled)
AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance());
if (!Settings.isStopEnabled) AuthMe.getInstance().getServer()
.getPluginManager().disablePlugin(AuthMe.getInstance());
return;
}
}
}
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");
this.con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/"
+ database + ".db");
}
@@ -89,18 +90,19 @@ public class SQLiteThread extends Thread implements DataSource {
try {
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,"
+ columnLastLogin + " BIGINT,"
+ lastlocX + " DOUBLE NOT NULL DEFAULT '0.0',"
+ lastlocY + " DOUBLE NOT NULL DEFAULT '0.0',"
+ lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0',"
+ lastlocWorld + " VARCHAR(255) DEFAULT 'world',"
+ columnEmail + " VARCHAR(255) DEFAULT 'your@email.com',"
+ "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + "));");
rs = con.getMetaData().getColumns(null, null, tableName, columnPassword);
+ columnID + " INTEGER AUTO_INCREMENT," + columnName
+ " VARCHAR(255) NOT NULL UNIQUE," + columnPassword
+ " VARCHAR(255) NOT NULL," + columnIp
+ " VARCHAR(40) NOT NULL," + columnLastLogin + " BIGINT,"
+ lastlocX + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocY
+ " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocZ
+ " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocWorld
+ " VARCHAR(255) DEFAULT 'world'," + columnEmail
+ " VARCHAR(255) DEFAULT 'your@email.com',"
+ "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID
+ "));");
rs = con.getMetaData().getColumns(null, null, tableName,
columnPassword);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ columnPassword + " VARCHAR(255) NOT NULL;");
@@ -112,7 +114,8 @@ public class SQLiteThread extends Thread implements DataSource {
+ columnIp + " VARCHAR(40) NOT NULL;");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnLastLogin);
rs = con.getMetaData().getColumns(null, null, tableName,
columnLastLogin);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ columnLastLogin + " BIGINT;");
@@ -120,19 +123,28 @@ public class SQLiteThread extends Thread implements DataSource {
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocX);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ lastlocX + " DOUBLE NOT NULL DEFAULT '0.0';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ lastlocY + " DOUBLE NOT NULL DEFAULT '0.0';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0';");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, lastlocWorld);
rs = con.getMetaData().getColumns(null, null, tableName,
lastlocWorld);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT 'world';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ lastlocWorld
+ " VARCHAR(255) NOT NULL DEFAULT 'world';");
}
rs.close();
rs = con.getMetaData().getColumns(null, null, tableName, columnEmail);
rs = con.getMetaData().getColumns(null, null, tableName,
columnEmail);
if (!rs.next()) {
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com';");
st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN "
+ columnEmail
+ " VARCHAR(255) DEFAULT 'your@email.com';");
}
} finally {
close(rs);
@@ -146,7 +158,8 @@ public class SQLiteThread extends Thread implements DataSource {
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnName + "=?");
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE "
+ columnName + "=?");
pst.setString(1, user);
rs = pst.executeQuery();
return rs.next();
@@ -169,15 +182,38 @@ public class SQLiteThread extends Thread implements DataSource {
pst.setString(1, user);
rs = pst.executeQuery();
if (rs.next()) {
if (rs.getString(columnIp).isEmpty() ) {
return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "198.18.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld) , rs.getString(columnEmail), API.getPlayerRealName(rs.getString(columnName)));
if (rs.getString(columnIp).isEmpty()) {
return new PlayerAuth(rs.getString(columnName),
rs.getString(columnPassword), "198.18.0.1",
rs.getLong(columnLastLogin),
rs.getDouble(lastlocX), rs.getDouble(lastlocY),
rs.getDouble(lastlocZ), rs.getString(lastlocWorld),
rs.getString(columnEmail), API.getPlayerRealName(rs
.getString(columnName)));
} else {
if(!columnSalt.isEmpty()){
return 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), API.getPlayerRealName(rs.getString(columnName)));
} else {
return 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), API.getPlayerRealName(rs.getString(columnName)));
}
}
if (!columnSalt.isEmpty()) {
return 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),
API.getPlayerRealName(rs.getString(columnName)));
} else {
return 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),
API.getPlayerRealName(rs.getString(columnName)));
}
}
} else {
return null;
}
@@ -195,14 +231,19 @@ public class SQLiteThread extends Thread implements DataSource {
PreparedStatement pst = null;
try {
if (columnSalt.isEmpty() && auth.getSalt().isEmpty()) {
pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + ") VALUES (?,?,?,?);");
pst = con.prepareStatement("INSERT INTO " + tableName + "("
+ columnName + "," + columnPassword + "," + columnIp
+ "," + columnLastLogin + ") VALUES (?,?,?,?);");
pst.setString(1, auth.getNickname());
pst.setString(2, auth.getHash());
pst.setString(3, auth.getIp());
pst.setLong(4, auth.getLastLogin());
pst.executeUpdate();
} else {
pst = con.prepareStatement("INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + columnSalt + ") VALUES (?,?,?,?,?);");
pst = con.prepareStatement("INSERT INTO " + tableName + "("
+ columnName + "," + columnPassword + "," + columnIp
+ "," + columnLastLogin + "," + columnSalt
+ ") VALUES (?,?,?,?,?);");
pst.setString(1, auth.getNickname());
pst.setString(2, auth.getHash());
pst.setString(3, auth.getIp());
@@ -223,7 +264,8 @@ public class SQLiteThread extends Thread implements DataSource {
public synchronized boolean updatePassword(PlayerAuth auth) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnPassword + "=? WHERE " + columnName + "=?;");
pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ columnPassword + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getHash());
pst.setString(2, auth.getNickname());
pst.executeUpdate();
@@ -240,7 +282,9 @@ public class SQLiteThread extends Thread implements DataSource {
public boolean updateSession(PlayerAuth auth) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnIp + "=?, " + columnLastLogin + "=? WHERE " + columnName + "=?;");
pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ columnIp + "=?, " + columnLastLogin + "=? WHERE "
+ columnName + "=?;");
pst.setString(1, auth.getIp());
pst.setLong(2, auth.getLastLogin());
pst.setString(3, auth.getNickname());
@@ -258,8 +302,9 @@ public class SQLiteThread extends Thread implements DataSource {
public int purgeDatabase(long until) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + "<?;");
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE "
+ columnLastLogin + "<?;");
pst.setLong(1, until);
return pst.executeUpdate();
} catch (SQLException ex) {
@@ -276,18 +321,19 @@ public class SQLiteThread extends Thread implements DataSource {
ResultSet rs = null;
List<String> list = new ArrayList<String>();
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + "<?;");
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE "
+ columnLastLogin + "<?;");
pst.setLong(1, until);
rs = pst.executeQuery();
while (rs.next()) {
list.add(rs.getString(columnName));
list.add(rs.getString(columnName));
}
return list;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>();
} finally {
close(rs);
close(rs);
close(pst);
}
}
@@ -296,7 +342,8 @@ public class SQLiteThread extends Thread implements DataSource {
public synchronized boolean removeAuth(String user) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;");
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE "
+ columnName + "=?;");
pst.setString(1, user);
pst.executeUpdate();
} catch (SQLException ex) {
@@ -312,7 +359,9 @@ public class SQLiteThread extends Thread implements DataSource {
public boolean updateQuitLoc(PlayerAuth auth) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + lastlocX + "=?, "+ lastlocY +"=?, "+ lastlocZ +"=?, " + lastlocWorld + "=? WHERE " + columnName + "=?;");
pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ lastlocX + "=?, " + lastlocY + "=?, " + lastlocZ + "=?, "
+ lastlocWorld + "=? WHERE " + columnName + "=?;");
pst.setDouble(1, auth.getQuitLocX());
pst.setDouble(2, auth.getQuitLocY());
pst.setDouble(3, auth.getQuitLocZ());
@@ -332,30 +381,31 @@ public class SQLiteThread extends Thread implements DataSource {
public int getIps(String ip) {
PreparedStatement pst = null;
ResultSet rs = null;
int countIp=0;
int countIp = 0;
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE "
+ columnIp + "=?;");
pst.setString(1, ip);
rs = pst.executeQuery();
while(rs.next()) {
countIp++;
}
return countIp;
while (rs.next()) {
countIp++;
}
return countIp;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return 0;
} finally {
} finally {
close(rs);
close(pst);
}
}
}
@Override
public boolean updateEmail(PlayerAuth auth) {
@Override
public boolean updateEmail(PlayerAuth auth) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnEmail + "=? WHERE " + columnName + "=?;");
pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ columnEmail + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getEmail());
pst.setString(2, auth.getNickname());
pst.executeUpdate();
@@ -368,14 +418,15 @@ public class SQLiteThread extends Thread implements DataSource {
return true;
}
@Override
public boolean updateSalt(PlayerAuth auth) {
if(columnSalt.isEmpty()) {
return false;
}
@Override
public boolean updateSalt(PlayerAuth auth) {
if (columnSalt.isEmpty()) {
return false;
}
PreparedStatement pst = null;
try {
pst = con.prepareStatement("UPDATE " + tableName + " SET " + columnSalt + "=? WHERE " + columnName + "=?;");
pst = con.prepareStatement("UPDATE " + tableName + " SET "
+ columnSalt + "=? WHERE " + columnName + "=?;");
pst.setString(1, auth.getSalt());
pst.setString(2, auth.getNickname());
pst.executeUpdate();
@@ -421,8 +472,8 @@ public class SQLiteThread extends Thread implements DataSource {
}
}
@Override
public List<String> getAllAuthsByName(PlayerAuth auth) {
@Override
public List<String> getAllAuthsByName(PlayerAuth auth) {
PreparedStatement pst = null;
ResultSet rs = null;
List<String> countIp = new ArrayList<String>();
@@ -431,10 +482,10 @@ public class SQLiteThread extends Thread implements DataSource {
+ columnIp + "=?;");
pst.setString(1, auth.getIp());
rs = pst.executeQuery();
while(rs.next()) {
countIp.add(rs.getString(columnName));
}
return countIp;
while (rs.next()) {
countIp.add(rs.getString(columnName));
}
return countIp;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>();
@@ -442,15 +493,15 @@ public class SQLiteThread extends Thread implements DataSource {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>();
} catch (NullPointerException npe) {
return new ArrayList<String>();
return new ArrayList<String>();
} finally {
close(rs);
close(pst);
}
}
}
}
@Override
public List<String> getAllAuthsByIp(String ip) {
@Override
public List<String> getAllAuthsByIp(String ip) {
PreparedStatement pst = null;
ResultSet rs = null;
List<String> countIp = new ArrayList<String>();
@@ -459,10 +510,10 @@ public class SQLiteThread extends Thread implements DataSource {
+ columnIp + "=?;");
pst.setString(1, ip);
rs = pst.executeQuery();
while(rs.next()) {
countIp.add(rs.getString(columnName));
}
return countIp;
while (rs.next()) {
countIp.add(rs.getString(columnName));
}
return countIp;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>();
@@ -470,15 +521,15 @@ public class SQLiteThread extends Thread implements DataSource {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>();
} catch (NullPointerException npe) {
return new ArrayList<String>();
return new ArrayList<String>();
} finally {
close(rs);
close(pst);
}
}
}
}
@Override
public List<String> getAllAuthsByEmail(String email) {
@Override
public List<String> getAllAuthsByEmail(String email) {
PreparedStatement pst = null;
ResultSet rs = null;
List<String> countEmail = new ArrayList<String>();
@@ -487,10 +538,10 @@ public class SQLiteThread extends Thread implements DataSource {
+ columnEmail + "=?;");
pst.setString(1, email);
rs = pst.executeQuery();
while(rs.next()) {
countEmail.add(rs.getString(columnName));
}
return countEmail;
while (rs.next()) {
countEmail.add(rs.getString(columnName));
}
return countEmail;
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>();
@@ -498,51 +549,52 @@ public class SQLiteThread extends Thread implements DataSource {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<String>();
} catch (NullPointerException npe) {
return new ArrayList<String>();
return new ArrayList<String>();
} finally {
close(rs);
close(pst);
}
}
}
}
@Override
public void purgeBanned(List<String> banned) {
@Override
public void purgeBanned(List<String> banned) {
PreparedStatement pst = null;
try {
for (String name : banned) {
pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;");
pst.setString(1, name);
pst.executeUpdate();
}
for (String name : banned) {
pst = con.prepareStatement("DELETE FROM " + tableName
+ " WHERE " + columnName + "=?;");
pst.setString(1, name);
pst.executeUpdate();
}
} catch (SQLException ex) {
ConsoleLogger.showError(ex.getMessage());
} finally {
close(pst);
}
}
}
@Override
public DataSourceType getType() {
return DataSourceType.SQLITE;
}
@Override
public DataSourceType getType() {
return DataSourceType.SQLITE;
}
@Override
public boolean isLogged(String user) {
return PlayersLogs.getInstance().players.contains(user.toLowerCase());
}
@Override
public boolean isLogged(String user) {
return PlayersLogs.getInstance().players.contains(user.toLowerCase());
}
@Override
public void setLogged(String user) {
PlayersLogs.getInstance().addPlayer(user);
}
@Override
public void setLogged(String user) {
PlayersLogs.getInstance().addPlayer(user);
}
@Override
public void setUnlogged(String user) {
PlayersLogs.getInstance().removePlayer(user);
}
@Override
public void setUnlogged(String user) {
PlayersLogs.getInstance().removePlayer(user);
}
@Override
public void purgeLogged() {
PlayersLogs.getInstance().clear();
}
@Override
public void purgeLogged() {
PlayersLogs.getInstance().clear();
}
}