Merge branch '4.0.0-Connection-Pool-Branch' into 4.0.0-BungeeCord-Support

# Conflicts:
#	Plan/src/main/java/com/djrapitops/plan/Plan.java
#	Plan/src/main/java/com/djrapitops/plan/systems/webapi/bukkit/ConfigureWebAPI.java
This commit is contained in:
Rsl1122 2017-08-24 11:57:03 +03:00
commit b1bee36f2c
45 changed files with 255 additions and 158 deletions

View File

@ -17,7 +17,7 @@
</repository> </repository>
</repositories> </repositories>
<dependencies> <dependencies>
<!-- PaperSpigot 1.12 built with Buildtools for Database classes.--> <!-- PaperSpigot 1.12 built with BuildTools for Database classes.-->
<dependency> <dependency>
<groupId>com.destroystokyo.paper</groupId> <groupId>com.destroystokyo.paper</groupId>
<artifactId>paper</artifactId> <artifactId>paper</artifactId>

View File

@ -119,7 +119,7 @@ public class Log {
* Logs trace of caught Exception to Errors.txt and notifies on console. * Logs trace of caught Exception to Errors.txt and notifies on console.
* *
* @param source Class name the exception was caught in. * @param source Class name the exception was caught in.
* @param e Throwable, eg NullPointerException * @param e {@code Throwable}, eg NullPointerException
*/ */
public static void toLog(String source, Throwable e) { public static void toLog(String source, Throwable e) {
Plan.getInstance().getPluginLogger().toLog(source, e); Plan.getInstance().getPluginLogger().toLog(source, e);
@ -129,7 +129,7 @@ public class Log {
* Logs multiple caught Errors to Errors.txt. * Logs multiple caught Errors to Errors.txt.
* *
* @param source Class name the exception was caught in. * @param source Class name the exception was caught in.
* @param e Collection of Throwables, eg NullPointerException * @param e Collection of {@code Throwable}, eg NullPointerException
*/ */
public static void toLog(String source, Collection<Throwable> e) { public static void toLog(String source, Collection<Throwable> e) {
Plan.getInstance().getPluginLogger().toLog(source, e); Plan.getInstance().getPluginLogger().toLog(source, e);

View File

@ -69,6 +69,8 @@ public class ManageHotswapCommand extends SubCommand {
return true; return true;
} }
assert database != null;
try { try {
database.getVersion(); //Test db connection database.getVersion(); //Test db connection
} catch (Exception e) { } catch (Exception e) {

View File

@ -31,7 +31,7 @@ public class AnalysisCacheHandler {
private AnalysisData cache; private AnalysisData cache;
private boolean analysisEnabled; private boolean analysisEnabled;
private Set<UUID> notifyWhenCached; private final Set<UUID> notifyWhenCached;
/** /**
* Class Constructor. * Class Constructor.

View File

@ -168,6 +168,8 @@ public abstract class Database {
return getName().toLowerCase().replace(" ", ""); return getName().toLowerCase().replace(" ", "");
} }
public abstract boolean isNewDatabase() throws SQLException;
/** /**
* Used to get the database schema version. * Used to get the database schema version.
* *
@ -343,6 +345,7 @@ public abstract class Database {
public UserInfoTable getUserInfoTable() { public UserInfoTable getUserInfoTable() {
return userInfoTable; return userInfoTable;
} }
public BasicDataSource getDataSource() { public BasicDataSource getDataSource() {
return dataSource; return dataSource;
} }

View File

@ -32,7 +32,6 @@ public class MySQLDB extends SQLDB {
String port = config.getString("Database.MySQL.Port"); String port = config.getString("Database.MySQL.Port");
String database = config.getString("Database.MySQL.Database"); String database = config.getString("Database.MySQL.Database");
dataSource.setUrl("jdbc:mysql://" + host + ":" + port + "/" + database + "?rewriteBatchedStatements=true"); dataSource.setUrl("jdbc:mysql://" + host + ":" + port + "/" + database + "?rewriteBatchedStatements=true");
String username = config.getString("Database.MySQL.User"); String username = config.getString("Database.MySQL.User");
@ -40,6 +39,7 @@ public class MySQLDB extends SQLDB {
dataSource.setUsername(username); dataSource.setUsername(username);
dataSource.setPassword(password); dataSource.setPassword(password);
dataSource.setMaxTotal(-1); dataSource.setMaxTotal(-1);
} }

View File

@ -138,15 +138,6 @@ public abstract class SQLDB extends Database {
return true; return true;
} }
private boolean isNewDatabase() {
try {
getVersion();
return false;
} catch (Exception ignored) {
return true;
}
}
/** /**
* @return * @return
*/ */
@ -197,6 +188,11 @@ public abstract class SQLDB extends Database {
return versionTable.getVersion(); return versionTable.getVersion();
} }
@Override
public boolean isNewDatabase() throws SQLException {
return versionTable.isNewDatabase();
}
/** /**
* @param version * @param version
* @throws SQLException * @throws SQLException
@ -233,12 +229,6 @@ public abstract class SQLDB extends Database {
try { try {
Benchmark.start("Remove Account"); Benchmark.start("Remove Account");
Log.debug("Database", "Removing Account: " + uuid); Log.debug("Database", "Removing Account: " + uuid);
try {
setupDatabase();
} catch (Exception e) {
Log.toLog(this.getClass().getName(), e);
return false;
}
for (Table t : getAllTablesInRemoveOrder()) { for (Table t : getAllTablesInRemoveOrder()) {
if (!(t instanceof UserIDTable)) { if (!(t instanceof UserIDTable)) {

View File

@ -8,7 +8,7 @@ package main.java.com.djrapitops.plan.database.sql;
*/ */
public class SqlParser { public class SqlParser {
private StringBuilder s; private final StringBuilder s;
public SqlParser() { public SqlParser() {
s = new StringBuilder(); s = new StringBuilder();

View File

@ -39,7 +39,7 @@ public class ActionsTable extends UserIDTable {
private final String columnActionID = "action_id"; private final String columnActionID = "action_id";
private final String columnAdditionalInfo = "additional_info"; private final String columnAdditionalInfo = "additional_info";
private ServerTable serverTable; private final ServerTable serverTable;
public ActionsTable(SQLDB db, boolean usingMySQL) { public ActionsTable(SQLDB db, boolean usingMySQL) {
super("plan_actions", db, usingMySQL); super("plan_actions", db, usingMySQL);
@ -80,8 +80,9 @@ public class ActionsTable extends UserIDTable {
statement.setLong(4, action.getDate()); statement.setLong(4, action.getDate());
statement.setString(5, action.getAdditionalInfo()); statement.setString(5, action.getAdditionalInfo());
statement.execute(); statement.execute();
commit(statement.getConnection());
} finally { } finally {
endTransaction(statement);
close(statement); close(statement);
} }
} }

View File

@ -25,7 +25,7 @@ public class CommandUseTable extends Table {
private final String columnCommand = "command"; private final String columnCommand = "command";
private final String columnTimesUsed = "times_used"; private final String columnTimesUsed = "times_used";
private final String columnServerID = "server_id"; private final String columnServerID = "server_id";
private ServerTable serverTable; private final ServerTable serverTable;
/** /**
* @param db * @param db
@ -157,8 +157,8 @@ public class CommandUseTable extends Table {
} }
statement.executeBatch(); statement.executeBatch();
commit(statement.getConnection());
} finally { } finally {
endTransaction(statement);
close(statement); close(statement);
} }
} }
@ -187,8 +187,8 @@ public class CommandUseTable extends Table {
} }
statement.executeBatch(); statement.executeBatch();
commit(statement.getConnection());
} finally { } finally {
endTransaction(statement);
close(statement); close(statement);
} }
} }

View File

@ -103,8 +103,9 @@ public class IPsTable extends UserIDTable {
statement.setString(2, ip); statement.setString(2, ip);
statement.setString(3, geolocation); statement.setString(3, geolocation);
statement.execute(); statement.execute();
commit(statement.getConnection());
} finally { } finally {
endTransaction(statement);
close(statement); close(statement);
} }
} }

View File

@ -64,17 +64,14 @@ public class KillsTable extends UserIDTable {
" OR " + columnVictimUserID + " = " + usersTable.statementSelectID); " OR " + columnVictimUserID + " = " + usersTable.statementSelectID);
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
statement.setString(2, uuid.toString()); statement.setString(2, uuid.toString());
statement.execute(); statement.execute();
commit(statement.getConnection());
return true; return true;
} catch (SQLException ex) { } catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex); Log.toLog(this.getClass().getName(), ex);
return false; return false;
} finally { } finally {
try {
endTransaction(statement);
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
}
close(statement); close(statement);
} }
} }
@ -106,9 +103,10 @@ public class KillsTable extends UserIDTable {
statement.setString(5, weapon); statement.setString(5, weapon);
statement.addBatch(); statement.addBatch();
} }
statement.executeBatch(); statement.executeBatch();
commit(statement.getConnection());
} finally { } finally {
endTransaction(statement);
close(statement); close(statement);
} }
} }
@ -128,7 +126,10 @@ public class KillsTable extends UserIDTable {
" JOIN " + usersTable + " on " + usersIDColumn + "=" + columnVictimUserID + " JOIN " + usersTable + " on " + usersIDColumn + "=" + columnVictimUserID +
" WHERE " + columnKillerUserID + "=" + usersTable.statementSelectID); " WHERE " + columnKillerUserID + "=" + usersTable.statementSelectID);
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
set = statement.executeQuery(); set = statement.executeQuery();
commit(statement.getConnection());
while (set.next()) { while (set.next()) {
long sessionID = set.getLong(columnSessionID); long sessionID = set.getLong(columnSessionID);
Session session = sessions.get(sessionID); Session session = sessions.get(sessionID);
@ -142,7 +143,6 @@ public class KillsTable extends UserIDTable {
session.getPlayerKills().add(new PlayerKill(victim, weapon, date)); session.getPlayerKills().add(new PlayerKill(victim, weapon, date));
} }
} finally { } finally {
endTransaction(statement);
close(set, statement); close(set, statement);
} }
} }

View File

@ -20,7 +20,7 @@ public class NicknamesTable extends UserIDTable {
private final String columnNick = "nickname"; private final String columnNick = "nickname";
private final String columnServerID = "server_id"; private final String columnServerID = "server_id";
private ServerTable serverTable; private final ServerTable serverTable;
/** /**
* @param db The database * @param db The database
@ -152,9 +152,10 @@ public class NicknamesTable extends UserIDTable {
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
statement.setString(2, Plan.getServerUUID().toString()); statement.setString(2, Plan.getServerUUID().toString());
statement.setString(3, displayName); statement.setString(3, displayName);
statement.execute(); statement.execute();
commit(statement.getConnection());
} finally { } finally {
endTransaction(statement);
close(statement); close(statement);
} }
} }

View File

@ -47,18 +47,14 @@ public class SecurityTable extends Table {
try { try {
statement = prepareStatement("DELETE FROM " + tableName + " WHERE (" + columnUser + "=?)"); statement = prepareStatement("DELETE FROM " + tableName + " WHERE (" + columnUser + "=?)");
statement.setString(1, user); statement.setString(1, user);
statement.execute(); statement.execute();
commit(statement.getConnection());
return true; return true;
} catch (SQLException ex) { } catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex); Log.toLog(this.getClass().getName(), ex);
return false; return false;
} finally { } finally {
try {
endTransaction(statement);
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
}
close(statement); close(statement);
} }
} }

View File

@ -65,7 +65,6 @@ public class ServerTable extends Table {
} else { } else {
updateServerInfo(info); updateServerInfo(info);
} }
} }
private void updateServerInfo(ServerInfo info) throws SQLException { private void updateServerInfo(ServerInfo info) throws SQLException {
@ -85,8 +84,9 @@ public class ServerTable extends Table {
statement.setBoolean(4, true); statement.setBoolean(4, true);
statement.setInt(5, info.getId()); statement.setInt(5, info.getId());
statement.executeUpdate(); statement.executeUpdate();
commit(statement.getConnection());
} finally { } finally {
endTransaction(statement);
close(statement); close(statement);
} }
} }
@ -116,8 +116,9 @@ public class ServerTable extends Table {
statement.setString(3, webAddress); statement.setString(3, webAddress);
statement.setBoolean(4, true); statement.setBoolean(4, true);
statement.execute(); statement.execute();
commit(statement.getConnection());
} finally { } finally {
endTransaction(statement);
close(statement); close(statement);
} }
} }

View File

@ -74,6 +74,7 @@ public class SessionsTable extends UserIDTable {
if (sessionID == -1) { if (sessionID == -1) {
throw new IllegalStateException("Session was not Saved!"); throw new IllegalStateException("Session was not Saved!");
} }
db.getWorldTimesTable().saveWorldTimes(uuid, sessionID, session.getWorldTimes()); db.getWorldTimesTable().saveWorldTimes(uuid, sessionID, session.getWorldTimes());
db.getKillsTable().savePlayerKills(uuid, sessionID, session.getPlayerKills()); db.getKillsTable().savePlayerKills(uuid, sessionID, session.getPlayerKills());
} }
@ -107,11 +108,11 @@ public class SessionsTable extends UserIDTable {
statement.setLong(3, session.getSessionEnd()); statement.setLong(3, session.getSessionEnd());
statement.setInt(4, session.getDeaths()); statement.setInt(4, session.getDeaths());
statement.setInt(5, session.getMobKills()); statement.setInt(5, session.getMobKills());
statement.setString(6, Plan.getServerUUID().toString()); statement.setString(6, Plan.getServerUUID().toString());
statement.execute(); statement.execute();
commit(statement.getConnection());
} finally { } finally {
endTransaction(statement);
close(statement); close(statement);
} }
} }

View File

@ -117,7 +117,9 @@ public class TPSTable extends Table {
statement.setLong(6, tps.getUsedMemory()); statement.setLong(6, tps.getUsedMemory());
statement.setDouble(7, tps.getEntityCount()); statement.setDouble(7, tps.getEntityCount());
statement.setDouble(8, tps.getChunksLoaded()); statement.setDouble(8, tps.getChunksLoaded());
statement.execute(); statement.execute();
commit(statement.getConnection());
} finally { } finally {
close(statement); close(statement);
} }
@ -133,9 +135,10 @@ public class TPSTable extends Table {
// More than 2 Months ago. // More than 2 Months ago.
long fiveWeeks = TimeAmount.MONTH.ms() * 2L; long fiveWeeks = TimeAmount.MONTH.ms() * 2L;
statement.setLong(1, MiscUtils.getTime() - fiveWeeks); statement.setLong(1, MiscUtils.getTime() - fiveWeeks);
statement.execute(); statement.execute();
commit(statement.getConnection());
} finally { } finally {
endTransaction(statement);
close(statement); close(statement);
} }
} }

View File

@ -115,7 +115,6 @@ public abstract class Table {
* @throws SQLException * @throws SQLException
*/ */
protected PreparedStatement prepareStatement(String sql) throws SQLException { protected PreparedStatement prepareStatement(String sql) throws SQLException {
System.out.println(sql);
return getConnection().prepareStatement(sql); return getConnection().prepareStatement(sql);
} }
@ -203,4 +202,4 @@ public abstract class Table {
endTransaction(statement.getConnection()); endTransaction(statement.getConnection());
} }
} }

View File

@ -29,17 +29,14 @@ public abstract class UserIDTable extends Table {
statement = prepareStatement("DELETE FROM " + tableName + statement = prepareStatement("DELETE FROM " + tableName +
" WHERE (" + columnUserID + "=" + usersTable.statementSelectID + ")"); " WHERE (" + columnUserID + "=" + usersTable.statementSelectID + ")");
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
statement.execute(); statement.execute();
commit(statement.getConnection());
return true; return true;
} catch (SQLException ex) { } catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex); Log.toLog(this.getClass().getName(), ex);
return false; return false;
} finally { } finally {
try {
endTransaction(statement);
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
}
close(statement); close(statement);
} }
} }

View File

@ -70,7 +70,9 @@ public class UserInfoTable extends UserIDTable {
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
statement.setLong(2, registered); statement.setLong(2, registered);
statement.setString(3, Plan.getServerUUID().toString()); statement.setString(3, Plan.getServerUUID().toString());
statement.execute(); statement.execute();
commit(statement.getConnection());
} finally { } finally {
close(statement); close(statement);
} }
@ -87,6 +89,7 @@ public class UserInfoTable extends UserIDTable {
set = statement.executeQuery(); set = statement.executeQuery();
return set.next(); return set.next();
} finally { } finally {
endTransaction(statement);
close(set, statement); close(set, statement);
} }
} }
@ -100,7 +103,9 @@ public class UserInfoTable extends UserIDTable {
statement.setBoolean(1, opped); statement.setBoolean(1, opped);
statement.setBoolean(2, banned); statement.setBoolean(2, banned);
statement.setString(3, uuid.toString()); statement.setString(3, uuid.toString());
statement.execute(); statement.execute();
commit(statement.getConnection());
} finally { } finally {
close(statement); close(statement);
} }
@ -138,6 +143,7 @@ public class UserInfoTable extends UserIDTable {
} }
return null; return null;
} finally { } finally {
endTransaction(statement);
close(set, statement); close(set, statement);
} }
} }

View File

@ -1,7 +1,6 @@
package main.java.com.djrapitops.plan.database.tables; package main.java.com.djrapitops.plan.database.tables;
import com.djrapitops.plugin.utilities.Verify; import com.djrapitops.plugin.utilities.Verify;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.database.databases.SQLDB; import main.java.com.djrapitops.plan.database.databases.SQLDB;
import main.java.com.djrapitops.plan.database.sql.*; import main.java.com.djrapitops.plan.database.sql.*;
@ -79,16 +78,13 @@ public class UsersTable extends UserIDTable {
try { try {
statement = prepareStatement("DELETE FROM " + tableName + " WHERE (" + columnUUID + "=?)"); statement = prepareStatement("DELETE FROM " + tableName + " WHERE (" + columnUUID + "=?)");
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
statement.execute(); statement.execute();
commit(statement.getConnection());
return true; return true;
} catch (SQLException ex) { } catch (SQLException ex) {
return false; return false;
} finally { } finally {
try {
endTransaction(statement);
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
}
close(statement); close(statement);
} }
} }
@ -167,9 +163,10 @@ public class UsersTable extends UserIDTable {
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
statement.setLong(2, registered); statement.setLong(2, registered);
statement.setString(3, name); statement.setString(3, name);
statement.execute(); statement.execute();
commit(statement.getConnection());
} finally { } finally {
endTransaction(statement);
close(statement); close(statement);
} }
} }
@ -198,9 +195,10 @@ public class UsersTable extends UserIDTable {
.toString()); .toString());
statement.setString(1, name); statement.setString(1, name);
statement.setString(2, uuid.toString()); statement.setString(2, uuid.toString());
statement.execute(); statement.execute();
commit(statement.getConnection());
} finally { } finally {
endTransaction(statement);
close(statement); close(statement);
} }
} }
@ -231,9 +229,10 @@ public class UsersTable extends UserIDTable {
+ columnTimesKicked + "=" + columnTimesKicked + "+ 1" + + columnTimesKicked + "=" + columnTimesKicked + "+ 1" +
" WHERE " + columnUUID + "=?"); " WHERE " + columnUUID + "=?");
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
statement.execute(); statement.execute();
commit(statement.getConnection());
} finally { } finally {
endTransaction(statement);
close(statement); close(statement);
} }
} }
@ -252,6 +251,7 @@ public class UsersTable extends UserIDTable {
} }
return null; return null;
} finally { } finally {
endTransaction(statement);
close(set, statement); close(set, statement);
} }
} }

View File

@ -1,6 +1,5 @@
package main.java.com.djrapitops.plan.database.tables; package main.java.com.djrapitops.plan.database.tables;
import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.database.databases.SQLDB; import main.java.com.djrapitops.plan.database.databases.SQLDB;
import main.java.com.djrapitops.plan.database.sql.Sql; import main.java.com.djrapitops.plan.database.sql.Sql;
import main.java.com.djrapitops.plan.database.sql.TableSqlParser; import main.java.com.djrapitops.plan.database.sql.TableSqlParser;
@ -33,6 +32,27 @@ public class VersionTable extends Table {
); );
} }
public boolean isNewDatabase() throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {
if (usingMySQL) {
statement = prepareStatement("SHOW TABLES LIKE ?");
} else {
statement = prepareStatement("SELECT tbl_name FROM sqlite_master WHERE tbl_name=?");
}
statement.setString(1, tableName);
set = statement.executeQuery();
return set.next();
} finally {
endTransaction(statement);
close(set, statement);
}
}
/** /**
* @return @throws SQLException * @return @throws SQLException
*/ */
@ -47,12 +67,15 @@ public class VersionTable extends Table {
if (set.next()) { if (set.next()) {
version = set.getInt("version"); version = set.getInt("version");
} }
Log.debug("Database", "DB Schema version: " + version);
return version; return version;
} catch (Exception exc) {
exc.printStackTrace();
} finally { } finally {
endTransaction(statement); endTransaction(statement);
close(set, statement); close(set, statement);
} }
return 1;
} }
/** /**
@ -64,6 +87,7 @@ public class VersionTable extends Table {
PreparedStatement statement = null; PreparedStatement statement = null;
try { try {
statement = prepareStatement("INSERT INTO " + tableName + " (version) VALUES (" + version + ")"); statement = prepareStatement("INSERT INTO " + tableName + " (version) VALUES (" + version + ")");
statement.executeUpdate(); statement.executeUpdate();
commit(statement.getConnection()); commit(statement.getConnection());
} finally { } finally {

View File

@ -101,8 +101,8 @@ public class WorldTable extends Table {
} }
statement.executeBatch(); statement.executeBatch();
commit(statement.getConnection());
} finally { } finally {
endTransaction(statement);
close(statement); close(statement);
} }
} }

View File

@ -98,8 +98,8 @@ public class WorldTimesTable extends UserIDTable {
} }
statement.executeBatch(); statement.executeBatch();
commit(statement.getConnection());
} finally { } finally {
endTransaction(statement);
close(statement); close(statement);
} }
} }

View File

@ -27,10 +27,10 @@ import java.util.UUID;
*/ */
public class ServerInfoManager { public class ServerInfoManager {
private Plan plugin; private final Plan plugin;
private ServerInfo serverInfo; private ServerInfo serverInfo;
private ServerInfoFile serverInfoFile; private ServerInfoFile serverInfoFile;
private ServerTable serverTable; private final ServerTable serverTable;
public ServerInfoManager(Plan plugin) { public ServerInfoManager(Plan plugin) {
this.plugin = plugin; this.plugin = plugin;
@ -60,7 +60,7 @@ public class ServerInfoManager {
} }
} }
private void updateDbInfo(UUID serverUUID) throws SQLException { private void updateDbInfo(UUID serverUUID) throws SQLException, IOException {
Optional<Integer> serverID = serverTable.getServerID(serverUUID); Optional<Integer> serverID = serverTable.getServerID(serverUUID);
if (!serverID.isPresent()) { if (!serverID.isPresent()) {
registerServer(serverUUID); registerServer(serverUUID);
@ -76,21 +76,24 @@ public class ServerInfoManager {
serverTable.saveCurrentServerInfo(serverInfo); serverTable.saveCurrentServerInfo(serverInfo);
} }
private void registerServer() throws SQLException { private void registerServer() throws SQLException, IOException {
registerServer(generateNewUUID(plugin.getServer())); registerServer(generateNewUUID(plugin.getServer()));
} }
private void registerServer(UUID serverUUID) throws SQLException { private void registerServer(UUID serverUUID) throws SQLException, IOException {
String webAddress = plugin.getUiServer().getAccessAddress(); String webAddress = plugin.getUiServer().getAccessAddress();
String name = Settings.SERVER_NAME.toString(); String name = Settings.SERVER_NAME.toString();
serverInfo = new ServerInfo(-1, serverUUID, name, webAddress); serverInfo = new ServerInfo(-1, serverUUID, name, webAddress);
serverTable.saveCurrentServerInfo(serverInfo); serverTable.saveCurrentServerInfo(serverInfo);
Optional<Integer> serverID = serverTable.getServerID(serverUUID); Optional<Integer> serverID = serverTable.getServerID(serverUUID);
if (serverID.isPresent()) { if (!serverID.isPresent()) {
serverInfo.setId(serverID.get());
} else {
throw new IllegalStateException("Failed to Register Server (ID not found)"); throw new IllegalStateException("Failed to Register Server (ID not found)");
} }
int id = serverID.get();
serverInfo.setId(id);
serverInfoFile.saveInfo(serverInfo, new ServerInfo(id, serverUUID, name, webAddress));
} }
private UUID generateNewUUID(Server server) { private UUID generateNewUUID(Server server) {

View File

@ -15,7 +15,7 @@ import org.bukkit.event.player.AsyncPlayerChatEvent;
*/ */
public class PlanChatListener implements Listener { public class PlanChatListener implements Listener {
private Plan plugin; private final Plan plugin;
/** /**
* Class Constructor. * Class Constructor.

View File

@ -10,7 +10,7 @@ package main.java.com.djrapitops.plan.systems.processing;
* @author Rsl1122 * @author Rsl1122
*/ */
public abstract class Processor<T> { public abstract class Processor<T> {
protected T object; protected final T object;
public Processor(T object) { public Processor(T object) {
this.object = object; this.object = object;

View File

@ -19,7 +19,7 @@ public class WebAPIManager {
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
private static Map<String, WebAPI> registry = new HashMap<>(); private static final Map<String, WebAPI> registry = new HashMap<>();
public static void registerNewAPI(String method, WebAPI api) { public static void registerNewAPI(String method, WebAPI api) {
registry.put(method.toLowerCase(), api); registry.put(method.toLowerCase(), api);

View File

@ -47,7 +47,7 @@ public enum Theme {
"fff", "000", "267F00", "e5cc12", "b74343", "1E90FF", "fff", "000", "267F00", "e5cc12", "b74343", "1E90FF",
"e0d264", "7dcc24", "b58310", "ac69ef", "ddd", "565556"); "e0d264", "7dcc24", "b58310", "ac69ef", "ddd", "565556");
private String[] colors; private final String[] colors;
Theme(String... colors) { Theme(String... colors) {
int length = colors.length; int length = colors.length;
@ -63,19 +63,17 @@ public enum Theme {
} }
public String replaceThemeColors(String resourceString) { public String replaceThemeColors(String resourceString) {
Theme def = Theme.DEFAULT;
String replaced = resourceString; String replaced = resourceString;
for (Colors c : Colors.values()) { for (Colors c : Colors.values()) {
replaced = replaced.replace("#" + def.getColor(c.getId()), "#" + this.getColor(c.getId())); replaced = replaced.replace("#" + Theme.DEFAULT.getColor(c.getId()), "#" + this.getColor(c.getId()));
} }
return replaced; return replaced;
} }
public static String replaceColors(String resourceString) { public static String replaceColors(String resourceString) {
Theme def = Theme.DEFAULT;
String replaced = resourceString; String replaced = resourceString;
for (Colors c : Colors.values()) { for (Colors c : Colors.values()) {
replaced = replaced.replace("#" + def.getColor(c.getId()), c.getColor()); replaced = replaced.replace("#" + Theme.DEFAULT.getColor(c.getId()), c.getColor());
} }
return replaced; return replaced;
} }

View File

@ -1,5 +1,7 @@
package main.java.com.djrapitops.plan.utilities.analysis; package main.java.com.djrapitops.plan.utilities.analysis;
import com.google.common.base.Objects;
/** /**
* @author Rsl1122 * @author Rsl1122
* @since 3.5.2 * @since 3.5.2
@ -25,4 +27,18 @@ public class Point {
public String toString() { public String toString() {
return "{x:" + x + " y:" + y + '}'; return "{x:" + x + " y:" + y + '}';
} }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Point point = (Point) o;
return Double.compare(point.x, x) == 0 &&
Double.compare(point.y, y) == 0;
}
@Override
public int hashCode() {
return Objects.hashCode(x, y);
}
} }

View File

@ -30,6 +30,8 @@ public class ReduceGapTriangles {
continue; continue;
} }
assert lastPoint != null;
long date = (long) point.getX(); long date = (long) point.getX();
long lastDate = (long) lastPoint.getX(); long lastDate = (long) lastPoint.getX();
double y = point.getY(); double y = point.getY();

View File

@ -60,7 +60,7 @@ public enum Html {
@Deprecated ERROR_TABLE_2(TABLELINE_2.parse("No data", "No data")), @Deprecated ERROR_TABLE_2(TABLELINE_2.parse("No data", "No data")),
TABLE_END("</tbody></table>"); // KILLDATA_NONE("No Kills"), TABLE_END("</tbody></table>"); // KILLDATA_NONE("No Kills"),
private String html; private final String html;
Html(String html) { Html(String html) {
this.html = html; this.html = html;

View File

@ -1,11 +1,8 @@
package main.java.com.djrapitops.plan.utilities.html.graphs; package main.java.com.djrapitops.plan.utilities.html.graphs;
import main.java.com.djrapitops.plan.data.Session;
import main.java.com.djrapitops.plan.data.TPS; import main.java.com.djrapitops.plan.data.TPS;
import main.java.com.djrapitops.plan.utilities.analysis.Point; import main.java.com.djrapitops.plan.utilities.analysis.Point;
import java.util.Arrays;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -27,12 +24,4 @@ public class PlayerActivityGraphCreator {
.collect(Collectors.toList()); .collect(Collectors.toList());
return SeriesCreator.seriesGraph(points, true); return SeriesCreator.seriesGraph(points, true);
} }
public static String buildSeriesDataStringSessions(Collection<Session> sessions) {
List<Point> points = sessions.stream()
.map(session -> new Point[]{new Point(session.getSessionStart(), 1), new Point(session.getSessionEnd(), 0)})
.flatMap(Arrays::stream)
.collect(Collectors.toList());
return SeriesCreator.seriesGraph(points, true, false);
}
} }

View File

@ -28,8 +28,5 @@ public class SessionTest {
public void setUp() { public void setUp() {
} }
/**
*
*/
// TODO Rewrite // TODO Rewrite
} }

View File

@ -21,7 +21,7 @@ import static junit.framework.TestCase.*;
@PrepareForTest(JavaPlugin.class) @PrepareForTest(JavaPlugin.class)
public class GeolocationCacheTest { public class GeolocationCacheTest {
private Map<String, String> ipsToCountries = new HashMap<>(); private final Map<String, String> ipsToCountries = new HashMap<>();
@Before @Before
public void setUp() { public void setUp() {

View File

@ -35,7 +35,7 @@ public class WorldTimesTest {
public void testWorldChange() { public void testWorldChange() {
long changeTime = time + 1000L; long changeTime = time + 1000L;
test.updateState(worldTwo, gms[0], changeTime); test.updateState(worldTwo, gms[0], changeTime);
assertEquals(1000L, (long) test.getWorldPlaytime(worldOne)); assertEquals(1000L, test.getWorldPlaytime(worldOne));
assertEquals(1000L, test.getGMTimes(worldOne).getTime(gms[0])); assertEquals(1000L, test.getGMTimes(worldOne).getTime(gms[0]));
} }
@ -43,7 +43,7 @@ public class WorldTimesTest {
public void testGMChange() { public void testGMChange() {
long changeTime = time + 1000L; long changeTime = time + 1000L;
test.updateState(worldOne, gms[0], changeTime); test.updateState(worldOne, gms[0], changeTime);
assertEquals(1000L, (long) test.getWorldPlaytime(worldOne)); assertEquals(1000L, test.getWorldPlaytime(worldOne));
assertEquals(1000L, test.getGMTimes(worldOne).getTime(gms[0])); assertEquals(1000L, test.getGMTimes(worldOne).getTime(gms[0]));
} }
@ -52,10 +52,10 @@ public class WorldTimesTest {
long changeTime = time + 1000L; long changeTime = time + 1000L;
long changeTime2 = changeTime + 1000L; long changeTime2 = changeTime + 1000L;
test.updateState(worldTwo, gms[2], changeTime); test.updateState(worldTwo, gms[2], changeTime);
assertEquals(1000L, (long) test.getWorldPlaytime(worldOne)); assertEquals(1000L, test.getWorldPlaytime(worldOne));
assertEquals(1000L, test.getGMTimes(worldOne).getTime(gms[0])); assertEquals(1000L, test.getGMTimes(worldOne).getTime(gms[0]));
test.updateState(worldOne, gms[1], changeTime2); test.updateState(worldOne, gms[1], changeTime2);
assertEquals(1000L, (long) test.getWorldPlaytime(worldOne)); assertEquals(1000L, test.getWorldPlaytime(worldOne));
assertEquals(1000L, test.getGMTimes(worldOne).getTime(gms[0])); assertEquals(1000L, test.getGMTimes(worldOne).getTime(gms[0]));
assertEquals(1000L, test.getGMTimes(worldTwo).getTime(gms[2])); assertEquals(1000L, test.getGMTimes(worldTwo).getTime(gms[2]));
} }

View File

@ -8,6 +8,7 @@ package test.java.main.java.com.djrapitops.plan.database;
import main.java.com.djrapitops.plan.database.Container; import main.java.com.djrapitops.plan.database.Container;
import main.java.com.djrapitops.plan.database.DBUtils; import main.java.com.djrapitops.plan.database.DBUtils;
import org.junit.Test; import org.junit.Test;
import test.java.utils.RandomData;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
@ -61,4 +62,15 @@ public class DBUtilsTest {
assertEquals(946, result.get(2).size()); assertEquals(946, result.get(2).size());
} }
@Test
public void testContainers() {
Object object = new Object();
int id = RandomData.randomInt(1, 100);
Container<Object> container = new Container<>(object, id);
assertEquals(id, container.getId());
assertEquals(object, container.getObject());
}
} }

View File

@ -47,9 +47,9 @@ public class DatabaseTest {
private Database db; private Database db;
private Database backup; private Database backup;
private int rows; private int rows;
private UUID uuid = MockUtils.getPlayerUUID(); private final UUID uuid = MockUtils.getPlayerUUID();
private List<String> worlds = Arrays.asList("TestWorld", "TestWorld2"); private final List<String> worlds = Arrays.asList("TestWorld", "TestWorld2");
private UUID uuid2 = MockUtils.getPlayer2UUID(); private final UUID uuid2 = MockUtils.getPlayer2UUID();
public DatabaseTest() { public DatabaseTest() {
} }
@ -58,18 +58,11 @@ public class DatabaseTest {
public void setUp() throws Exception { public void setUp() throws Exception {
TestInit t = TestInit.init(); TestInit t = TestInit.init();
plan = t.getPlanMock(); plan = t.getPlanMock();
db = new SQLiteDB(plan, "debug" + MiscUtils.getTime()) { db = new SQLiteDB(plan, "debug" + MiscUtils.getTime());
@Override
public void startConnectionPingTask() {
}
};
db.init(); db.init();
db.getServerTable().saveCurrentServerInfo(new ServerInfo(-1, t.getServerUUID(), "ServerName", "")); db.getServerTable().saveCurrentServerInfo(new ServerInfo(-1, TestInit.getServerUUID(), "ServerName", ""));
File f = new File(plan.getDataFolder(), "Errors.txt"); File f = new File(plan.getDataFolder(), "Errors.txt");
rows = FileUtil.lines(f).size(); rows = FileUtil.lines(f).size();
db.init();
} }
@After @After
@ -344,6 +337,7 @@ public class DatabaseTest {
saveTwoWorlds(); saveTwoWorlds();
saveUserOne(); saveUserOne();
saveUserTwo(); saveUserTwo();
Session session = new Session(12345L, "", ""); Session session = new Session(12345L, "", "");
session.endSession(22345L); session.endSession(22345L);
session.setWorldTimes(createWorldTimes()); session.setWorldTimes(createWorldTimes());

View File

@ -0,0 +1,88 @@
/*
* Licence is provided in the jar as license.yml also here:
* https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml
*/
package test.java.main.java.com.djrapitops.plan.ui.graphs;
import main.java.com.djrapitops.plan.data.Session;
import main.java.com.djrapitops.plan.data.TPS;
import main.java.com.djrapitops.plan.ui.html.graphs.*;
import main.java.com.djrapitops.plan.utilities.analysis.Point;
import org.junit.Before;
import org.junit.Test;
import test.java.utils.RandomData;
import java.util.*;
import static junit.framework.TestCase.assertEquals;
/**
* @author Fuzzlemann
*/
public class GraphTest {
private final List<TPS> tpsList = new ArrayList<>();
private final List<Session> sessionList = new ArrayList<>();
private final Map<String, Integer> geoList = new HashMap<>();
private final Map<String, Long> worldTimes = new HashMap<>();
private List<Point> points = new ArrayList<>();
@Before
public void setUp() {
for (int i = 0; i < 10; i++) {
tpsList.add(new TPS(i, i, i, i, i, i, i));
sessionList.add(new Session(i, (long) i, (long) i, i, i));
geoList.put(String.valueOf(i), i);
worldTimes.put(String.valueOf(i), (long) i);
}
points = RandomData.randomPoints();
}
@Test
public void testGraphCreators() {
assertEquals(CPUGraphCreator.buildSeriesDataString(tpsList), "[[0,0.0],[9,9.0]]");
assertEquals(PlayerActivityGraphCreator.buildSeriesDataString(tpsList), "[[0,0.0],[9,9.0]]");
assertEquals(PunchCardGraphCreator.createDataSeries(sessionList), "[{x:3600000, y:3, z:14, marker: { radius:14}},]");
assertEquals(RamGraphCreator.buildSeriesDataString(tpsList), "[[0,0.0],[9,9.0]]");
assertEquals(TPSGraphCreator.buildSeriesDataString(tpsList), "[[0,0.0],[9,9.0]]");
assertEquals(WorldLoadGraphCreator.buildSeriesDataStringChunks(tpsList), "[[0,0.0],[9,9.0]]");
assertEquals(WorldLoadGraphCreator.buildSeriesDataStringEntities(tpsList), "[[0,0.0],[9,9.0]]");
assertEquals(WorldMapCreator.createDataSeries(geoList), "[{'code':'1','value':1},{'code':'2','value':2},{'code':'3','value':3},{'code':'4','value':4},{'code':'5','value':5},{'code':'6','value':6},{'code':'7','value':7},{'code':'8','value':8},{'code':'9','value':9}]");
assertEquals(WorldPieCreator.createSeriesData(worldTimes), "[{name:'0',y:0},{name:'1',y:1, sliced: true, selected: true},{name:'2',y:2},{name:'3',y:3},{name:'4',y:4},{name:'5',y:5},{name:'6',y:6},{name:'7',y:7},{name:'8',y:8},{name:'9',y:9}]");
}
@Test
public void testSeriesCreator() {
String result = SeriesCreator.seriesGraph(points, false, false);
String[] splittedResult = result.split(",");
Map<String, String> expected = new LinkedHashMap<>();
String key = null;
for (String resultString : splittedResult) {
resultString = resultString.replaceAll("[\\[\\]]", "");
if (key == null) {
key = resultString;
} else {
expected.put(key, resultString);
key = null;
}
}
int i2 = 0;
for (Map.Entry<String, String> entry : expected.entrySet()) {
String expectedX = entry.getKey();
String expectedY = entry.getValue();
Point point = points.get(i2);
assertEquals("Given X does not match expected X", expectedX, String.valueOf((long) point.getX()));
assertEquals("Given Y does not match expected Y", expectedY, String.valueOf(point.getY()));
i2++;
}
}
}

View File

@ -20,22 +20,13 @@ import org.powermock.modules.junit4.PowerMockRunner;
@PrepareForTest(JavaPlugin.class) @PrepareForTest(JavaPlugin.class)
public class NewPlayerCreatorTest { public class NewPlayerCreatorTest {
/**
*
*/
public NewPlayerCreatorTest() { public NewPlayerCreatorTest() {
} }
/**
*
*/
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
} }
/**
*
*/
@After @After
public void tearDown() { public void tearDown() {
} }

View File

@ -21,9 +21,9 @@ public class PassEncryptTest {
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
for (int i = 0; i < 20; i++) { for (int i = 0; i < 20; i++) {
String password = RandomData.randomString(RandomData.randomInt(1, 50)); String password = RandomData.randomString(RandomData.randomInt(1, 20));
PASSWORD_MAP.put(password, PassEncryptUtil.createHash(password)); PASSWORD_MAP.put(password, PassEncryptUtil.createHash(password));
}; }
} }
@Test @Test

View File

@ -28,7 +28,7 @@ import static junit.framework.TestCase.assertNotNull;
@PrepareForTest(JavaPlugin.class) @PrepareForTest(JavaPlugin.class)
public class HastebinTest { public class HastebinTest {
private AtomicReference<String> testLink = new AtomicReference<>(null); private final AtomicReference<String> testLink = new AtomicReference<>(null);
@Before @Before
public void checkAvailability() throws Exception { public void checkAvailability() throws Exception {

View File

@ -22,27 +22,31 @@ import java.io.IOException;
public class DBTestSuite { public class DBTestSuite {
@BeforeClass @BeforeClass
public static void setUp() throws IOException { public static void setUp() throws IOException {
clean(true); clean();
} }
@AfterClass @AfterClass
public static void tearDown() throws IOException { public static void tearDown() throws IOException {
clean(false); clean();
} }
private static void clean(boolean dbOnly) throws IOException { private static void clean() {
File testFolder = TestInit.getTestFolder(); File testFolder = TestInit.getTestFolder();
if (!testFolder.exists() || !testFolder.isDirectory()) { if (!testFolder.exists() || !testFolder.isDirectory()) {
return; return;
} }
for (File f : testFolder.listFiles()) { File[] files = testFolder.listFiles();
if (dbOnly && !f.getName().contains(".db")) {
continue;
}
f.delete(); if (files == null) {
return;
}
for (File f : files) {
if (!f.delete()) {
f.deleteOnExit();
}
} }
} }
} }

View File

@ -23,18 +23,12 @@ import static org.powermock.api.mockito.PowerMockito.when;
*/ */
public class MockUtils { public class MockUtils {
/**
* @return
*/
public static World mockWorld() { public static World mockWorld() {
World mockWorld = Mockito.mock(World.class); World mockWorld = Mockito.mock(World.class);
when(mockWorld.toString()).thenReturn("World"); when(mockWorld.toString()).thenReturn("World");
return mockWorld; return mockWorld;
} }
/**
* @return
*/
public static IPlayer mockIPlayer() { public static IPlayer mockIPlayer() {
return Fetch.wrapBukkit(mockPlayer()); return Fetch.wrapBukkit(mockPlayer());
} }
@ -54,16 +48,10 @@ public class MockUtils {
return p; return p;
} }
/**
* @return
*/
public static UUID getPlayerUUID() { public static UUID getPlayerUUID() {
return UUID.fromString("45b0dfdb-f71d-4cf3-8c21-27c9d4c651db"); return UUID.fromString("45b0dfdb-f71d-4cf3-8c21-27c9d4c651db");
} }
/**
* @return
*/
public static IPlayer mockIPlayer2() { public static IPlayer mockIPlayer2() {
return Fetch.wrapBukkit(mockPlayer2()); return Fetch.wrapBukkit(mockPlayer2());
} }
@ -83,9 +71,6 @@ public class MockUtils {
return p; return p;
} }
/**
* @return
*/
public static UUID getPlayer2UUID() { public static UUID getPlayer2UUID() {
return UUID.fromString("ec94a954-1fa1-445b-b09b-9b698519af80"); return UUID.fromString("ec94a954-1fa1-445b-b09b-9b698519af80");
} }
@ -97,9 +82,6 @@ public class MockUtils {
return uuids; return uuids;
} }
/**
* @return
*/
public static IPlayer mockBrokenPlayer() { public static IPlayer mockBrokenPlayer() {
Player p = PowerMockito.mock(Player.class); Player p = PowerMockito.mock(Player.class);
when(p.getGameMode()).thenReturn(GameMode.SURVIVAL); when(p.getGameMode()).thenReturn(GameMode.SURVIVAL);
@ -114,9 +96,6 @@ public class MockUtils {
return Fetch.wrapBukkit(p); return Fetch.wrapBukkit(p);
} }
/**
* @return
*/
public static CommandSender mockConsoleSender() { public static CommandSender mockConsoleSender() {
return PowerMockito.mock(CommandSender.class); return PowerMockito.mock(CommandSender.class);
} }

View File

@ -24,7 +24,6 @@ import org.powermock.api.mockito.PowerMockito;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Logger; import java.util.logging.Logger;