Mega Update

Performance optimisation
Async MySQL
Code cleanup/restructure
This commit is contained in:
GeorgH93 2015-09-24 17:06:00 +02:00
parent daa328cd1f
commit fcb44a0a55
11 changed files with 658 additions and 473 deletions

View File

@ -43,7 +43,7 @@ Database:
# true: Only to use if your server is running in online mode and your minecraft version is 1.7.5 or newer
# false: In offline mode or for minecraft version below 1.7.5
# Should be configured automaticaly based on your minecraft version and online mode settings
# If you are using BungeeCord please set this setting based on your BungeeCord's online mode.
# If you are using BungeeCord please set this setting based on your BungeeCord's online mode!!!
UseUUIDs: true
# Defines the storage format for UUIDs for compatibility with other plugins (shared tables)
# true: format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
@ -55,12 +55,18 @@ Database:
Database: minecraft
User: minecraft
Password: minecraft
# Tables settings for shared tables
# Tables settings for shared tables when using MySQL - Advanced MySQL Settings
# Use these settings only if you know what you are doing!!!!
# Do only change this settings if you know what you are doing and have some basic MySQL knowlage!!!
# Changing settings down here after you have used this plugin may result in data inconsitency!!!
Tables:
# Table names
# Don't change the players table if you have backpacks stored in your database already! Player id's might wont match anymore resulting data inconsitency.
User: backpack_players
Backpack: backpacks
# Field settings for the tables
# Do not change them after the tables have been generated!
# If you like to change them after the tables have been generated alter the tables manualy or delete them (the system then will regenerate them).
Fields:
User:
Player_ID: player_id

View File

@ -26,16 +26,17 @@
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
public class Backpack
public class Backpack implements InventoryHolder
{
private OfflinePlayer owner;
private HashMap<Player, Boolean> opened = new HashMap<>();
private Inventory bp;
private int size, id;
private int size, ownerID;
private String title;
private boolean inWork;
private boolean inWork, hasChanged;
public Backpack(OfflinePlayer owner)
{
@ -51,9 +52,9 @@ public Backpack(OfflinePlayer owner, int Size, int ID)
{
this.owner = owner;
title = String.format(MinePacks.BackpackTitle, owner.getName());
bp = Bukkit.createInventory(null, Size, title);
bp = Bukkit.createInventory(this, Size, title);
size = Size;
id = ID;
ownerID = ID;
inWork = false;
}
@ -63,14 +64,14 @@ public Backpack(OfflinePlayer owner, ItemStack[] backpack, int ID)
bp.setContents(backpack);
}
public int getID()
public int getOwnerID()
{
return id;
return ownerID;
}
public void setID(int ID)
public void setOwnerID(int id)
{
id = ID;
ownerID = id;
}
public OfflinePlayer getOwner()
@ -80,6 +81,25 @@ public OfflinePlayer getOwner()
public void open(Player p, boolean editable)
{
if(owner.isOnline())
{
Player player = owner.getPlayer();
if(player != null)
{
int size = MinePacks.getInstance().getBackpackPermSize(player);
if(size != bp.getSize())
{
List<ItemStack> items = setSize(size);
for(ItemStack i : items)
{
if (i != null)
{
player.getWorld().dropItemNaturally(player.getLocation(), i);
}
}
}
}
}
opened.put(p, editable);
p.openInventory(bp);
}
@ -103,7 +123,8 @@ public boolean inUse()
{
return inWork;
}
@SuppressWarnings("unused")
public int getSize()
{
return size;
@ -155,9 +176,34 @@ public List<ItemStack> setSize(int newSize)
inWork = false;
return removedItems;
}
public Inventory getBackpack()
/**
* Get the object's inventory.
*
* @return The inventory.
*/
public Inventory getInventory()
{
return bp;
}
@SuppressWarnings("unused")
public boolean hasChanged()
{
return hasChanged;
}
public void setChanged()
{
hasChanged = true;
}
public void save()
{
if(hasChanged)
{
MinePacks.getInstance().DB.saveBackpack(this);
hasChanged = false;
}
}
}

View File

@ -17,55 +17,33 @@
package at.pcgamingfreaks.georgh.MinePacks.Database;
import java.util.HashSet;
import java.util.HashMap;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import at.pcgamingfreaks.georgh.MinePacks.Backpack;
import at.pcgamingfreaks.georgh.MinePacks.MinePacks;
import at.pcgamingfreaks.georgh.MinePacks.Database.ItemStackSerializer.ItemStackSerializer;
import org.bukkit.inventory.Inventory;
import at.pcgamingfreaks.georgh.MinePacks.Database.ItemStackSerializer.InventorySerializer;
public class Database
{
protected MinePacks plugin;
protected boolean UseUUIDs, UseUUIDSeparators;
protected boolean useUUIDs, useUUIDSeparators;
protected long maxAge;
private HashSet<Backpack> backpacks = new HashSet<>();
protected ItemStackSerializer itsSerializer = new ItemStackSerializer();
private HashMap<OfflinePlayer, Backpack> backpacks = new HashMap<>();
protected InventorySerializer itsSerializer = new InventorySerializer();
public Database(MinePacks mp)
{
plugin = mp;
UseUUIDSeparators = plugin.config.getUseUUIDSeparators();
UseUUIDs = plugin.config.getUseUUIDs();
useUUIDSeparators = plugin.config.getUseUUIDSeparators();
useUUIDs = plugin.config.getUseUUIDs();
maxAge = plugin.config.getAutoCleanupMaxInactiveDays();
}
public void close() { }
protected String getPlayerNameOrUUID(OfflinePlayer player)
{
if(UseUUIDs)
{
if(UseUUIDSeparators)
{
return player.getUniqueId().toString();
}
else
{
return player.getUniqueId().toString().replace("-", "");
}
}
else
{
return player.getName();
}
}
public static Database getDatabase(MinePacks Plugin)
{
switch(Plugin.config.getDatabaseType().toLowerCase())
@ -79,33 +57,44 @@ public static Database getDatabase(MinePacks Plugin)
}
}
private Backpack findBackpack(OfflinePlayer player)
protected String getPlayerNameOrUUID(OfflinePlayer player)
{
for(Backpack bp : backpacks)
if(useUUIDs)
{
if(bp.getOwner().equals(player))
{
return bp;
}
return (useUUIDSeparators) ? player.getUniqueId().toString() : player.getUniqueId().toString().replace("-", "");
}
else
{
return player.getName();
}
}
protected String getPlayerFormattedUUID(OfflinePlayer player)
{
if(useUUIDs)
{
return (useUUIDSeparators) ? player.getUniqueId().toString() : player.getUniqueId().toString().replace("-", "");
}
return null;
}
public Backpack getBackpack(Inventory inventory)
public Backpack getBackpack(OfflinePlayer player)
{
for(Backpack bp : backpacks)
if(player == null)
{
if(bp.getBackpack().equals(inventory))
{
return bp;
}
return null;
}
return null;
return backpacks.get(player);
}
@SuppressWarnings("unused")
public Backpack getBackpack(OfflinePlayer player, boolean loadedOnly)
{
Backpack lbp = findBackpack(player);
if(player == null)
{
return null;
}
Backpack lbp = backpacks.get(player);
if(lbp == null && !loadedOnly)
{
lbp = loadBackpack(player);
@ -113,21 +102,86 @@ public Backpack getBackpack(OfflinePlayer player, boolean loadedOnly)
{
lbp = new Backpack(player);
}
backpacks.add(lbp);
backpacks.put(player, lbp);
}
return lbp;
}
public void UnloadBackpack(Backpack backpack)
public void getBackpack(final OfflinePlayer player, final Callback<Backpack> callback)
{
backpacks.remove(backpack);
if(player == null)
{
return;
}
Backpack lbp = backpacks.get(player);
if(lbp == null)
{
loadBackpack(player, new Callback<Backpack>()
{
@Override
public void onResult(Backpack backpack)
{
if(backpack == null)
{
backpack = new Backpack(player);
}
backpacks.put(player, backpack);
callback.onResult(backpack);
}
});
}
else
{
callback.onResult(lbp);
}
}
public void unloadBackpack(Backpack backpack)
{
backpacks.remove(backpack.getOwner());
}
public void asyncLoadBackpack(final OfflinePlayer player)
{
if(player != null && backpacks.get(player) == null)
{
loadBackpack(player, new Callback<Backpack>()
{
@Override
public void onResult(Backpack backpack)
{
if(backpack == null)
{
backpack = new Backpack(player);
}
backpacks.put(player, backpack);
}
});
}
}
// DB Functions
public void close() { }
public void updatePlayerAndLoadBackpack(Player player)
{
updatePlayer(player);
asyncLoadBackpack(player);
}
public void updatePlayer(Player player) {}
public void saveBackpack(Backpack backpack) {}
public Backpack loadBackpack(OfflinePlayer player) { return null; }
protected Backpack loadBackpack(OfflinePlayer player) { return null; }
protected void loadBackpack(final OfflinePlayer player, final Callback<Backpack> callback)
{
callback.onResult(loadBackpack(player));
}
public interface Callback<T>
{
void onResult(T done);
}
}

View File

@ -65,24 +65,24 @@ private void CheckFiles()
continue; // We don't have to check if the file name is correct cause we have the deleted the file
}
len = file.getName().length() - ext.length();
if(UseUUIDs) // Use UUID-based saving
if(useUUIDs) // Use UUID-based saving
{
if(len <= 16) // It's a player name
{
file.renameTo(new File(saveFolder, UUIDConverter.getUUIDFromName(file.getName().substring(0, len), true, UseUUIDSeparators) + ext));
file.renameTo(new File(saveFolder, UUIDConverter.getUUIDFromName(file.getName().substring(0, len), true, useUUIDSeparators) + ext));
}
else // It's an UUID
{
if(file.getName().contains("-"))
{
if(!UseUUIDSeparators)
if(!useUUIDSeparators)
{
file.renameTo(new File(saveFolder, file.getName().replaceAll("-", "")));
}
}
else
{
if(UseUUIDSeparators)
if(useUUIDSeparators)
{
file.renameTo(new File(saveFolder, file.getName().replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})" + ext, "$1-$2-$3-$4-$5" + ext)));
}
@ -105,14 +105,15 @@ private String getFileName(OfflinePlayer player)
}
// DB Functions
@Override
public void saveBackpack(Backpack backpack)
{
File save = new File(saveFolder, getFileName(backpack.getOwner()));
try
{
FileOutputStream fos = new FileOutputStream(save);
fos.write(itsSerializer.getUsedVersion());
fos.write(itsSerializer.serialize(backpack.getBackpack()));
fos.write(itsSerializer.getUsedSerializer());
fos.write(itsSerializer.serialize(backpack.getInventory()));
fos.flush();
fos.close();
}
@ -121,7 +122,8 @@ public void saveBackpack(Backpack backpack)
e.printStackTrace();
}
}
@Override
public Backpack loadBackpack(OfflinePlayer player)
{
File save = new File(saveFolder, getFileName(player));

View File

@ -23,13 +23,13 @@
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import at.pcgamingfreaks.UUIDConverter;
import at.pcgamingfreaks.georgh.MinePacks.Backpack;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import at.pcgamingfreaks.georgh.MinePacks.MinePacks;
import org.bukkit.inventory.ItemStack;
public class MySQL extends SQL
{
@ -37,104 +37,20 @@ public MySQL(MinePacks mp)
{
super(mp); // Load Settings
BuildQuerys(); // Build Querys
CheckDB(); // Check Database
if(UseUUIDs && UpdatePlayer)
{
CheckUUIDs(); // Check if there are user accounts without UUID
}
// Fire DB request every 10 minutes to keep database connection alive
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable(){ @Override public void run() { try { GetConnection().createStatement().execute("SELECT 1"); }
catch(Exception e) { } }}, 600*20, 600*20);
if(maxAge > 0)
{
try
{
GetConnection().createStatement().execute("DELETE FROM `" + Table_Backpacks + "` WHERE `" + Field_BPLastUpdate + "` + INTERVAL " + maxAge + " day < NOW()");
}
catch (SQLException e)
{
e.printStackTrace();
}
}
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable(){ @Override public void run() { try { getConnection().createStatement().execute("SELECT 1"); }
catch(Exception ignored) {} }}, 600*20, 600*20);
}
protected void CheckUUIDs()
@Override
protected void updateQuerysForDialect()
{
try
{
List<String> converter = new ArrayList<String>();
Statement stmt = GetConnection().createStatement();
ResultSet res = stmt.executeQuery("SELECT `" + Field_PlayerID + "`,`" + Field_Name + "` FROM `" + Table_Players + "` WHERE `" + Field_UUID + "` IS NULL");
while(res.next())
{
if(res.isFirst())
{
plugin.log.info(plugin.lang.get("Console.UpdateUUIDs"));
}
converter.add("UPDATE `" + Table_Players + "` SET `" + Field_UUID + "`='" + UUIDConverter.getUUIDFromName(res.getString(2), true, UseUUIDSeparators) + "' WHERE `" + Field_PlayerID + "`='" + res.getInt(1) + "'");
}
if(converter.size() > 0)
{
for (String string : converter)
{
stmt.execute(string);
}
plugin.log.info(String.format(plugin.lang.get("Console.UpdatedUUIDs"), converter.size()));
}
res.close();
res = null;
if(UseUUIDSeparators)
{
res = stmt.executeQuery("SELECT `" + Field_PlayerID + "`,`" + Field_UUID + "` FROM `" + Table_Players + "` WHERE `" + Field_UUID + "` NOT LIKE '%-%'");
while(res.next())
{
if(res.isFirst())
{
plugin.log.info(plugin.lang.get("Console.UpdateUUIDs"));
}
converter.add("UPDATE `" + Table_Players + "` SET `" + Field_UUID + "`='" + res.getString(2).replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5") + "' WHERE `" + Field_PlayerID + "`='" + res.getInt(1) + "'");
}
if(converter.size() > 0)
{
for (String string : converter)
{
stmt.execute(string);
}
plugin.log.info(String.format(plugin.lang.get("Console.UpdatedUUIDs"), converter.size()));
}
}
else
{
res = stmt.executeQuery("SELECT `" + Field_PlayerID + "`,`" + Field_UUID + "` FROM `" + Table_Players + "` WHERE `" + Field_UUID + "` LIKE '%-%'");
while(res.next())
{
if(res.isFirst())
{
plugin.log.info(plugin.lang.get("Console.UpdateUUIDs"));
}
converter.add("UPDATE `" + Table_Players + "` SET `" + Field_UUID + "`='" + res.getString(2).replaceAll("-", "") + "' WHERE `" + Field_PlayerID + "`='" + res.getInt(1) + "'");
}
if(converter.size() > 0)
{
for (String string : converter)
{
stmt.execute(string);
}
plugin.log.info(String.format(plugin.lang.get("Console.UpdatedUUIDs"), converter.size()));
}
}
res.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
Query_DeleteOldBackpacks = "DELETE FROM `{TableBackpacks}` WHERE `{FieldBPLastUpdate}` + INTERVAL {VarMaxAge} day < NOW()";
Query_UpdateBP = Query_UpdateBP.replaceAll("\\{NOW\\}", "NOW()");
}
protected Connection GetConnection()
@Override
protected Connection getConnection()
{
try
{
@ -149,30 +65,59 @@ protected Connection GetConnection()
}
return conn;
}
protected void CheckDB()
protected Connection getNewConnection()
{
try
{
Statement stmt = GetConnection().createStatement();
return DriverManager.getConnection("jdbc:mysql://" + plugin.config.getMySQLHost() + "/" + plugin.config.getMySQLDatabase() + "?autoReconnect=true&timeBetweenEvictionRunsMillis=300000&testWhileIdle=true", plugin.config.getMySQLUser(), plugin.config.getMySQLPassword());
}
catch (SQLException e)
{
e.printStackTrace();
}
return null;
}
@Override
protected void checkDB()
{
try
{
Statement stmt = getConnection().createStatement();
ResultSet res;
stmt.execute("CREATE TABLE IF NOT EXISTS `" + Table_Players + "` (`" + Field_PlayerID + "` INT UNSIGNED NOT NULL AUTO_INCREMENT,`" + Field_Name + "` CHAR(16) NOT NULL UNIQUE"
+ ((UseUUIDs) ? ",`" + Field_UUID + "` CHAR(36) UNIQUE" : "") + ", PRIMARY KEY (`" + Field_PlayerID + "`));");
if(UseUUIDs)
if(useUUIDs)
{
stmt.execute("CREATE TABLE IF NOT EXISTS `" + Table_Players + "` (`" + Field_PlayerID + "` INT UNSIGNED NOT NULL AUTO_INCREMENT,`" + Field_Name + "` CHAR(16) NOT NULL,`" + Field_UUID + "` CHAR(36) UNIQUE, PRIMARY KEY (`" + Field_PlayerID + "`));");
res = stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + Table_Players + "' AND COLUMN_NAME = '" + Field_UUID + "';");
if(!res.next())
{
stmt.execute("ALTER TABLE `" + Table_Players + "` ADD COLUMN `" + Field_UUID + "` CHAR(36) UNIQUE;");
}
res.close();
}
if(UseUUIDSeparators)
{
res = stmt.executeQuery("SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + Table_Players + "' AND COLUMN_NAME = '" + Field_UUID + "';");
if(res.next() && res.getInt(1) < 36)
res = stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + Table_Players + "' AND COLUMN_NAME = '" + Field_Name + "' AND COLUMN_KEY='UNI';");
if(res.next())
{
stmt.execute("ALTER TABLE `" + Table_Players + "` ADD MODIFY `" + Field_UUID + "` CHAR(36) UNIQUE;");
stmt.execute("ALTER TABLE `" + Table_Players + "` DROP INDEX `" + Field_Name + "_UNIQUE`;");
}
res.close();
if(useUUIDSeparators)
{
res = stmt.executeQuery("SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + Table_Players + "' AND COLUMN_NAME = '" + Field_UUID + "';");
if(res.next() && res.getInt(1) < 36)
{
stmt.execute("ALTER TABLE `" + Table_Players + "` MODIFY `" + Field_UUID + "` CHAR(36) UNIQUE;");
}
res.close();
}
}
else
{
stmt.execute("CREATE TABLE IF NOT EXISTS `" + Table_Players + "` (`" + Field_PlayerID + "` INT UNSIGNED NOT NULL AUTO_INCREMENT,`" + Field_Name + "` CHAR(16) NOT NULL, PRIMARY KEY (`" + Field_PlayerID + "`));");
res = stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + Table_Players + "' AND COLUMN_NAME = '" + Field_Name + "' AND COLUMN_KEY='UNI';");
if(!res.next())
{
stmt.execute("ALTER TABLE `" + Table_Players + "` ADD UNIQUE INDEX `" + Field_Name + "_UNIQUE` (`" + Field_Name + "` ASC);");
}
res.close();
}
@ -200,13 +145,8 @@ protected void CheckDB()
}
}
protected void AddDateFieldToQuery()
{
Query_InsertBP = ") VALUES (";
Query_UpdateBP = ",`" + Field_BPLastUpdate + "`=NOW()";
}
// Plugin Functions
@Override
public void updatePlayer(final Player player)
{
if(!UpdatePlayer)
@ -217,61 +157,144 @@ public void updatePlayer(final Player player)
{
@Override
public void run()
{
{
try
{
PreparedStatement ps;
Connection con = DriverManager.getConnection("jdbc:mysql://" + plugin.config.getMySQLHost() + "/" + plugin.config.getMySQLDatabase(), plugin.config.getMySQLUser(), plugin.config.getMySQLPassword());;
ps = con.prepareStatement(Query_UpdatePlayerGet);
ps.setString(1, getPlayerNameOrUUID(player));
ResultSet rs = ps.executeQuery();
if(rs.next())
Connection con = getNewConnection();
PreparedStatement ps = con.prepareStatement(Query_UpdatePlayerAdd);
ps.setString(1, player.getName());
if(useUUIDs)
{
rs.close();
ps.close();
if(!UseUUIDs)
{
con.close();
return;
}
ps = con.prepareStatement(Query_UpdatePlayerUUID);
ps.setString(1, player.getName());
if(UseUUIDSeparators)
{
ps.setString(2, player.getUniqueId().toString());
}
else
{
ps.setString(2, player.getUniqueId().toString().replace("-", ""));
}
}
else
{
rs.close();
ps.close();
ps = con.prepareStatement(Query_UpdatePlayerAdd);
ps.setString(1, player.getName());
if(UseUUIDs)
{
if(UseUUIDSeparators)
{
ps.setString(2, player.getUniqueId().toString());
}
else
{
ps.setString(2, player.getUniqueId().toString().replace("-", ""));
}
}
String uuid = getPlayerFormattedUUID(player);
ps.setString(2, uuid);
ps.setString(3, player.getName());
}
ps.execute();
ps.close();
con.close();
}
catch (SQLException e)
{
plugin.log.info("Failed to add user: " + player.getName());
e.printStackTrace();
}
}});
catch(SQLException e)
{
plugin.log.info("Failed to add/update user: " + player.getName());
e.printStackTrace();
}
}
});
}
@Override
protected void loadBackpack(final OfflinePlayer player, final Callback<Backpack> callback)
{
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run()
{
try
{
Connection conn = getNewConnection();
PreparedStatement ps = getConnection().prepareStatement(Query_GetBP);
ps.setString(1, getPlayerNameOrUUID(player));
ResultSet rs = ps.executeQuery();
final int bpID, version;
final byte[] data;
if(rs.next())
{
bpID = rs.getInt(1);
version = rs.getInt(3);
data = rs.getBytes(2);
}
else
{
bpID = -1;
version = 0;
data = null;
}
plugin.getServer().getScheduler().runTask(plugin, new Runnable()
{
@Override
public void run()
{
ItemStack[] its = (data != null) ? itsSerializer.deserialize(data, version) : null;
callback.onResult((its != null) ? new Backpack(player, its, bpID) : null);
}
});
rs.close();
ps.close();
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
}
@Override
public void saveBackpack(final Backpack backpack)
{
final byte[] data = itsSerializer.serialize(backpack.getInventory());
final int id = backpack.getOwnerID();
final String nameOrUUID = getPlayerNameOrUUID(backpack.getOwner()), name = backpack.getOwner().getName();
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run()
{
try
{
Connection conn = getNewConnection();
PreparedStatement ps; // Statement Variable
// Building the mysql statement
if(id <= 0)
{
final int newID;
ps = conn.prepareStatement(Query_GetPlayerID);
ps.setString(1, nameOrUUID);
ResultSet rs = ps.executeQuery();
if(rs.next())
{
newID = rs.getInt(1);
plugin.getServer().getScheduler().runTask(plugin, new Runnable() {
@Override
public void run()
{
backpack.setOwnerID(newID);
}
});
}
else
{
newID = -1;
}
rs.close();
ps.close();
if(newID <= 0)
{
plugin.log.warning("Failed saving backpack for: " + name + " (Unable to get players ID from database)");
conn.close();
return;
}
ps = conn.prepareStatement(Query_InsertBP);
ps.setInt(1, newID);
ps.setBytes(2, data);
ps.setInt(3, itsSerializer.getUsedSerializer());
}
else
{
ps = conn.prepareStatement(Query_UpdateBP);
ps.setBytes(1, data);
ps.setInt(2, itsSerializer.getUsedSerializer());
ps.setInt(3, id);
}
ps.execute();
ps.close();
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
}
}

View File

@ -17,11 +17,11 @@
package at.pcgamingfreaks.georgh.MinePacks.Database;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import at.pcgamingfreaks.UUIDConverter;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
@ -29,19 +29,44 @@
import at.pcgamingfreaks.georgh.MinePacks.Backpack;
import at.pcgamingfreaks.georgh.MinePacks.MinePacks;
public class SQL extends Database
public abstract class SQL extends Database
{
protected Connection conn = null;
protected String Table_Players, Table_Backpacks; // Table Names
protected String Field_Name, Field_PlayerID, Field_UUID, Field_BPOwner, Field_BPITS, Field_BPVersion, Field_BPLastUpdate; // Table Fields
protected String Query_UpdatePlayerGet, Query_UpdatePlayerUUID, Query_UpdatePlayerAdd, Query_GetPlayerID, Query_InsertBP, Query_UpdateBP, Query_GetBP; // DB Querys
protected String Query_UpdatePlayerAdd, Query_GetPlayerID, Query_InsertBP, Query_UpdateBP, Query_GetBP, Query_DeleteOldBackpacks, Query_GetUnsetOrInvalidUUIDs, Query_FixUUIDs; // DB Querys
protected boolean UpdatePlayer;
public SQL(MinePacks mp)
{
super(mp);
// Load Settings
loadSettings();
buildQuerys();
checkDB();
if(useUUIDs && UpdatePlayer)
{
checkUUIDs(); // Check if there are user accounts without UUID
}
// Delete old backpacks
if(maxAge > 0)
{
try
{
getConnection().createStatement().execute(Query_DeleteOldBackpacks);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
protected void loadSettings()
{
// Load table and field names
Table_Players = plugin.config.getUserTable();
Table_Backpacks = plugin.config.getBackpackTable();
Field_PlayerID = plugin.config.getDBFields("User.Player_ID");
@ -60,129 +85,181 @@ public void close()
{
conn.close();
}
catch(Exception e) { }
catch(Exception ignored) { }
}
protected void BuildQuerys()
protected void checkUUIDs()
{
if(UseUUIDs)
class UpdateData // Helper class for fixing UUIDs
{
Query_UpdatePlayerGet = "SELECT `" + Field_PlayerID + "` FROM `" + Table_Players + "` WHERE `" + Field_UUID + "`=?;";
Query_UpdatePlayerUUID = "UPDATE `" + Table_Players + "` SET `" + Field_Name + "`=? WHERE `" + Field_UUID + "`=?;";
Query_UpdatePlayerAdd = "INSERT INTO `" + Table_Players + "` (`" + Field_Name + "`,`" + Field_UUID + "`) VALUES (?,?);";
Query_GetPlayerID = "SELECT `" + Field_PlayerID + "` FROM `" + Table_Players + "` WHERE `" + Field_UUID + "`=?;";
Query_GetBP = "SELECT `" + Field_BPOwner + "`,`" + Field_BPITS + "`,`" + Field_BPVersion + "` FROM `" + Table_Backpacks + "` INNER JOIN `" + Table_Players + "` ON `" + Table_Backpacks + "`.`" + Field_BPOwner + "`=`" + Table_Players + "`.`" + Field_PlayerID + "` WHERE `" + Field_UUID + "`=?;";
int id;
String name, uuid;
public UpdateData(String name, String uuid, int id) { this.id = id; this.name = name; this.uuid = uuid; }
}
try
{
List<UpdateData> converter = new ArrayList<>();
PreparedStatement ps = getConnection().prepareStatement(Query_FixUUIDs);
ResultSet res = getConnection().createStatement().executeQuery(Query_GetUnsetOrInvalidUUIDs);
while(res.next())
{
if(res.isFirst())
{
plugin.log.info(plugin.lang.get("Console.UpdateUUIDs"));
}
converter.add(new UpdateData(res.getString(2), res.getString(3), res.getInt(1)));
}
res.close();
if(converter.size() > 0)
{
for (UpdateData data : converter)
{
if(data.uuid == null)
{
ps.setString(1, UUIDConverter.getUUIDFromName(data.name, true, useUUIDSeparators, false));
}
else
{
ps.setString(1, (useUUIDSeparators) ? data.uuid.replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5") : data.uuid.replaceAll("-", ""));
}
ps.setInt(2, data.id);
}
plugin.log.info(String.format(plugin.lang.get("Console.UpdatedUUIDs"), converter.size()));
}
ps.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
protected abstract Connection getConnection();
protected abstract void checkDB();
protected final void buildQuerys()
{
// Build the SQL querys with placeholders for the table and field names
Query_GetBP = "SELECT `{FieldBPOwner}`,`{FieldBPITS}`,`{FieldBPVersion}` FROM `{TableBackpacks}` INNER JOIN `{TablePlayers}` ON `{TableBackpacks}`.`{FieldBPOwner}`=`{TablePlayers}`.`{FieldPlayerID}` WHERE ";
if(useUUIDs)
{
Query_UpdatePlayerAdd = "INSERT INTO `{TablePlayers}` (`{FieldName}`,`{FieldUUID}`) VALUES (?,?) ON DUPLICATE KEY UPDATE `{FieldName}`=?;";
Query_GetPlayerID = "SELECT `{FieldPlayerID}` FROM `{TablePlayers}` WHERE `{FieldUUID}`=?;";
Query_GetBP += "`{FieldUUID}`=?;";
}
else
{
Query_UpdatePlayerGet = "SELECT `" + Field_PlayerID + "` FROM `" + Table_Players + "` WHERE `" + Field_Name + "`=?;";
Query_UpdatePlayerAdd = "INSERT INTO `" + Table_Players + "` (`" + Field_Name + "`) VALUES (?);";
Query_GetPlayerID = "SELECT `" + Field_PlayerID + "` FROM `" + Table_Players + "` WHERE `" + Field_Name + "`=?;";
Query_GetBP = "SELECT `" + Field_BPOwner + "`,`" + Field_BPITS + "`,`" + Field_BPVersion + "` FROM `" + Table_Backpacks + "` INNER JOIN `" + Table_Players + "` ON `" + Table_Backpacks + "`.`" + Field_BPOwner + "`=`" + Table_Players + "`.`" + Field_PlayerID + "` WHERE `" + Field_Name + "`=?;";
Query_UpdatePlayerAdd = "INSERT IGNORE INTO `{TablePlayers}` (`{FieldName}`) VALUES (?);";
Query_GetPlayerID = "SELECT `{FieldPlayerID}` FROM `{TablePlayers}` WHERE `{FieldName}`=?;";
Query_GetBP += "`{FieldName}`=?;";
}
Query_InsertBP = "INSERT INTO `" + Table_Backpacks + "` (`" + Field_BPOwner + "`, `" + Field_BPITS + "`, `" + Field_BPVersion + "`";
Query_UpdateBP = "UPDATE `" + Table_Backpacks + "` SET `" + Field_BPITS + "`=?,`" + Field_BPVersion + "`=?";
if(maxAge < 1)
Query_InsertBP = "INSERT INTO `{TableBackpacks}` (`{FieldBPOwner}`,`{FieldBPITS}`,`{FieldBPVersion}`) VALUES (?,?,?);";
Query_UpdateBP = "UPDATE `{TableBackpacks}` SET `{FieldBPITS}`=?,`{FieldBPVersion}`=?";
if(maxAge > 0)
{
Query_InsertBP += ") VALUES (";
Query_UpdateBP += ",`{FieldBPLastUpdate}`={NOW}";
}
Query_UpdateBP += " WHERE `{FieldBPOwner}`=?;";
Query_DeleteOldBackpacks = "DELETE FROM `{TableBackpacks}` WHERE `{FieldBPLastUpdate}` < DATE('now', '-{VarMaxAge} days')";
if(useUUIDSeparators)
{
Query_GetUnsetOrInvalidUUIDs = "SELECT `{FieldPlayerID}`,`{FieldName}`,`{FieldUUID}` FROM `{TablePlayers}` WHERE `{FieldUUID}` IS NULL OR `{FieldUUID}` NOT LIKE '%-%-%-%-%';";
}
else
{
AddDateFieldToQuery();
Query_GetUnsetOrInvalidUUIDs = "SELECT `{FieldPlayerID}`,`{FieldName}`,`{FieldUUID}` FROM `{TablePlayers}` WHERE `{FieldUUID}` IS NULL OR `{FieldUUID}` LIKE '%-%';";
}
Query_InsertBP += "?,?,?);";
Query_UpdateBP += " WHERE `" + Field_BPOwner + "`=?;";
Query_FixUUIDs = "UPDATE `{TablePlayers}` SET `{FieldUUID}`=? WHERE `{FieldPlayerID}`=?;";
updateQuerysForDialect();
// Replace the table and filed names with the names from the config
Query_UpdatePlayerAdd = Query_UpdatePlayerAdd.replaceAll("\\{TablePlayers\\}", Table_Players).replaceAll("\\{FieldName\\}", Field_Name).replaceAll("\\{FieldUUID\\}", Field_UUID).replaceAll("\\{FieldPlayerID\\}", Field_PlayerID);
Query_GetPlayerID = Query_GetPlayerID.replaceAll("\\{TablePlayers\\}", Table_Players).replaceAll("\\{FieldName\\}", Field_Name).replaceAll("\\{FieldUUID\\}", Field_UUID).replaceAll("\\{FieldPlayerID\\}", Field_PlayerID);
Query_GetBP = Query_GetBP.replaceAll("\\{FieldBPOwner\\}", Field_BPOwner).replaceAll("\\{FieldBPITS\\}",Field_BPITS).replaceAll("\\{FieldBPVersion\\}", Field_BPVersion).replaceAll("\\{TableBackpacks\\}", Table_Backpacks).replaceAll("\\{TablePlayers\\}", Table_Players).replaceAll("\\{FieldPlayerID\\}", Field_PlayerID).replaceAll("\\{FieldName\\}", Field_Name).replaceAll("\\{FieldUUID\\}", Field_UUID);
Query_InsertBP = Query_InsertBP.replaceAll("\\{TableBackpacks\\}", Table_Backpacks).replaceAll("\\{FieldBPOwner\\}", Field_BPOwner).replaceAll("\\{FieldBPITS\\}",Field_BPITS).replaceAll("\\{FieldBPVersion\\}", Field_BPVersion).replaceAll("\\{FieldBPLastUpdate\\}", Field_BPLastUpdate);
Query_UpdateBP = Query_UpdateBP.replaceAll("\\{TableBackpacks\\}", Table_Backpacks).replaceAll("\\{FieldBPOwner\\}", Field_BPOwner).replaceAll("\\{FieldBPITS\\}",Field_BPITS).replaceAll("\\{FieldBPVersion\\}", Field_BPVersion).replaceAll("\\{FieldBPLastUpdate\\}", Field_BPLastUpdate);
Query_DeleteOldBackpacks = Query_DeleteOldBackpacks.replaceAll("\\{TableBackpacks\\}", Table_Backpacks).replaceAll("\\{FieldBPLastUpdate\\}", Field_BPLastUpdate).replaceAll("\\{VarMaxAge\\}", maxAge + "");
Query_GetUnsetOrInvalidUUIDs = Query_GetUnsetOrInvalidUUIDs.replaceAll("\\{TablePlayers\\}", Table_Players).replaceAll("\\{FieldName\\}", Field_Name).replaceAll("\\{FieldUUID\\}", Field_UUID).replaceAll("\\{FieldPlayerID\\}", Field_PlayerID);
Query_FixUUIDs = Query_FixUUIDs.replaceAll("\\{TablePlayers\\}", Table_Players).replaceAll("\\{FieldUUID\\}", Field_UUID).replaceAll("\\{FieldPlayerID\\}", Field_PlayerID);
}
protected void AddDateFieldToQuery() // Will be overwriten by the used DB System
{
Query_InsertBP = ", `" + Field_BPLastUpdate + "`) VALUES (?,";
Query_UpdateBP = ",`" + Field_BPLastUpdate + "`=?";
}
protected void CheckUUIDs() { }
protected Connection GetConnection() { return null; }
protected void CheckDB() { }
protected abstract void updateQuerysForDialect();
// Plugin Functions
public void updatePlayer(final Player player)
{
try
{
PreparedStatement ps = GetConnection().prepareStatement(Query_UpdatePlayerGet);
ps.setString(1, getPlayerNameOrUUID(player));
ResultSet rs = ps.executeQuery();
if(rs.next())
PreparedStatement ps = getConnection().prepareStatement(Query_UpdatePlayerAdd);
ps.setString(1, player.getName());
if(useUUIDs)
{
rs.close();
ps.close();
if(!UseUUIDs)
{
return;
}
ps = GetConnection().prepareStatement(Query_UpdatePlayerUUID);
ps.setString(1, player.getName());
ps.setString(2, player.getUniqueId().toString().replace("-", ""));
}
else
{
rs.close();
ps.close();
ps = GetConnection().prepareStatement(Query_UpdatePlayerAdd);
ps.setString(1, player.getName());
if(UseUUIDs)
{
ps.setString(2, player.getUniqueId().toString().replace("-", ""));
}
String uuid = getPlayerFormattedUUID(player);
ps.setString(2, uuid);
ps.setString(3, player.getName());
}
ps.execute();
ps.close();
}
catch (SQLException e)
{
plugin.log.info("Failed to add user: " + player.getName());
plugin.log.info("Failed to add/update user: " + player.getName());
e.printStackTrace();
}
}
public int getPlayerID(OfflinePlayer player)
{
int id = -1;
try
{
PreparedStatement ps = getConnection().prepareStatement(Query_GetPlayerID);
ps.setString(1, getPlayerNameOrUUID(player));
ResultSet rs = ps.executeQuery();
if(rs.next())
{
id = rs.getInt(1);
}
rs.close();
ps.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return id;
}
public void saveBackpack(Backpack backpack)
{
try
{
PreparedStatement ps = null; // Statement Variable
PreparedStatement ps; // Statement Variable
// Building the mysql statement
if(backpack.getID() <= 0)
if(backpack.getOwnerID() <= 0)
{
ps = GetConnection().prepareStatement(Query_GetPlayerID);
ps.setString(1, getPlayerNameOrUUID(backpack.getOwner()));
ResultSet rs = ps.executeQuery();
if(rs.next())
{
backpack.setID(rs.getInt(1));
}
else
{
plugin.log.warning("Faild saving backpack for: " + backpack.getOwner().getName() + " (Unable to get players ID)");
return;
}
rs.close();
ps.close();
ps = GetConnection().prepareStatement(Query_InsertBP);
ps.setInt(1, backpack.getID());
ps.setBytes(2, itsSerializer.serialize(backpack.getBackpack()));
ps.setInt(3, itsSerializer.getUsedVersion());
backpack.setOwnerID(getPlayerID(backpack.getOwner()));
if(backpack.getOwnerID() <= 0)
{
plugin.log.warning("Failed saving backpack for: " + backpack.getOwner().getName() + " (Unable to get players ID from database)");
return;
}
ps = getConnection().prepareStatement(Query_InsertBP);
ps.setInt(1, backpack.getOwnerID());
ps.setBytes(2, itsSerializer.serialize(backpack.getInventory()));
ps.setInt(3, itsSerializer.getUsedSerializer());
ps.execute();
ps.close();
return;
}
else
{
ps = GetConnection().prepareStatement(Query_UpdateBP);
ps.setBytes(1, itsSerializer.serialize(backpack.getBackpack()));
ps.setInt(2, itsSerializer.getUsedVersion());
ps.setInt(3, backpack.getID());
ps = getConnection().prepareStatement(Query_UpdateBP);
ps.setBytes(1, itsSerializer.serialize(backpack.getInventory()));
ps.setInt(2, itsSerializer.getUsedSerializer());
ps.setInt(3, backpack.getOwnerID());
}
ps.execute();
ps.close();
@ -197,19 +274,18 @@ public Backpack loadBackpack(OfflinePlayer player)
{
try
{
PreparedStatement ps = null; // Statement Variable
ps = GetConnection().prepareStatement(Query_GetBP);
PreparedStatement ps = getConnection().prepareStatement(Query_GetBP);
ps.setString(1, getPlayerNameOrUUID(player));
ResultSet rs = ps.executeQuery();
if(!rs.next())
{
return null;
}
int bpid = rs.getInt(1);
int bpID = rs.getInt(1);
ItemStack[] its = itsSerializer.deserialize(rs.getBytes(2), rs.getInt(3));
rs.close();
ps.close();
return new Backpack(player, its, bpid);
return new Backpack(player, its, bpID);
}
catch(Exception e)
{

View File

@ -23,18 +23,20 @@
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import at.pcgamingfreaks.UUIDConverter;
import at.pcgamingfreaks.georgh.MinePacks.MinePacks;
public class SQLite extends SQL
{
public SQLite(MinePacks mp)
{
super(mp); // Load Settings
super(mp);
}
@Override
protected void loadSettings()
{
// Set table and field names to fixed values to prevent users from destroying old databases.
Field_PlayerID = "player_id";
Field_Name = "name";
Field_UUID = "uuid";
@ -44,83 +46,70 @@ public SQLite(MinePacks mp)
Field_BPLastUpdate = "lastupdate";
Table_Players = "backpack_players";
Table_Backpacks = "backpacks";
UseUUIDSeparators = false;
// Set fixed settings
useUUIDSeparators = false;
UpdatePlayer = true;
BuildQuerys(); // Build Query's
CheckDB(); // Check Database
if(UseUUIDs && UpdatePlayer)
{
CheckUUIDs(); // Check if there are user accounts without UUID
}
}
@Override
protected void updateQuerysForDialect()
{
if(maxAge > 0)
{
try
{
GetConnection().createStatement().execute("DELETE FROM `" + Table_Backpacks + "` WHERE `" + Field_BPLastUpdate + "` < DATE('now', '-" + maxAge + " days')");
}
catch (SQLException e)
{
e.printStackTrace();
}
Query_InsertBP = Query_InsertBP.replaceAll("\\) VALUES \\(\\?,\\?,\\?", "{FieldBPLastUpdate}) VALUES (?,?,?,DATE('now')");
}
Query_DeleteOldBackpacks = "DELETE FROM `{TableBackpacks}` WHERE `{FieldBPLastUpdate}` < DATE('now', '-{VarMaxAge} days')";
Query_UpdateBP = Query_UpdateBP.replaceAll("\\{NOW\\}", "DATE('now')");
}
protected Connection GetConnection()
@Override
protected Connection getConnection()
{
try
{
if(conn == null || conn.isClosed())
{
try
{
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + plugin.getDataFolder().getAbsolutePath() + File.separator + "backpack.db");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
Class.forName("org.sqlite.JDBC"); // Throws an exception if the SQLite driver is not found.
conn = DriverManager.getConnection("jdbc:sqlite:" + plugin.getDataFolder().getAbsolutePath() + File.separator + "backpack.db");
}
}
catch (SQLException e)
catch (ClassNotFoundException | SQLException e)
{
e.printStackTrace();
}
return conn;
}
protected void CheckDB()
@Override
protected void checkDB()
{
try
{
Statement stmt = GetConnection().createStatement();
stmt.execute("CREATE TABLE IF NOT EXISTS `" + Table_Players + "` (`player_id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` CHAR(16) NOT NULL UNIQUE" + ((UseUUIDs) ? ", `uuid` CHAR(32) UNIQUE" : "") +");");
if(UseUUIDs)
Statement stmt = getConnection().createStatement();
stmt.execute("CREATE TABLE IF NOT EXISTS `backpack_players` (`player_id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` CHAR(16) NOT NULL UNIQUE" + ((useUUIDs) ? ", `uuid` CHAR(32) UNIQUE" : "") +");");
if(useUUIDs)
{
try
{
stmt.execute("ALTER TABLE `" + Table_Players + "` ADD COLUMN `uuid` CHAR(32);");
stmt.execute("ALTER TABLE `backpack_players` ADD COLUMN `uuid` CHAR(32);");
}
catch(SQLException e) { }
catch(SQLException ignored) {}
}
stmt.execute("CREATE TABLE IF NOT EXISTS `" + Table_Backpacks + "` (`owner` INT UNSIGNED PRIMARY KEY, `itemstacks` BLOB, `version` INT DEFAULT 0);");
stmt.execute("CREATE TABLE IF NOT EXISTS `backpacks` (`owner` INT UNSIGNED PRIMARY KEY, `itemstacks` BLOB, `version` INT DEFAULT 0);");
try
{
stmt.execute("ALTER TABLE `" + Table_Backpacks + "` ADD COLUMN `version` INT DEFAULT 0;");
stmt.execute("ALTER TABLE `backpacks` ADD COLUMN `version` INT DEFAULT 0;");
}
catch(SQLException e) { }
catch(SQLException ignored) {}
if(maxAge > 0)
{
try
{
ResultSet rs = stmt.executeQuery("SELECT DATE('now');");
rs.next();
stmt.execute("ALTER TABLE `" + Table_Backpacks + "` ADD COLUMN `lastupdate` DATE DEFAULT '" + rs.getString(1) + "';");
stmt.execute("ALTER TABLE `backpacks` ADD COLUMN `lastupdate` DATE DEFAULT '" + rs.getString(1) + "';");
}
catch(SQLException e) { }
catch(SQLException ignored) {}
}
stmt.close();
}
@ -129,40 +118,4 @@ protected void CheckDB()
e.printStackTrace();
}
}
protected void CheckUUIDs()
{
try
{
List<String> converter = new ArrayList<String>();
Statement stmt = GetConnection().createStatement();
ResultSet res = stmt.executeQuery("SELECT `name` FROM `" + Table_Players + "` WHERE `uuid` IS NULL");
while(res.next())
{
if(res.isFirst())
{
plugin.log.info(plugin.lang.get("Console.UpdateUUIDs"));
}
converter.add("UPDATE `" + Table_Players + "` SET `uuid`='" + UUIDConverter.getUUIDFromName(res.getString(1), plugin.getServer().getOnlineMode()) + "' WHERE `name`='" + res.getString(1).replace("\\", "\\\\").replace("'", "\\'") + "'");
}
if(converter.size() > 0)
{
for (String string : converter)
{
stmt.execute(string);
}
plugin.log.info(String.format(plugin.lang.get("Console.UpdatedUUIDs"),converter.size()));
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
protected void AddDateFieldToQuery()
{
Query_InsertBP = ") VALUES (";
Query_UpdateBP = ",`" + Field_BPLastUpdate + "`=DATE('now')";
}
}

View File

@ -17,6 +17,7 @@
package at.pcgamingfreaks.georgh.MinePacks;
import at.pcgamingfreaks.georgh.MinePacks.Database.Database;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
@ -48,35 +49,42 @@ public EventListener(MinePacks mp)
@EventHandler
public void onDeath(PlayerDeathEvent event)
{
Player player = event.getEntity();
final Player player = event.getEntity();
if (drop_on_death && !player.hasPermission("backpack.KeepOnDeath"))
{
Backpack backpack = plugin.DB.getBackpack(player, false);
Inventory backpackInventory = backpack.getBackpack();
for (ItemStack i : backpackInventory.getContents())
plugin.DB.getBackpack(player, new Database.Callback<Backpack>()
{
if (i != null)
{
player.getWorld().dropItemNaturally(player.getLocation(), i);
backpackInventory.remove(i);
}
}
plugin.DB.saveBackpack(backpack);
@Override
public void onResult(Backpack backpack)
{
Inventory backpackInventory = backpack.getInventory();
for(ItemStack i : backpackInventory.getContents())
{
if(i != null)
{
player.getWorld().dropItemNaturally(player.getLocation(), i);
backpackInventory.remove(i);
backpack.setChanged();
}
}
backpack.save(); // We have to save it now!
}
});
}
}
@EventHandler
public void onClose(InventoryCloseEvent event)
{
if (event.getInventory() != null && event.getInventory().getTitle() != null && event.getPlayer() instanceof Player)
if (event.getInventory() != null && event.getInventory().getHolder() instanceof Backpack && event.getPlayer() instanceof Player)
{
Backpack backpack = plugin.DB.getBackpack(event.getInventory());
if(backpack != null && !backpack.inUse())
Backpack backpack = (Backpack)event.getInventory().getHolder();
if(!backpack.inUse())
{
Player closer = (Player)event.getPlayer();
if(backpack.canEdit(closer))
{
plugin.DB.saveBackpack(backpack);
backpack.save();
}
backpack.close(closer);
if(event.getPlayer().getName().equals(backpack.getOwner().getName()))
@ -100,29 +108,34 @@ public void onClose(InventoryCloseEvent event)
@EventHandler
public void onClick(InventoryClickEvent event)
{
if (event.getInventory() != null && event.getInventory().getTitle() != null && event.getWhoClicked() instanceof Player)
if (event.getInventory() != null && event.getInventory().getHolder() instanceof Backpack && event.getWhoClicked() instanceof Player)
{
Backpack backpack = plugin.DB.getBackpack(event.getInventory());
if(backpack != null && !backpack.canEdit((Player)event.getWhoClicked()))
Backpack backpack = (Backpack) event.getInventory().getHolder();
if(!backpack.canEdit((Player)event.getWhoClicked()))
{
event.setCancelled(true);
}
else
{
backpack.setChanged();
}
}
}
@EventHandler
public void PlayerLoginEvent(PlayerJoinEvent event)
public void onPlayerLoginEvent(PlayerJoinEvent event)
{
plugin.DB.updatePlayer(event.getPlayer());
plugin.DB.updatePlayerAndLoadBackpack(event.getPlayer());
}
@EventHandler
public void PlayerLeaveEvent(PlayerQuitEvent event)
public void onPlayerLeaveEvent(PlayerQuitEvent event)
{
Backpack bp = plugin.DB.getBackpack(event.getPlayer(), true);
if(bp != null && !bp.isOpen())
Backpack backpack = plugin.DB.getBackpack(event.getPlayer());
if(backpack != null && !backpack.isOpen())
{
plugin.DB.UnloadBackpack(bp);
backpack.save();
plugin.DB.unloadBackpack(backpack);
}
if(plugin.cooldowns.containsKey(event.getPlayer()))
{

View File

@ -43,9 +43,10 @@ public void run()
{
for(Player player : Bukkit.getServer().getOnlinePlayers())
{
if(player.getInventory().firstEmpty() == -1 && player.hasPermission("backpack.fullpickup"))
if(player.getInventory().firstEmpty() == -1 && player.hasPermission("backpack") && player.hasPermission("backpack.fullpickup"))
{
Backpack backpack = plugin.DB.getBackpack(player, false);
// Only check loaded backpacks (loading them would take to much time for a repeating task, the will be loaded async soon enough)
Backpack backpack = plugin.DB.getBackpack(player);
if(backpack == null)
{
continue;
@ -58,7 +59,8 @@ public void run()
Item item = (Item) entity;
if(!item.isDead() && item.getPickupDelay() <= 0)
{
HashMap<Integer, ItemStack> full = backpack.getBackpack().addItem(item.getItemStack());
HashMap<Integer, ItemStack> full = backpack.getInventory().addItem(item.getItemStack());
backpack.setChanged();
if(!full.isEmpty())
{
item.setItemStack(full.get(0));

View File

@ -32,6 +32,8 @@
public class MinePacks extends JavaPlugin
{
private static MinePacks instance = null;
public Logger log;
public Config config;
public Language lang;
@ -42,6 +44,11 @@ public class MinePacks extends JavaPlugin
public static String BackpackTitle;
public String Message_InvalidBackpack;
public static MinePacks getInstance()
{
return instance;
}
@Override
public void onEnable()
{
@ -49,6 +56,8 @@ public void onEnable()
config = new Config(this);
lang = new Language(this);
instance = this;
lang.load(config.getLanguage(), config.getLanguageUpdateMode());
DB = Database.getDatabase(this);
getCommand("backpack").setExecutor(new OnCommand(this));
@ -56,7 +65,7 @@ public void onEnable()
if(config.getFullInvCollect())
{
(new ItemsCollector(this)).runTaskTimerAsynchronously(this, config.getFullInvCheckInterval(), config.getFullInvCheckInterval());
(new ItemsCollector(this)).runTaskTimer(this, config.getFullInvCheckInterval(), config.getFullInvCheckInterval());
}
BackpackTitle = config.getBPTitle();
@ -77,12 +86,23 @@ public void onDisable()
log.info(lang.get("Console.Disabled"));
}
public void OpenBackpack(Player opener, OfflinePlayer owner, boolean editable)
public void openBackpack(final Player opener, OfflinePlayer owner, final boolean editable)
{
OpenBackpack(opener, DB.getBackpack(owner, false), editable);
if(owner == null)
{
return;
}
DB.getBackpack(owner, new Database.Callback<Backpack>()
{
@Override
public void onResult(Backpack backpack)
{
openBackpack(opener, backpack, editable);
}
});
}
public void OpenBackpack(Player opener, Backpack backpack, boolean editable)
public void openBackpack(Player opener, Backpack backpack, boolean editable)
{
if(backpack == null)
{

View File

@ -18,8 +18,8 @@
package at.pcgamingfreaks.georgh.MinePacks;
import java.util.Date;
import java.util.List;
import at.pcgamingfreaks.georgh.MinePacks.Database.Database;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
@ -27,7 +27,6 @@
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class OnCommand implements CommandExecutor
{
@ -51,7 +50,7 @@ public OnCommand(MinePacks mp)
@Override
public boolean onCommand(CommandSender sender, Command cmd, String arg, String[] args)
{
Player player;
final Player player;
if (sender instanceof Player)
{
player = (Player) sender;
@ -78,25 +77,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String arg, String[]
}
plugin.cooldowns.put(player, (new Date()).getTime());
}
Backpack bp = plugin.DB.getBackpack(player, false);
if(bp == null)
{
player.sendMessage(plugin.Message_InvalidBackpack);
return true;
}
int size = plugin.getBackpackPermSize(player);
if(size != bp.getSize())
{
List<ItemStack> items = bp.setSize(size);
for(ItemStack i : items)
{
if (i != null)
{
player.getWorld().dropItemNaturally(player.getLocation(), i);
}
}
}
plugin.OpenBackpack(player, bp, true);
plugin.openBackpack(player, player, true);
}
else
{
@ -138,15 +119,24 @@ public boolean onCommand(CommandSender sender, Command cmd, String arg, String[]
case "clear":
if(player.hasPermission("backpack.clean"))
{
OfflinePlayer OP = player;
if(player.hasPermission("backpack.clean.other") && args.length == 2)
final OfflinePlayer OP = (args.length == 2 && player.hasPermission("backpack.clean.other")) ? Bukkit.getOfflinePlayer(args[1]) : player;
plugin.DB.getBackpack(OP, new Database.Callback<Backpack>()
{
OP = Bukkit.getOfflinePlayer(args[1]);
}
Backpack BP = plugin.DB.getBackpack(OP, false);
BP.getBackpack().clear();
plugin.DB.saveBackpack(BP);
player.sendMessage(Message_BackpackCleaned);
@Override
public void onResult(Backpack backpack)
{
if(backpack != null)
{
backpack.getInventory().clear();
backpack.save();
player.sendMessage(Message_BackpackCleaned);
}
else
{
player.sendMessage(plugin.Message_InvalidBackpack);
}
}
});
}
else
{
@ -156,7 +146,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String arg, String[]
default: // Shows the backpack of an other player
if(player.hasPermission("backpack.others"))
{
plugin.OpenBackpack(player, Bukkit.getOfflinePlayer(args[0]), player.hasPermission("backpack.others.edit"));
plugin.openBackpack(player, Bukkit.getOfflinePlayer(args[0]), player.hasPermission("backpack.others.edit"));
}
else
{