Using PreparedStatements instead of normal Statements (#99)

This commit is contained in:
Ceees2 2017-08-23 17:37:25 +02:00 committed by RoboMWM
parent 72504941df
commit a23703707b

View File

@ -1,32 +1,29 @@
/* /*
GriefPrevention Server Plugin for Minecraft GriefPrevention Server Plugin for Minecraft
Copyright (C) 2012 Ryan Hamshire Copyright (C) 2012 Ryan Hamshire
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package me.ryanhamshire.GriefPrevention; package me.ryanhamshire.GriefPrevention;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import java.sql.Connection; import java.sql.*;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
import java.util.Date;
import org.bukkit.*; import org.bukkit.*;
@ -39,6 +36,19 @@ public class DatabaseDataStore extends DataStore
private String userName; private String userName;
private String password; private String password;
private String updateNameSQL;
private String insertClaimSQL;
private String deleteClaimSQL;
private String getPlayerDataSQL;
private String deletePlayerDataSQL;
private String insertPlayerDataSQL;
private String insertNextClaimIdSQL;
private String deleteGroupBonusSQL;
private String insertSchemaVerSQL;
private String deleteNextClaimIdSQL;
private String deleteSchemaVersionSQL;
private String selectSchemaVersionSQL;
DatabaseDataStore(String url, String userName, String password) throws Exception DatabaseDataStore(String url, String userName, String password) throws Exception
{ {
this.databaseUrl = url; this.databaseUrl = url;
@ -93,10 +103,10 @@ public class DatabaseDataStore extends DataStore
//if the next claim id table is empty, this is a brand new database which will write using the latest schema //if the next claim id table is empty, this is a brand new database which will write using the latest schema
//otherwise, schema version is determined by schemaversion table (or =0 if table is empty, see getSchemaVersion()) //otherwise, schema version is determined by schemaversion table (or =0 if table is empty, see getSchemaVersion())
ResultSet results = statement.executeQuery("SELECT * FROM griefprevention_nextclaimid;"); ResultSet results = statement.executeQuery("SELECT * FROM griefprevention_nextclaimid;");
if(!results.next()) if(!results.next())
{ {
this.setSchemaVersion(latestSchemaVersion); this.setSchemaVersion(latestSchemaVersion);
} }
} }
catch(Exception e3) catch(Exception e3)
{ {
@ -106,6 +116,19 @@ public class DatabaseDataStore extends DataStore
throw e3; throw e3;
} }
this.updateNameSQL = "UPDATE griefprevention_playerdata SET name = ? WHERE name = ?;";
this.insertClaimSQL = "INSERT INTO griefprevention_claimdata (id, owner, lessercorner, greatercorner, builders, containers, accessors, managers, inheritnothing, parentid) VALUES(?,?,?,?,?,?,?,?,?,?);";
this.deleteClaimSQL = "DELETE FROM griefprevention_claimdata WHERE id=?;";
this.getPlayerDataSQL = "SELECT * FROM griefprevention_playerdata WHERE name=?;";
this.deletePlayerDataSQL = "DELETE FROM griefprevention_playerdata WHERE name=?;";
this.insertPlayerDataSQL = "INSERT INTO griefprevention_playerdata (name, lastlogin, accruedblocks, bonusblocks) VALUES (?,?,?,?);";
this.insertNextClaimIdSQL = "INSERT INTO griefprevention_nextclaimid VALUES (?);";
this.deleteGroupBonusSQL = "DELETE FROM griefprevention_playerdata WHERE name=?;";
this.insertSchemaVerSQL = "INSERT INTO griefprevention_schemaversion VALUES (?)";
this.deleteNextClaimIdSQL = "DELETE FROM griefprevention_nextclaimid;";
this.deleteSchemaVersionSQL = "DELETE FROM griefprevention_schemaversion;";
this.selectSchemaVersionSQL = "SELECT * FROM griefprevention_schemaversion;";
//load group data into memory //load group data into memory
Statement statement = databaseConnection.createStatement(); Statement statement = databaseConnection.createStatement();
ResultSet results = statement.executeQuery("SELECT * FROM griefprevention_playerdata;"); ResultSet results = statement.executeQuery("SELECT * FROM griefprevention_playerdata;");
@ -142,88 +165,88 @@ public class DatabaseDataStore extends DataStore
} }
if(this.getSchemaVersion() == 0) if(this.getSchemaVersion() == 0)
{ {
try try
{ {
this.refreshDataConnection(); this.refreshDataConnection();
//pull ALL player data from the database //pull ALL player data from the database
statement = this.databaseConnection.createStatement(); statement = this.databaseConnection.createStatement();
results = statement.executeQuery("SELECT * FROM griefprevention_playerdata;"); results = statement.executeQuery("SELECT * FROM griefprevention_playerdata;");
//make a list of changes to be made //make a list of changes to be made
HashMap<String, UUID> changes = new HashMap<String, UUID>(); HashMap<String, UUID> changes = new HashMap<String, UUID>();
ArrayList<String> namesToConvert = new ArrayList<String>(); ArrayList<String> namesToConvert = new ArrayList<String>();
while(results.next()) while(results.next())
{ {
//get the id //get the id
String playerName = results.getString("name"); String playerName = results.getString("name");
//add to list of names to convert to UUID //add to list of names to convert to UUID
namesToConvert.add(playerName); namesToConvert.add(playerName);
} }
//resolve and cache as many as possible through various means //resolve and cache as many as possible through various means
try try
{ {
UUIDFetcher fetcher = new UUIDFetcher(namesToConvert); UUIDFetcher fetcher = new UUIDFetcher(namesToConvert);
fetcher.call(); fetcher.call();
} }
catch(Exception e) catch(Exception e)
{ {
GriefPrevention.AddLogEntry("Failed to resolve a batch of names to UUIDs. Details:" + e.getMessage()); GriefPrevention.AddLogEntry("Failed to resolve a batch of names to UUIDs. Details:" + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
//reset results cursor //reset results cursor
results.beforeFirst(); results.beforeFirst();
//for each result //for each result
while(results.next()) while(results.next())
{ {
//get the id //get the id
String playerName = results.getString("name"); String playerName = results.getString("name");
//try to convert player name to UUID //try to convert player name to UUID
try try
{ {
UUID playerID = UUIDFetcher.getUUIDOf(playerName); UUID playerID = UUIDFetcher.getUUIDOf(playerName);
//if successful, update the playerdata row by replacing the player's name with the player's UUID //if successful, update the playerdata row by replacing the player's name with the player's UUID
if(playerID != null) if(playerID != null)
{ {
changes.put(playerName, playerID); changes.put(playerName, playerID);
} }
} }
//otherwise leave it as-is. no harm done - it won't be requested by name, and this update only happens once. //otherwise leave it as-is. no harm done - it won't be requested by name, and this update only happens once.
catch(Exception ex){ } catch(Exception ex){ }
} }
//refresh data connection in case data migration took a long time //refresh data connection in case data migration took a long time
this.refreshDataConnection(); this.refreshDataConnection();
for(String name : changes.keySet()) for(String name : changes.keySet())
{ {
try try (PreparedStatement updateStmnt = this.databaseConnection.prepareStatement(this.getUpdateNameSQL())) {
{ updateStmnt.setString(1, changes.get(name).toString());
statement = this.databaseConnection.createStatement(); updateStmnt.setString(2, name);
statement.execute("UPDATE griefprevention_playerdata SET name = '" + changes.get(name).toString() + "' WHERE name = '" + name + "';"); updateStmnt.executeUpdate();
} }
catch(SQLException e) catch(SQLException e)
{ {
GriefPrevention.AddLogEntry("Unable to convert player data for " + name + ". Skipping."); GriefPrevention.AddLogEntry("Unable to convert player data for " + name + ". Skipping.");
GriefPrevention.AddLogEntry(e.getMessage()); GriefPrevention.AddLogEntry(e.getMessage());
} }
} }
} }
catch(SQLException e) catch(SQLException e)
{ {
GriefPrevention.AddLogEntry("Unable to convert player data. Details:"); GriefPrevention.AddLogEntry("Unable to convert player data. Details:");
GriefPrevention.AddLogEntry(e.getMessage()); GriefPrevention.AddLogEntry(e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
} }
if(this.getSchemaVersion() <= 2) if(this.getSchemaVersion() <= 2)
{ {
@ -231,8 +254,8 @@ public class DatabaseDataStore extends DataStore
statement.execute("ALTER TABLE griefprevention_claimdata ADD inheritNothing BOOLEAN DEFAULT 0 AFTER managers;"); statement.execute("ALTER TABLE griefprevention_claimdata ADD inheritNothing BOOLEAN DEFAULT 0 AFTER managers;");
} }
//load claims data into memory //load claims data into memory
results = statement.executeQuery("SELECT * FROM griefprevention_claimdata;"); results = statement.executeQuery("SELECT * FROM griefprevention_claimdata;");
ArrayList<Claim> claimsToRemove = new ArrayList<Claim>(); ArrayList<Claim> claimsToRemove = new ArrayList<Claim>();
@ -250,7 +273,6 @@ public class DatabaseDataStore extends DataStore
long parentId = results.getLong("parentid"); long parentId = results.getLong("parentid");
claimID = results.getLong("id"); claimID = results.getLong("id");
boolean inheritNothing = results.getBoolean("inheritNothing"); boolean inheritNothing = results.getBoolean("inheritNothing");
Location lesserBoundaryCorner = null; Location lesserBoundaryCorner = null;
Location greaterBoundaryCorner = null; Location greaterBoundaryCorner = null;
String lesserCornerString = "(location not available)"; String lesserCornerString = "(location not available)";
@ -258,53 +280,52 @@ public class DatabaseDataStore extends DataStore
{ {
lesserCornerString = results.getString("lessercorner"); lesserCornerString = results.getString("lessercorner");
lesserBoundaryCorner = this.locationFromString(lesserCornerString, validWorlds); lesserBoundaryCorner = this.locationFromString(lesserCornerString, validWorlds);
String greaterCornerString = results.getString("greatercorner"); String greaterCornerString = results.getString("greatercorner");
greaterBoundaryCorner = this.locationFromString(greaterCornerString, validWorlds); greaterBoundaryCorner = this.locationFromString(greaterCornerString, validWorlds);
} }
catch(Exception e) catch(Exception e)
{ {
if(e.getMessage() != null && e.getMessage().contains("World not found")) if(e.getMessage() != null && e.getMessage().contains("World not found"))
{ {
GriefPrevention.AddLogEntry("Failed to load a claim (ID:" + claimID.toString() + ") because its world isn't loaded (yet?). Please delete the claim or contact the GriefPrevention developer with information about which plugin(s) you're using to load or create worlds. " + lesserCornerString); GriefPrevention.AddLogEntry("Failed to load a claim (ID:" + claimID.toString() + ") because its world isn't loaded (yet?). Please delete the claim or contact the GriefPrevention developer with information about which plugin(s) you're using to load or create worlds. " + lesserCornerString);
continue; continue;
} }
else else
{ {
throw e; throw e;
} }
} }
String ownerName = results.getString("owner"); String ownerName = results.getString("owner");
UUID ownerID = null; UUID ownerID = null;
if(ownerName.isEmpty() || ownerName.startsWith("--")) if(ownerName.isEmpty() || ownerName.startsWith("--"))
{ {
ownerID = null; //administrative land claim or subdivision ownerID = null; //administrative land claim or subdivision
} }
else if(this.getSchemaVersion() < 1) else if(this.getSchemaVersion() < 1)
{ {
try try
{ {
ownerID = UUIDFetcher.getUUIDOf(ownerName); ownerID = UUIDFetcher.getUUIDOf(ownerName);
} }
catch(Exception ex) catch(Exception ex)
{ {
GriefPrevention.AddLogEntry("This owner name did not convert to a UUID: " + ownerName + "."); GriefPrevention.AddLogEntry("This owner name did not convert to a UUID: " + ownerName + ".");
GriefPrevention.AddLogEntry(" Converted land claim to administrative @ " + lesserBoundaryCorner.toString()); GriefPrevention.AddLogEntry(" Converted land claim to administrative @ " + lesserBoundaryCorner.toString());
} }
} }
else else
{ {
try try
{ {
ownerID = UUID.fromString(ownerName); ownerID = UUID.fromString(ownerName);
} }
catch(Exception ex) catch(Exception ex)
{ {
GriefPrevention.AddLogEntry("This owner entry is not a UUID: " + ownerName + "."); GriefPrevention.AddLogEntry("This owner entry is not a UUID: " + ownerName + ".");
GriefPrevention.AddLogEntry(" Converted land claim to administrative @ " + lesserBoundaryCorner.toString()); GriefPrevention.AddLogEntry(" Converted land claim to administrative @ " + lesserBoundaryCorner.toString());
} }
} }
String buildersString = results.getString("builders"); String buildersString = results.getString("builders");
List<String> builderNames = Arrays.asList(buildersString.split(";")); List<String> builderNames = Arrays.asList(buildersString.split(";"));
@ -321,22 +342,21 @@ public class DatabaseDataStore extends DataStore
String managersString = results.getString("managers"); String managersString = results.getString("managers");
List<String> managerNames = Arrays.asList(managersString.split(";")); List<String> managerNames = Arrays.asList(managersString.split(";"));
managerNames = this.convertNameListToUUIDList(managerNames); managerNames = this.convertNameListToUUIDList(managerNames);
Claim claim = new Claim(lesserBoundaryCorner, greaterBoundaryCorner, ownerID, builderNames, containerNames, accessorNames, managerNames, inheritNothing, claimID); Claim claim = new Claim(lesserBoundaryCorner, greaterBoundaryCorner, ownerID, builderNames, containerNames, accessorNames, managerNames, inheritNothing, claimID);
if(removeClaim) if(removeClaim)
{ {
claimsToRemove.add(claim); claimsToRemove.add(claim);
} }
else if(parentId == -1) else if(parentId == -1)
{ {
//top level claim //top level claim
this.addClaim(claim, false); this.addClaim(claim, false);
} }
else else
{ {
//subdivision //subdivision
subdivisionsToLoad.add(claim); subdivisionsToLoad.add(claim);
} }
} }
catch(SQLException e) catch(SQLException e)
@ -347,34 +367,34 @@ public class DatabaseDataStore extends DataStore
} }
//add subdivisions to their parent claims //add subdivisions to their parent claims
for(Claim childClaim : subdivisionsToLoad) for(Claim childClaim : subdivisionsToLoad)
{
//find top level claim parent
Claim topLevelClaim = this.getClaimAt(childClaim.getLesserBoundaryCorner(), true, null);
if(topLevelClaim == null)
{
claimsToRemove.add(childClaim);
GriefPrevention.AddLogEntry("Removing orphaned claim subdivision: " + childClaim.getLesserBoundaryCorner().toString());
continue;
}
//add this claim to the list of children of the current top level claim
childClaim.parent = topLevelClaim;
topLevelClaim.children.add(childClaim);
childClaim.inDataStore = true;
}
for(int i = 0; i < claimsToRemove.size(); i++)
{ {
this.deleteClaimFromSecondaryStorage(claimsToRemove.get(i)); //find top level claim parent
Claim topLevelClaim = this.getClaimAt(childClaim.getLesserBoundaryCorner(), true, null);
if(topLevelClaim == null)
{
claimsToRemove.add(childClaim);
GriefPrevention.AddLogEntry("Removing orphaned claim subdivision: " + childClaim.getLesserBoundaryCorner().toString());
continue;
}
//add this claim to the list of children of the current top level claim
childClaim.parent = topLevelClaim;
topLevelClaim.children.add(childClaim);
childClaim.inDataStore = true;
}
for(Claim claim : claimsToRemove)
{
this.deleteClaimFromSecondaryStorage(claim);
} }
if(this.getSchemaVersion() <= 2) if(this.getSchemaVersion() <= 2)
{ {
this.refreshDataConnection(); this.refreshDataConnection();
statement = this.databaseConnection.createStatement(); statement = this.databaseConnection.createStatement();
statement.execute("DELETE FROM griefprevention_claimdata WHERE id='-1';"); statement.execute("DELETE FROM griefprevention_claimdata WHERE id='-1';");
} }
super.initialize(); super.initialize();
@ -415,59 +435,26 @@ public class DatabaseDataStore extends DataStore
claim.getPermissions(builders, containers, accessors, managers); claim.getPermissions(builders, containers, accessors, managers);
String buildersString = ""; String buildersString = this.storageStringBuilder(builders);
for(int i = 0; i < builders.size(); i++) String containersString = this.storageStringBuilder(containers);
{ String accessorsString = this.storageStringBuilder(accessors);
buildersString += builders.get(i) + ";"; String managersString = this.storageStringBuilder(managers);
}
String containersString = "";
for(int i = 0; i < containers.size(); i++)
{
containersString += containers.get(i) + ";";
}
String accessorsString = "";
for(int i = 0; i < accessors.size(); i++)
{
accessorsString += accessors.get(i) + ";";
}
String managersString = "";
for(int i = 0; i < managers.size(); i++)
{
managersString += managers.get(i) + ";";
}
boolean inheritNothing = claim.getSubclaimRestrictions(); boolean inheritNothing = claim.getSubclaimRestrictions();
long parentId = claim.parent == null ? -1 : claim.parent.id;
long parentId; try (PreparedStatement insertStmt = this.databaseConnection.prepareStatement(this.getInsertClaimSQL())) {
if(claim.parent == null)
{
parentId = -1;
}
else
{
parentId = claim.parent.id;
}
try insertStmt.setLong(1, claim.id);
{ insertStmt.setString(2, owner);
this.refreshDataConnection(); insertStmt.setString(3, lesserCornerString);
insertStmt.setString(4, greaterCornerString);
Statement statement = databaseConnection.createStatement(); insertStmt.setString(5, buildersString);
statement.execute("INSERT INTO griefprevention_claimdata (id, owner, lessercorner, greatercorner, builders, containers, accessors, managers, inheritnothing, parentid) VALUES(" + insertStmt.setString(6, containersString);
claim.id + ", '" + insertStmt.setString(7, accessorsString);
owner + "', '" + insertStmt.setString(8, managersString);
lesserCornerString + "', '" + insertStmt.setBoolean(9, inheritNothing);
greaterCornerString + "', '" + insertStmt.setLong(10, parentId);
buildersString + "', '" + insertStmt.executeUpdate();
containersString + "', '" +
accessorsString + "', '" +
managersString + "', " +
inheritNothing + ", "+
parentId +
");");
} }
catch(SQLException e) catch(SQLException e)
{ {
@ -480,13 +467,9 @@ public class DatabaseDataStore extends DataStore
@Override @Override
synchronized void deleteClaimFromSecondaryStorage(Claim claim) synchronized void deleteClaimFromSecondaryStorage(Claim claim)
{ {
try try(PreparedStatement deleteStmnt = this.databaseConnection.prepareStatement(this.getDeleteClaimSQL())) {
{ deleteStmnt.setLong(1, claim.id);
this.refreshDataConnection(); deleteStmnt.executeUpdate();
Statement statement = this.databaseConnection.createStatement();
statement.execute("DELETE FROM griefprevention_claimdata WHERE id='" + claim.id + "';");
} }
catch(SQLException e) catch(SQLException e)
{ {
@ -502,12 +485,10 @@ public class DatabaseDataStore extends DataStore
PlayerData playerData = new PlayerData(); PlayerData playerData = new PlayerData();
playerData.playerID = playerID; playerData.playerID = playerID;
try try (PreparedStatement selectStmnt = this.databaseConnection.prepareStatement( this.getGetPlayerDataSQL()))
{ {
this.refreshDataConnection(); selectStmnt.setString(1, playerID.toString());
ResultSet results = selectStmnt.executeQuery();
Statement statement = this.databaseConnection.createStatement();
ResultSet results = statement.executeQuery("SELECT * FROM griefprevention_playerdata WHERE name='" + playerID.toString() + "';");
//if data for this player exists, use it //if data for this player exists, use it
if(results.next()) if(results.next())
@ -518,9 +499,9 @@ public class DatabaseDataStore extends DataStore
} }
catch(SQLException e) catch(SQLException e)
{ {
StringWriter errors = new StringWriter(); StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors)); e.printStackTrace(new PrintWriter(errors));
GriefPrevention.AddLogEntry(playerID + " " + errors.toString(), CustomLogEntryTypes.Exception); GriefPrevention.AddLogEntry(playerID + " " + errors.toString(), CustomLogEntryTypes.Exception);
} }
return playerData; return playerData;
@ -538,24 +519,26 @@ public class DatabaseDataStore extends DataStore
private void savePlayerData(String playerID, PlayerData playerData) private void savePlayerData(String playerID, PlayerData playerData)
{ {
try try (PreparedStatement deleteStmnt = this.databaseConnection.prepareStatement(this.getDeletePlayerDataSQL());
{ PreparedStatement insertStmnt = this.databaseConnection.prepareStatement(this.getInsertPlayerDataSQL())) {
this.refreshDataConnection();
OfflinePlayer player = Bukkit.getOfflinePlayer(UUID.fromString(playerID)); OfflinePlayer player = Bukkit.getOfflinePlayer(UUID.fromString(playerID));
SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sqlFormat.format(new Date(player.getLastPlayed())); String dateString = sqlFormat.format(new Date(player.getLastPlayed()));
deleteStmnt.setString(1, playerID);
deleteStmnt.executeUpdate();
Statement statement = databaseConnection.createStatement(); insertStmnt.setString(1, playerID);
statement.execute("DELETE FROM griefprevention_playerdata WHERE name='" + playerID.toString() + "';"); insertStmnt.setString(2, dateString);
statement = databaseConnection.createStatement(); insertStmnt.setInt(3, playerData.getAccruedClaimBlocks());
statement.execute("INSERT INTO griefprevention_playerdata (name, lastlogin, accruedblocks, bonusblocks) VALUES ('" + playerID.toString() + "', '" + dateString + "', " + playerData.getAccruedClaimBlocks() + ", " + playerData.getBonusClaimBlocks() + ");"); insertStmnt.setInt(4, playerData.getBonusClaimBlocks());
insertStmnt.executeUpdate();
} }
catch(SQLException e) catch(SQLException e)
{ {
StringWriter errors = new StringWriter(); StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors)); e.printStackTrace(new PrintWriter(errors));
GriefPrevention.AddLogEntry(playerID + " " + errors.toString(), CustomLogEntryTypes.Exception); GriefPrevention.AddLogEntry(playerID + " " + errors.toString(), CustomLogEntryTypes.Exception);
} }
} }
@ -570,13 +553,11 @@ public class DatabaseDataStore extends DataStore
{ {
this.nextClaimID = nextID; this.nextClaimID = nextID;
try try (PreparedStatement deleteStmnt = this.databaseConnection.prepareStatement(this.getDeleteNextClaimIdSQL());
{ PreparedStatement insertStmnt = this.databaseConnection.prepareStatement(this.getInsertNextClaimIdSQL())) {
this.refreshDataConnection(); deleteStmnt.execute();
insertStmnt.setLong(1, nextID);
Statement statement = databaseConnection.createStatement(); insertStmnt.executeUpdate();
statement.execute("DELETE FROM griefprevention_nextclaimid;");
statement.execute("INSERT INTO griefprevention_nextclaimid VALUES (" + nextID + ");");
} }
catch(SQLException e) catch(SQLException e)
{ {
@ -590,23 +571,24 @@ public class DatabaseDataStore extends DataStore
synchronized void saveGroupBonusBlocks(String groupName, int currentValue) synchronized void saveGroupBonusBlocks(String groupName, int currentValue)
{ {
//group bonus blocks are stored in the player data table, with player name = $groupName //group bonus blocks are stored in the player data table, with player name = $groupName
try try (PreparedStatement deleteStmnt = this.databaseConnection.prepareStatement(this.getDeleteGroupBonusSQL());
{ PreparedStatement insertStmnt = this.databaseConnection.prepareStatement(this.getInsertPlayerDataSQL())) {
this.refreshDataConnection(); SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sqlFormat.format(new Date());
deleteStmnt.setString(1, '$' + groupName);
deleteStmnt.executeUpdate();
SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); insertStmnt.setString(1, '$' + groupName);
String dateString = sqlFormat.format(new Date()); insertStmnt.setString(2, dateString);
insertStmnt.setInt(3, 0);
Statement statement = databaseConnection.createStatement(); insertStmnt.setInt(4, currentValue);
statement.execute("DELETE FROM griefprevention_playerdata WHERE name='$" + groupName + "';"); insertStmnt.executeUpdate();
statement = databaseConnection.createStatement(); }
statement.execute("INSERT INTO griefprevention_playerdata (name, lastlogin, accruedblocks, bonusblocks) VALUES ('$" + groupName + "', '" + dateString + "', " + "0" + ", " + String.valueOf(currentValue) + ");"); catch(SQLException e)
} {
catch(SQLException e) GriefPrevention.AddLogEntry("Unable to save data for group " + groupName + ". Details:");
{ GriefPrevention.AddLogEntry(e.getMessage());
GriefPrevention.AddLogEntry("Unable to save data for group " + groupName + ". Details:"); }
GriefPrevention.AddLogEntry(e.getMessage());
}
} }
@Override @Override
@ -632,11 +614,11 @@ public class DatabaseDataStore extends DataStore
if(this.databaseConnection == null || !this.databaseConnection.isValid(3)) if(this.databaseConnection == null || !this.databaseConnection.isValid(3))
{ {
if(this.databaseConnection != null && !this.databaseConnection.isClosed()) if(this.databaseConnection != null && !this.databaseConnection.isClosed())
{ {
this.databaseConnection.close(); this.databaseConnection.close();
} }
//set username/pass properties //set username/pass properties
Properties connectionProps = new Properties(); Properties connectionProps = new Properties();
connectionProps.put("user", this.userName); connectionProps.put("user", this.userName);
connectionProps.put("password", this.password); connectionProps.put("password", this.password);
@ -648,54 +630,108 @@ public class DatabaseDataStore extends DataStore
} }
} }
@Override @Override
protected int getSchemaVersionFromStorage() protected int getSchemaVersionFromStorage()
{ {
try try (PreparedStatement selectStmnt = this.databaseConnection.prepareStatement(this.getSelectSchemaVersionSQL())) {
{ ResultSet results = selectStmnt.executeQuery();
this.refreshDataConnection();
Statement statement = this.databaseConnection.createStatement(); //if there's nothing yet, assume 0 and add it
ResultSet results = statement.executeQuery("SELECT * FROM griefprevention_schemaversion;"); if(!results.next())
{
this.setSchemaVersion(0);
return 0;
}
//otherwise return the value that's in the table
else
{
return results.getInt("version");
}
}
catch(SQLException e)
{
GriefPrevention.AddLogEntry("Unable to retrieve schema version from database. Details:");
GriefPrevention.AddLogEntry(e.getMessage());
e.printStackTrace();
return 0;
}
}
//if there's nothing yet, assume 0 and add it @Override
if(!results.next()) protected void updateSchemaVersionInStorage(int versionToSet)
{ {
this.setSchemaVersion(0); try (PreparedStatement deleteStmnt = this.databaseConnection.prepareStatement(this.getDeleteSchemaVersionSQL());
return 0; PreparedStatement insertStmnt = this.databaseConnection.prepareStatement(this.getInsertSchemaVerSQL())) {
} deleteStmnt.execute();
//otherwise return the value that's in the table insertStmnt.setInt(1, versionToSet);
else insertStmnt.executeUpdate();
{ }
return results.getInt("version"); catch(SQLException e)
} {
GriefPrevention.AddLogEntry("Unable to set next schema version to " + versionToSet + ". Details:");
GriefPrevention.AddLogEntry(e.getMessage());
}
}
} /**
catch(SQLException e) * Concats an array to a string divided with the ; sign
{ * @param input Arraylist with strings to concat
GriefPrevention.AddLogEntry("Unable to retrieve schema version from database. Details:"); * @return String with all values from input array
GriefPrevention.AddLogEntry(e.getMessage()); */
e.printStackTrace(); private String storageStringBuilder(ArrayList<String> input) {
return 0; String output = "";
} for(String string : input) {
} output += string + ";";
}
return output;
}
@Override public String getUpdateNameSQL() {
protected void updateSchemaVersionInStorage(int versionToSet) return updateNameSQL;
{ }
try
{
this.refreshDataConnection();
Statement statement = databaseConnection.createStatement(); public String getInsertClaimSQL() {
statement.execute("DELETE FROM griefprevention_schemaversion;"); return insertClaimSQL;
statement.execute("INSERT INTO griefprevention_schemaversion VALUES (" + versionToSet + ");"); }
}
catch(SQLException e) public String getDeleteClaimSQL() {
{ return deleteClaimSQL;
GriefPrevention.AddLogEntry("Unable to set next schema version to " + versionToSet + ". Details:"); }
GriefPrevention.AddLogEntry(e.getMessage());
} public String getGetPlayerDataSQL() {
} return getPlayerDataSQL;
}
public String getDeletePlayerDataSQL() {
return deletePlayerDataSQL;
}
public String getInsertPlayerDataSQL() {
return insertPlayerDataSQL;
}
public String getInsertNextClaimIdSQL() {
return insertNextClaimIdSQL;
}
public String getDeleteGroupBonusSQL() {
return deleteGroupBonusSQL;
}
public String getInsertSchemaVerSQL() {
return insertSchemaVerSQL;
}
public String getDeleteNextClaimIdSQL() {
return deleteNextClaimIdSQL;
}
public String getDeleteSchemaVersionSQL() {
return deleteSchemaVersionSQL;
}
public String getSelectSchemaVersionSQL() {
return selectSchemaVersionSQL;
}
} }