Merge pull request #274 from Fuzzlemann/master

PR for the Connection Pool
This commit is contained in:
Rsl1122 2017-08-24 11:42:33 +03:00 committed by GitHub
commit 5de19263ee
32 changed files with 118 additions and 84 deletions

View File

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

View File

@ -119,7 +119,7 @@ public class Log {
* Logs trace of caught Exception to Errors.txt and notifies on console.
*
* @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) {
Plan.getInstance().getPluginLogger().toLog(source, e);
@ -129,7 +129,7 @@ public class Log {
* Logs multiple caught Errors to Errors.txt.
*
* @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) {
Plan.getInstance().getPluginLogger().toLog(source, e);

View File

@ -151,6 +151,21 @@ public class Plan extends BukkitPlugin<Plan> {
}
Benchmark.stop("Enable", "Init Database");
Benchmark.start("WebServer Initialization");
uiServer = new WebServer(this);
registerWebAPIs(); // TODO Move to WebServer class
uiServer.initServer();
if (!uiServer.isEnabled()) {
Log.error("WebServer was not successfully initialized.");
}
//TODO Re-Enable after DB ServerTable has been initialized properly.
Benchmark.start("ServerInfo Registration");
serverInfoManager = new ServerInfoManager(this);
Benchmark.stop("Enable", "ServerInfo Registration");
Benchmark.start("Init DataCache");
this.dataCache = new DataCache(this);
Benchmark.stop("Enable", "Init DataCache");
@ -174,21 +189,6 @@ public class Plan extends BukkitPlugin<Plan> {
Benchmark.stop("Enable", "Analysis refresh task registration");
Benchmark.start("WebServer Initialization");
uiServer = new WebServer(this);
registerWebAPIs(); // TODO Move to WebServer class
uiServer.initServer();
if (!uiServer.isEnabled()) {
Log.error("WebServer was not successfully initialized.");
}
//TODO Re-Enable after DB ServerTable has been initialized properly.
// Benchmark.start("ServerInfo Registration");
// serverInfoManager = new ServerInfoManager(this);
// Benchmark.stop("Enable", "ServerInfo Registration");
setupFilter(); // TODO Move to RegisterCommand Constructor
// Data view settings // TODO Rewrite. (TextUI removed & webserver might be running on bungee

View File

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

View File

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

View File

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

View File

@ -27,10 +27,10 @@ import java.util.UUID;
*/
public class ServerInfoManager {
private Plan plugin;
private final Plan plugin;
private ServerInfo serverInfo;
private ServerInfoFile serverInfoFile;
private ServerTable serverTable;
private final ServerTable serverTable;
public ServerInfoManager(Plan 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);
if (!serverID.isPresent()) {
registerServer(serverUUID);
@ -76,21 +76,24 @@ public class ServerInfoManager {
serverTable.saveCurrentServerInfo(serverInfo);
}
private void registerServer() throws SQLException {
private void registerServer() throws SQLException, IOException {
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 name = Settings.SERVER_NAME.toString();
serverInfo = new ServerInfo(-1, serverUUID, name, webAddress);
serverTable.saveCurrentServerInfo(serverInfo);
Optional<Integer> serverID = serverTable.getServerID(serverUUID);
if (serverID.isPresent()) {
serverInfo.setId(serverID.get());
} else {
if (!serverID.isPresent()) {
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) {

View File

@ -168,6 +168,8 @@ public abstract class Database {
return getName().toLowerCase().replace(" ", "");
}
public abstract boolean isNewDatabase() throws SQLException;
/**
* Used to get the database schema version.
*

View File

@ -39,6 +39,7 @@ public class MySQLDB extends SQLDB {
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setMaxTotal(-1);
}

View File

@ -138,15 +138,6 @@ public abstract class SQLDB extends Database {
return true;
}
private boolean isNewDatabase() {
try {
getVersion();
return false;
} catch (Exception ignored) {
return true;
}
}
/**
* @return
*/
@ -197,6 +188,11 @@ public abstract class SQLDB extends Database {
return versionTable.getVersion();
}
@Override
public boolean isNewDatabase() throws SQLException {
return versionTable.isNewDatabase();
}
/**
* @param version
* @throws SQLException

View File

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

View File

@ -39,7 +39,7 @@ public class ActionsTable extends UserIDTable {
private final String columnActionID = "action_id";
private final String columnAdditionalInfo = "additional_info";
private ServerTable serverTable;
private final ServerTable serverTable;
public ActionsTable(SQLDB db, boolean usingMySQL) {
super("plan_actions", db, usingMySQL);

View File

@ -25,7 +25,7 @@ public class CommandUseTable extends Table {
private final String columnCommand = "command";
private final String columnTimesUsed = "times_used";
private final String columnServerID = "server_id";
private ServerTable serverTable;
private final ServerTable serverTable;
/**
* @param db

View File

@ -20,7 +20,7 @@ public class NicknamesTable extends UserIDTable {
private final String columnNick = "nickname";
private final String columnServerID = "server_id";
private ServerTable serverTable;
private final ServerTable serverTable;
/**
* @param db The database

View File

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

View File

@ -89,6 +89,7 @@ public class UserInfoTable extends UserIDTable {
set = statement.executeQuery();
return set.next();
} finally {
endTransaction(statement);
close(set, statement);
}
}
@ -142,6 +143,7 @@ public class UserInfoTable extends UserIDTable {
}
return null;
} finally {
endTransaction(statement);
close(set, statement);
}
}

View File

@ -251,6 +251,7 @@ public class UsersTable extends UserIDTable {
}
return null;
} finally {
endTransaction(statement);
close(set, statement);
}
}

View File

@ -1,6 +1,5 @@
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.sql.Sql;
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
*/
@ -47,12 +67,15 @@ public class VersionTable extends Table {
if (set.next()) {
version = set.getInt("version");
}
Log.debug("Database", "DB Schema version: " + version);
return version;
} catch (Exception exc) {
exc.printStackTrace();
} finally {
endTransaction(statement);
close(set, statement);
}
return 1;
}
/**

View File

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

View File

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

View File

@ -47,7 +47,7 @@ public enum Theme {
"fff", "000", "267F00", "e5cc12", "b74343", "1E90FF",
"e0d264", "7dcc24", "b58310", "ac69ef", "ddd", "565556");
private String[] colors;
private final String[] colors;
Theme(String... colors) {
int length = colors.length;
@ -63,19 +63,17 @@ public enum Theme {
}
public String replaceThemeColors(String resourceString) {
Theme def = Theme.DEFAULT;
String replaced = resourceString;
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;
}
public static String replaceColors(String resourceString) {
Theme def = Theme.DEFAULT;
String replaced = resourceString;
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;
}

View File

@ -10,7 +10,6 @@ import main.java.com.djrapitops.plan.ui.webserver.response.Response;
import main.java.com.djrapitops.plan.ui.webserver.response.api.BadRequestResponse;
import main.java.com.djrapitops.plan.ui.webserver.response.api.SuccessResponse;
import main.java.com.djrapitops.plan.utilities.webserver.api.WebAPI;
import org.apache.commons.lang3.text.translate.CharSequenceTranslator;
import org.bukkit.configuration.file.FileConfiguration;
import java.util.Map;

View File

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

View File

@ -19,7 +19,7 @@ public class WebAPIManager {
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) {
registry.put(method.toLowerCase(), api);

View File

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

View File

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

View File

@ -35,7 +35,7 @@ public class WorldTimesTest {
public void testWorldChange() {
long changeTime = time + 1000L;
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]));
}
@ -43,7 +43,7 @@ public class WorldTimesTest {
public void testGMChange() {
long changeTime = time + 1000L;
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]));
}
@ -52,10 +52,10 @@ public class WorldTimesTest {
long changeTime = time + 1000L;
long changeTime2 = changeTime + 1000L;
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]));
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(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.DBUtils;
import org.junit.Test;
import test.java.utils.RandomData;
import java.util.ArrayList;
import java.util.HashMap;
@ -61,4 +62,15 @@ public class DBUtilsTest {
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 backup;
private int rows;
private UUID uuid = MockUtils.getPlayerUUID();
private List<String> worlds = Arrays.asList("TestWorld", "TestWorld2");
private UUID uuid2 = MockUtils.getPlayer2UUID();
private final UUID uuid = MockUtils.getPlayerUUID();
private final List<String> worlds = Arrays.asList("TestWorld", "TestWorld2");
private final UUID uuid2 = MockUtils.getPlayer2UUID();
public DatabaseTest() {
}
@ -63,8 +63,6 @@ public class DatabaseTest {
db.getServerTable().saveCurrentServerInfo(new ServerInfo(-1, TestInit.getServerUUID(), "ServerName", ""));
File f = new File(plan.getDataFolder(), "Errors.txt");
rows = FileUtil.lines(f).size();
db.init();
}
@After
@ -497,13 +495,8 @@ public class DatabaseTest {
assertTrue(usersTable.isRegistered(uuid));
System.out.println("0 " + uuid);
System.out.println("1 " + db.getUsersTable().getSavedUUIDs());
db.removeAccount(uuid);
System.out.println("2 " + db.getUsersTable().getSavedUUIDs());
assertFalse(usersTable.isRegistered(uuid));
assertFalse(userInfoTable.isRegistered(uuid));
assertTrue(nicknamesTable.getNicknames(uuid).isEmpty());

View File

@ -21,10 +21,10 @@ import static junit.framework.TestCase.assertEquals;
*/
public class GraphTest {
private List<TPS> tpsList = new ArrayList<>();
private List<Session> sessionList = new ArrayList<>();
private Map<String, Integer> geoList = new HashMap<>();
private Map<String, Long> worldTimes = new HashMap<>();
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<>();

View File

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

View File

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