This commit is contained in:
Fuzzlemann 2017-08-08 18:26:45 +02:00
parent e306bc1021
commit cd38d0f36e
13 changed files with 98 additions and 25 deletions

View File

@ -43,9 +43,7 @@ public enum Permissions {
} }
/** /**
* Returns the permission node in plugin.yml. * Same as {@link #getPermission()}.
* <p>
* Same as getPermission.
* *
* @return permission node eg. plan.inspect * @return permission node eg. plan.inspect
*/ */

View File

@ -72,7 +72,7 @@ public class Plan extends BukkitPlugin<Plan> {
private HookHandler hookHandler; // Manages 3rd party data sources private HookHandler hookHandler; // Manages 3rd party data sources
private Database db; private Database db;
private HashSet<Database> databases; private Set<Database> databases;
private WebServer uiServer; private WebServer uiServer;
@ -85,8 +85,9 @@ public class Plan extends BukkitPlugin<Plan> {
* @return API of the current instance of Plan. * @return API of the current instance of Plan.
* @throws IllegalStateException If onEnable method has not been called on * @throws IllegalStateException If onEnable method has not been called on
* Plan and the instance is null. * Plan and the instance is null.
* @throws NoClassDefFoundError If Plan is not installed.
*/ */
public static API getPlanAPI() throws IllegalStateException { public static API getPlanAPI() throws IllegalStateException, NoClassDefFoundError {
Plan instance = getInstance(); Plan instance = getInstance();
if (instance == null) { if (instance == null) {
throw new IllegalStateException("Plugin not enabled properly, Singleton instance is null."); throw new IllegalStateException("Plugin not enabled properly, Singleton instance is null.");
@ -110,7 +111,7 @@ public class Plan extends BukkitPlugin<Plan> {
*/ */
@Override @Override
public void onEnable() { public void onEnable() {
// Sets the Required variables for RslPlugin instance to function correctly // Sets the Required variables for BukkitPlugin instance to function correctly
setInstance(this); setInstance(this);
super.setDebugMode(Settings.DEBUG.toString()); super.setDebugMode(Settings.DEBUG.toString());
super.setColorScheme(new ColorScheme(Phrase.COLOR_MAIN.color(), Phrase.COLOR_SEC.color(), Phrase.COLOR_TER.color())); super.setColorScheme(new ColorScheme(Phrase.COLOR_MAIN.color(), Phrase.COLOR_SEC.color(), Phrase.COLOR_TER.color()));

View File

@ -43,7 +43,7 @@ public class WebCheckCommand extends SubCommand {
if (!Check.isTrue(table.userExists(user), ChatColor.RED + "[Plan] User Doesn't exist.", sender)) { if (!Check.isTrue(table.userExists(user), ChatColor.RED + "[Plan] User Doesn't exist.", sender)) {
return; return;
} }
WebUser info = table.getSecurityInfo(user); WebUser info = table.getWebUser(user);
sender.sendMessage(info.getName() + ": Permission level: " + info.getPermLevel()); sender.sendMessage(info.getName() + ": Permission level: " + info.getPermLevel());
} catch (Exception ex) { } catch (Exception ex) {
Log.toLog(this.getClass().getName(), ex); Log.toLog(this.getClass().getName(), ex);

View File

@ -19,8 +19,6 @@ import java.util.Map.Entry;
*/ */
public class DBUtils { public class DBUtils {
private static final int BATCH_SIZE = 2048;
/** /**
* Constructor used to hide the public constructor * Constructor used to hide the public constructor
*/ */
@ -28,6 +26,8 @@ public class DBUtils {
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
private static final int BATCH_SIZE = 10192;
/** /**
* Splits a collection of objects into lists with the size defined by * Splits a collection of objects into lists with the size defined by
* BATCH_SIZE. * BATCH_SIZE.

View File

@ -30,6 +30,7 @@ import java.util.stream.Collectors;
public abstract class SQLDB extends Database { public abstract class SQLDB extends Database {
private final boolean supportsModification; private final boolean supportsModification;
private final boolean usingMySQL;
private Connection connection; private Connection connection;
@ -40,7 +41,7 @@ public abstract class SQLDB extends Database {
public SQLDB(Plan plugin, boolean supportsModification) { public SQLDB(Plan plugin, boolean supportsModification) {
super(plugin); super(plugin);
this.supportsModification = supportsModification; this.supportsModification = supportsModification;
boolean usingMySQL = getName().equals("MySQL"); usingMySQL = getName().equals("MySQL");
usersTable = new UsersTable(this, usingMySQL); usersTable = new UsersTable(this, usingMySQL);
gmTimesTable = new GMTimesTable(this, usingMySQL); gmTimesTable = new GMTimesTable(this, usingMySQL);
@ -153,7 +154,6 @@ public abstract class SQLDB extends Database {
Log.error("Failed to create table: " + securityTable.getTableName()); Log.error("Failed to create table: " + securityTable.getTableName());
return false; return false;
} }
Benchmark.stop("Database: Create tables"); Benchmark.stop("Database: Create tables");
if (!newDatabase && getVersion() < 8) { if (!newDatabase && getVersion() < 8) {
@ -250,6 +250,7 @@ public abstract class SQLDB extends Database {
@Override @Override
public void setVersion(int version) throws SQLException { public void setVersion(int version) throws SQLException {
versionTable.setVersion(version); versionTable.setVersion(version);
commit();
} }
/** /**
@ -293,7 +294,7 @@ public abstract class SQLDB extends Database {
return false; return false;
} }
int userId = usersTable.getUserId(uuid); int userId = usersTable.getUserId(uuid);
return userId != -1 boolean success = userId != -1
&& locationsTable.removeUserLocations(userId) && locationsTable.removeUserLocations(userId)
&& ipsTable.removeUserIps(userId) && ipsTable.removeUserIps(userId)
&& nicknamesTable.removeUserNicknames(userId) && nicknamesTable.removeUserNicknames(userId)
@ -302,6 +303,12 @@ public abstract class SQLDB extends Database {
&& killsTable.removeUserKillsAndVictims(userId) && killsTable.removeUserKillsAndVictims(userId)
&& worldTimesTable.removeUserWorldTimes(userId) && worldTimesTable.removeUserWorldTimes(userId)
&& usersTable.removeUser(uuid); && usersTable.removeUser(uuid);
if (success) {
commit();
} else {
rollback();
}
return success;
} finally { } finally {
Benchmark.stop("Database: Remove Account"); Benchmark.stop("Database: Remove Account");
setAvailable(); setAvailable();
@ -488,6 +495,7 @@ public abstract class SQLDB extends Database {
gmTimesTable.saveGMTimes(gmTimes); gmTimesTable.saveGMTimes(gmTimes);
worldTable.saveWorlds(worldNames); worldTable.saveWorlds(worldNames);
worldTimesTable.saveWorldTimes(worldTimes); worldTimesTable.saveWorldTimes(worldTimes);
commit();
userDatas.values().stream() userDatas.values().stream()
.filter(Objects::nonNull) .filter(Objects::nonNull)
.filter(UserData::isAccessed) .filter(UserData::isAccessed)
@ -523,6 +531,7 @@ public abstract class SQLDB extends Database {
worldTable.saveWorlds(new HashSet<>(data.getWorldTimes().getTimes().keySet())); worldTable.saveWorlds(new HashSet<>(data.getWorldTimes().getTimes().keySet()));
worldTimesTable.saveWorldTimes(userId, data.getWorldTimes().getTimes()); worldTimesTable.saveWorldTimes(userId, data.getWorldTimes().getTimes());
data.stopAccessing(); data.stopAccessing();
commit();
setAvailable(); setAvailable();
} }
@ -547,14 +556,25 @@ public abstract class SQLDB extends Database {
*/ */
@Override @Override
public boolean removeAllData() { public boolean removeAllData() {
boolean success = true;
setStatus("Clearing all data"); setStatus("Clearing all data");
for (Table table : getAllTablesInRemoveOrder()) { try {
if (!table.removeAllData()) { for (Table table : getAllTablesInRemoveOrder()) {
return false; if (!table.removeAllData()) {
success = false;
break;
}
} }
if (success) {
commit();
} else {
rollback();
}
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
} }
setAvailable(); setAvailable();
return true; return success;
} }
/** /**
@ -578,4 +598,26 @@ public abstract class SQLDB extends Database {
private void setAvailable() { private void setAvailable() {
setStatus("Running"); setStatus("Running");
} }
/**
* Commits changes to the .db file when using SQLite Database.
* <p>
* MySQL has Auto Commit enabled.
*/
public void commit() throws SQLException {
if (!usingMySQL) {
getConnection().commit();
}
}
/**
* Reverts transaction when using SQLite Database.
* <p>
* MySQL has Auto Commit enabled.
*/
public void rollback() throws SQLException {
if (!usingMySQL) {
connection.rollback();
}
}
} }

View File

@ -105,6 +105,7 @@ public class CommandUseTable extends Table {
} }
updateCommands(updateData); updateCommands(updateData);
commit();
Benchmark.stop("Database: Save Commanduse"); Benchmark.stop("Database: Save Commanduse");
} }

View File

@ -77,16 +77,17 @@ public class SecurityTable extends Table {
statement.setString(2, saltPassHash); statement.setString(2, saltPassHash);
statement.setInt(3, permLevel); statement.setInt(3, permLevel);
statement.execute(); statement.execute();
commit();
} finally { } finally {
close(statement); close(statement);
} }
} }
public boolean userExists(String user) throws SQLException { public boolean userExists(String user) throws SQLException {
return getSecurityInfo(user) != null; return getWebUser(user) != null;
} }
public WebUser getSecurityInfo(String user) throws SQLException { public WebUser getWebUser(String user) throws SQLException {
PreparedStatement statement = null; PreparedStatement statement = null;
ResultSet set = null; ResultSet set = null;
try { try {

View File

@ -115,7 +115,6 @@ public class TPSTable extends Table {
/** /**
* @param data * @param data
* @throws SQLException
*/ */
public void saveTPSData(List<TPS> data) { public void saveTPSData(List<TPS> data) {
List<List<TPS>> batches = DBUtils.splitIntoBatches(data); List<List<TPS>> batches = DBUtils.splitIntoBatches(data);

View File

@ -172,4 +172,14 @@ public abstract class Table {
public String toString() { public String toString() {
return tableName; return tableName;
} }
/**
* Commits changes to .db file when using SQLite databse.
*
* Auto Commit enabled when using MySQL
* @throws SQLException If commit fails or there is nothing to commit.
*/
protected void commit() throws SQLException {
db.commit();
}
} }

View File

@ -164,7 +164,7 @@ public class WebServer {
throw new IllegalArgumentException("User Doesn't exist"); throw new IllegalArgumentException("User Doesn't exist");
} }
WebUser webUser = securityTable.getSecurityInfo(user); WebUser webUser = securityTable.getWebUser(user);
boolean correctPass = PassEncryptUtil.verifyPassword(passwordRaw, webUser.getSaltedPassHash()); boolean correctPass = PassEncryptUtil.verifyPassword(passwordRaw, webUser.getSaltedPassHash());
if (!correctPass) { if (!correctPass) {

View File

@ -21,22 +21,26 @@ public class PlayersPageResponse extends Response {
public static String buildContent(List<UserData> cached) { public static String buildContent(List<UserData> cached) {
StringBuilder html = new StringBuilder("<!DOCTYPE html><html><body><h1>Cached Players</h1><p>"); StringBuilder html = new StringBuilder("<!DOCTYPE html><html><body><h1>Cached Players</h1><p>");
int size = cached.size(); int size = cached.size();
html.append(size) html.append(size)
.append(" players. Use browser's Search to find players by name. (Chrome Ctrl+F)</p><table><tr>"); .append(" players. Use browser's Search to find players by name. (Chrome Ctrl+F)</p><table><tr>");
cached.sort(new UserDataNameComparator()); cached.sort(new UserDataNameComparator());
int i = 1; int i = 1;
for (UserData userData : cached) { for (UserData userData : cached) {
String name = userData.getName(); String name = userData.getName();
String link = Html.LINK.parse(HtmlUtils.getRelativeInspectUrl(name), name); String link = Html.LINK.parse(HtmlUtils.getRelativeInspectUrl(name), name);
html.append("<td>").append(link).append("</td>"); html.append("<td>").append(link).append("</td>");
if (i < size
&& i % 8 == 0) { if (i < size && i % 8 == 0) {
html.append("</tr><tr>"); html.append("</tr><tr>");
} }
i++; i++;
} }
html.append("</tr></table></body></html>"); html.append("</tr></table></body></html>");
return html.toString(); return html.toString();
} }

View File

@ -1277,8 +1277,12 @@
} }
var perc = - 100 / navButtons.length; var perc = - 100 / navButtons.length;
slideIndex = i; slideIndex = i;
if (slideIndex > max) {slideIndex = 0}; if (slideIndex > max) {
if (slideIndex < 0) {slideIndex = max}; slideIndex = 0
}
if (slideIndex < 0) {
slideIndex = max
}
window.sessionStorage.setItem("AnalysisSlideIndex", slideIndex); window.sessionStorage.setItem("AnalysisSlideIndex", slideIndex);
var value = slideIndex * perc; var value = slideIndex * perc;
x.style.transition = "0.5s"; x.style.transition = "0.5s";

View File

@ -3,9 +3,11 @@ package test.java.main.java.com.djrapitops.plan.database;
import main.java.com.djrapitops.plan.Plan; import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.TPS; import main.java.com.djrapitops.plan.data.TPS;
import main.java.com.djrapitops.plan.data.UserData; import main.java.com.djrapitops.plan.data.UserData;
import main.java.com.djrapitops.plan.data.WebUser;
import main.java.com.djrapitops.plan.database.Database; import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.database.databases.SQLiteDB; import main.java.com.djrapitops.plan.database.databases.SQLiteDB;
import main.java.com.djrapitops.plan.utilities.MiscUtils; import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.PassEncryptUtil;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
@ -125,4 +127,15 @@ public class DatabaseCommitTest {
db.init(); db.init();
assertTrue(!db.getUserDataForUUIDS(uuids).isEmpty()); assertTrue(!db.getUserDataForUUIDS(uuids).isEmpty());
} }
@Test
public void testCommitToDBFile5() throws SQLException, PassEncryptUtil.CannotPerformOperationException {
db.init();
List<UserData> data = RandomData.randomUserData();
WebUser webUser = new WebUser("Test", PassEncryptUtil.createHash("surprise"), 0);
db.getSecurityTable().addNewUser(webUser);
db.close();
db.init();
assertTrue(webUser.equals(db.getSecurityTable().getWebUser("Test")));
}
} }