From 7b6d7d59bdd77820059b69ae81febf8b24091368 Mon Sep 17 00:00:00 2001 From: Acrobot Date: Sat, 23 Jul 2011 21:00:47 +0200 Subject: [PATCH] - Long name (>15 chars) support - Added Bukkit Persistence Reimplemented by LennardF1989 - Made the plugin faster - Deleted unnecessary files (.jar size went down by 10 KB) - Added final and private keywords - Support for Bukkit's built-in permissions - Updated to newest Bukkit's standard (getFace -> getRelative) --- com/Acrobot/ChestShop/ChestShop.java | 103 +++-- .../ChestShop/Chests/MinecraftChest.java | 22 +- com/Acrobot/ChestShop/Commands/ItemInfo.java | 14 +- com/Acrobot/ChestShop/Commands/Options.java | 84 ----- com/Acrobot/ChestShop/Config/Config.java | 43 ++- com/Acrobot/ChestShop/Config/Language.java | 20 +- com/Acrobot/ChestShop/Config/Property.java | 5 +- com/Acrobot/ChestShop/DB/Generator.java | 69 ++-- com/Acrobot/ChestShop/DB/Queue.java | 2 +- com/Acrobot/ChestShop/Economy.java | 11 +- com/Acrobot/ChestShop/Items/DataValue.java | 6 +- com/Acrobot/ChestShop/Items/Items.java | 27 +- .../ChestShop/Listeners/blockBreak.java | 50 +-- .../ChestShop/Listeners/playerInteract.java | 54 +-- .../ChestShop/Listeners/pluginEnable.java | 3 +- .../ChestShop/Listeners/signChange.java | 20 +- .../ChestShop/Logging/FileWriterQueue.java | 5 +- com/Acrobot/ChestShop/Logging/Logging.java | 20 +- com/Acrobot/ChestShop/Messaging/Message.java | 12 - com/Acrobot/ChestShop/Options/Option.java | 41 -- com/Acrobot/ChestShop/Permission.java | 11 +- com/Acrobot/ChestShop/Protection/Default.java | 34 +- .../ChestShop/Protection/LockettePlugin.java | 3 +- .../ChestShop/Protection/MaskChest.java | 14 +- com/Acrobot/ChestShop/Shop/Shop.java | 84 ++--- .../ChestShop/Shop/ShopManagement.java | 18 +- .../restrictedSign.java} | 24 +- com/Acrobot/ChestShop/Utils/uBlock.java | 24 +- com/Acrobot/ChestShop/Utils/uInventory.java | 39 +- com/Acrobot/ChestShop/Utils/uLongName.java | 30 ++ com/Acrobot/ChestShop/Utils/uSign.java | 35 +- com/lennardf1989/bukkitex/Database.java | 357 ++++++++++++++++++ .../payment/forChestShop/Methods.java | 4 +- .../payment/forChestShop/methods/BOSE6.java | 8 +- .../payment/forChestShop/methods/BOSE7.java | 4 +- .../payment/forChestShop/methods/EE17.java | 2 +- .../payment/forChestShop/methods/iCo4.java | 8 +- .../payment/forChestShop/methods/iCo5.java | 16 +- plugin.yml | 39 +- 39 files changed, 779 insertions(+), 586 deletions(-) delete mode 100644 com/Acrobot/ChestShop/Commands/Options.java delete mode 100644 com/Acrobot/ChestShop/Messaging/Message.java delete mode 100644 com/Acrobot/ChestShop/Options/Option.java rename com/Acrobot/ChestShop/{Restrictions/RestrictedSign.java => Signs/restrictedSign.java} (61%) create mode 100644 com/Acrobot/ChestShop/Utils/uLongName.java create mode 100644 com/lennardf1989/bukkitex/Database.java diff --git a/com/Acrobot/ChestShop/ChestShop.java b/com/Acrobot/ChestShop/ChestShop.java index 6826d70..c8d3159 100644 --- a/com/Acrobot/ChestShop/ChestShop.java +++ b/com/Acrobot/ChestShop/ChestShop.java @@ -1,7 +1,6 @@ package com.Acrobot.ChestShop; import com.Acrobot.ChestShop.Commands.ItemInfo; -import com.Acrobot.ChestShop.Commands.Options; import com.Acrobot.ChestShop.Commands.Version; import com.Acrobot.ChestShop.Config.Config; import com.Acrobot.ChestShop.Config.Property; @@ -10,18 +9,18 @@ import com.Acrobot.ChestShop.DB.Queue; import com.Acrobot.ChestShop.DB.Transaction; import com.Acrobot.ChestShop.Listeners.*; import com.Acrobot.ChestShop.Logging.FileWriterQueue; -import com.Acrobot.ChestShop.Logging.Logging; import com.Acrobot.ChestShop.Protection.MaskChest; import com.avaje.ebean.EbeanServer; +import com.lennardf1989.bukkitex.Database; import org.bukkit.Server; import org.bukkit.event.Event; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.util.config.Configuration; -import javax.persistence.PersistenceException; import java.io.File; -import java.util.ArrayList; +import java.util.LinkedList; import java.util.List; /** @@ -31,50 +30,42 @@ import java.util.List; */ public class ChestShop extends JavaPlugin { - private final pluginEnable pluginEnable = new pluginEnable(); - private final blockBreak blockBreak = new blockBreak(); - private final blockPlace blockPlace = new blockPlace(); - private final signChange signChange = new signChange(); - private final pluginDisable pluginDisable = new pluginDisable(); - private final playerInteract playerInteract = new playerInteract(); + public static File folder = new File("plugins/ChestShop"); //In case Bukkit fails + private static EbeanServer DB; - public static File folder; - public static EbeanServer db; - - private static PluginDescriptionFile desc; + private static PluginDescriptionFile description; private static Server server; public void onEnable() { PluginManager pm = getServer().getPluginManager(); - //Register our events - pm.registerEvent(Event.Type.BLOCK_BREAK, blockBreak, Event.Priority.Normal, this); - pm.registerEvent(Event.Type.BLOCK_PLACE, blockPlace, Event.Priority.Normal, this); - pm.registerEvent(Event.Type.SIGN_CHANGE, signChange, Event.Priority.Normal, this); - pm.registerEvent(Event.Type.PLAYER_INTERACT, playerInteract, Event.Priority.Highest, this); - pm.registerEvent(Event.Type.PLUGIN_ENABLE, pluginEnable, Event.Priority.Monitor, this); - pm.registerEvent(Event.Type.PLUGIN_DISABLE, pluginDisable, Event.Priority.Monitor, this); - - desc = this.getDescription(); //Description of the plugin - server = getServer(); //Setting out server variable - //Yep, set up our folder! folder = getDataFolder(); //Set up our config file! Config.setUp(); + //Register our events + pm.registerEvent(Event.Type.BLOCK_BREAK, new blockBreak(), Event.Priority.Normal, this); + pm.registerEvent(Event.Type.BLOCK_PLACE, new blockPlace(), Event.Priority.Normal, this); + pm.registerEvent(Event.Type.SIGN_CHANGE, new signChange(), Event.Priority.Normal, this); + pm.registerEvent(Event.Type.PLAYER_INTERACT, new playerInteract(), Event.Priority.Highest, this); + pm.registerEvent(Event.Type.PLUGIN_ENABLE, new pluginEnable(), Event.Priority.Monitor, this); + pm.registerEvent(Event.Type.PLUGIN_DISABLE, new pluginDisable(), Event.Priority.Monitor, this); + pm.registerEvent(Event.Type.BLOCK_PISTON_EXTEND, new blockBreak(), Event.Priority.Normal, this); + pm.registerEvent(Event.Type.BLOCK_PISTON_RETRACT, new blockBreak(), Event.Priority.Normal, this); - //Now set up our database for storing transactions! - setupDBfile(); - if (Config.getBoolean(Property.LOG_TO_DATABASE)) { + description = this.getDescription(); //Description of the plugin + server = getServer(); //Setting out server variable + + if (Config.getBoolean(Property.LOG_TO_DATABASE) || Config.getBoolean(Property.GENERATE_STATISTICS_PAGE)) { //Now set up our database for storing transactions! setupDB(); getServer().getScheduler().scheduleAsyncRepeatingTask(this, new Queue(), 200L, 200L); if (Config.getBoolean(Property.GENERATE_STATISTICS_PAGE)) { - getServer().getScheduler().scheduleAsyncRepeatingTask(this, new Generator(), 300L, 300L); + getServer().getScheduler().scheduleAsyncRepeatingTask(this, new Generator(), 300L, (long) Config.getDouble(Property.STATISTICS_PAGE_GENERATION_INTERVAL) * 20L); } - db = getDatabase(); + DB = database.getDatabase(); } //Now set up our logging to file! @@ -90,7 +81,6 @@ public class ChestShop extends JavaPlugin { //Register our commands! getCommand("iteminfo").setExecutor(new ItemInfo()); - getCommand("chestOptions").setExecutor(new Options()); getCommand("csVersion").setExecutor(new Version()); System.out.println('[' + getPluginName() + "] version " + getVersion() + " initialized!"); @@ -101,32 +91,39 @@ public class ChestShop extends JavaPlugin { } ///////////////////// DATABASE STUFF //////////////////////////////// - private void setupDB() { - try { - getDatabase().find(Transaction.class).findRowCount(); - } catch (PersistenceException pe) { - Logging.log("Installing database for " + getPluginName()); - installDDL(); - } + private static Configuration getBukkitConfig() { + Configuration config = new Configuration(new File("bukkit.yml")); + config.load(); + return config; } - private static void setupDBfile() { - File file = new File("ebean.properties"); + private Database database; - if (!file.exists()) { - try { - file.createNewFile(); - } catch (Exception e) { - Logging.log("Failed to create ebean.properties file!"); + private void setupDB() { + database = new Database(this) { + protected java.util.List> getDatabaseClasses() { + List> list = new LinkedList>(); + list.add(Transaction.class); + return list; } - } + }; + + Configuration config = getBukkitConfig(); + + database.initializeDatabase( + config.getString("database.driver"), + config.getString("database.url"), + config.getString("database.username"), + config.getString("database.password"), + config.getString("database.isolation"), + false, + false + ); } @Override - public List> getDatabaseClasses() { - List> list = new ArrayList>(); - list.add(Transaction.class); - return list; + public EbeanServer getDatabase() { + return database.getDatabase(); } /////////////////////////////////////////////////////////////////////////////// @@ -135,14 +132,14 @@ public class ChestShop extends JavaPlugin { } public static String getVersion() { - return desc.getVersion(); + return description.getVersion(); } public static String getPluginName() { - return desc.getName(); + return description.getName(); } public static EbeanServer getDB() { - return db; + return DB; } } diff --git a/com/Acrobot/ChestShop/Chests/MinecraftChest.java b/com/Acrobot/ChestShop/Chests/MinecraftChest.java index 32f707b..8e6ccf1 100644 --- a/com/Acrobot/ChestShop/Chests/MinecraftChest.java +++ b/com/Acrobot/ChestShop/Chests/MinecraftChest.java @@ -3,15 +3,14 @@ package com.Acrobot.ChestShop.Chests; import com.Acrobot.ChestShop.Utils.uBlock; import com.Acrobot.ChestShop.Utils.uInventory; import org.bukkit.block.Chest; -import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; /** * @author Acrobot */ public class MinecraftChest implements ChestObject { - Chest main; - Chest neighbor; + private final Chest main; + private final Chest neighbor; public MinecraftChest(Chest chest) { this.main = chest; @@ -50,16 +49,12 @@ public class MinecraftChest implements ChestObject { public void addItem(ItemStack item, int amount) { int left = addItem(item, amount, main); - if (neighbor != null && left > 0) { - addItem(item, left, neighbor); - } + if (neighbor != null && left > 0) addItem(item, left, neighbor); } public void removeItem(ItemStack item, short durability, int amount) { int left = removeItem(item, durability, amount, main); - if (neighbor != null && left > 0) { - removeItem(item, durability, left, neighbor); - } + if (neighbor != null && left > 0) removeItem(item, durability, left, neighbor); } public int amount(ItemStack item, short durability) { @@ -88,17 +83,14 @@ public class MinecraftChest implements ChestObject { } private static int fits(ItemStack item, int amount, short durability, Chest chest) { - Inventory inv = chest.getInventory(); - return uInventory.fits(inv, item, amount, durability); + return uInventory.fits(chest.getInventory(), item, amount, durability); } private static int addItem(ItemStack item, int amount, Chest chest) { - Inventory inv = chest.getInventory(); - return uInventory.add(inv, item, amount); + return uInventory.add(chest.getInventory(), item, amount); } private static int removeItem(ItemStack item, short durability, int amount, Chest chest) { - Inventory inv = chest.getInventory(); - return uInventory.remove(inv, item, amount, durability); + return uInventory.remove(chest.getInventory(), item, amount, durability); } } diff --git a/com/Acrobot/ChestShop/Commands/ItemInfo.java b/com/Acrobot/ChestShop/Commands/ItemInfo.java index 749c403..f5621fa 100644 --- a/com/Acrobot/ChestShop/Commands/ItemInfo.java +++ b/com/Acrobot/ChestShop/Commands/ItemInfo.java @@ -15,19 +15,13 @@ import org.bukkit.inventory.ItemStack; */ public class ItemInfo implements CommandExecutor { public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - boolean isPlayer = (sender instanceof Player); - if (args.length == 0) { - if (!isPlayer) { - return false; - } + if (!(sender instanceof Player)) return false; Player player = (Player) sender; ItemStack itemInHand = player.getItemInHand(); - if (itemInHand.getType() == Material.AIR) { - return false; - } + if (itemInHand.getType() == Material.AIR) return false; player.sendMessage(Config.getLocal(Language.iteminfo)); player.sendMessage(itemInHand.getTypeId() + ":" + itemInHand.getDurability() + " - " + itemInHand.getType().name()); @@ -36,9 +30,7 @@ public class ItemInfo implements CommandExecutor { } else { ItemStack item = Items.getItemStack(args[0]); - if (item == null) { - return false; - } + if (item == null) return false; sender.sendMessage(Config.getLocal(Language.iteminfo)); sender.sendMessage(item.getTypeId() + ":" + item.getDurability() + " - " + item.getType().name()); diff --git a/com/Acrobot/ChestShop/Commands/Options.java b/com/Acrobot/ChestShop/Commands/Options.java deleted file mode 100644 index 02d5d1d..0000000 --- a/com/Acrobot/ChestShop/Commands/Options.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.Acrobot.ChestShop.Commands; - -import com.Acrobot.ChestShop.Options.Option; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; - -/** - * @author Acrobot - */ -public class Options implements CommandExecutor { - - public static boolean exists(String name) { - name = name.toLowerCase(); - return Option.getOption(name) != null; - } - - public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - return false; - /*if (!(sender instanceof Player)) { - return false; - } - Player player = (Player) sender; - - if (!playerpref.containsKey(player)) { - setDefault(player); - } - - if (args.length == 0) { - String[] options = optionList(); - - player.sendMessage(Config.getLocal("options")); - - for (String s : options) { - player.sendMessage(s); - } - return true; - } - - if (args.length == 1) { - Boolean exists = exists(args[0]); - - if (!exists) { - return false; - } - - player.sendMessage(Config.getColored("&a" + args[0] + " is set to: " + playerpref.get(player).getOption(args[0]))); - return true; - } - - if (args.length == 2) { - try { - Boolean option = Boolean.parseBoolean(args[1]); - Options options = playerpref.get(player); - Boolean exists = exists(args[0]); - - if (!exists) { - return false; - } - - Boolean success = options.setOption(args[0], option); - if (!success) { - return false; - } - playerpref.put(player, Option.va) - player.sendMessage(Config.getColored("&aSuccessfully set " + args[0] + " to " + args[1])); - - return true; - } catch (Exception e) { - return false; - } - } - - return false;*/ - } - - private static String[] optionList() { - return new String[]{ - "balance - show current balance after transaction", - "outOfStock - show that your shop is out of stock", - "someoneBought - show that someone bought from your shop" - }; - } -} diff --git a/com/Acrobot/ChestShop/Config/Config.java b/com/Acrobot/ChestShop/Config/Config.java index ae6003b..91f5b57 100644 --- a/com/Acrobot/ChestShop/Config/Config.java +++ b/com/Acrobot/ChestShop/Config/Config.java @@ -1,6 +1,8 @@ package com.Acrobot.ChestShop.Config; +import com.Acrobot.ChestShop.ChestShop; import com.Acrobot.ChestShop.Logging.Logging; +import com.Acrobot.ChestShop.Utils.uLongName; import org.bukkit.util.config.Configuration; import java.io.File; @@ -10,32 +12,51 @@ import java.io.FileWriter; * @author Acrobot */ public class Config { - private static File configFile = new File("plugins/ChestShop", "config.yml"); - private static File langFile = new File("plugins/ChestShop", "local.yml"); - - private static Configuration config = new Configuration(configFile); - private static Configuration language = new Configuration(langFile); - + private static File configFile; + private static File langFile; + private static Configuration config = new Configuration(new File(ChestShop.folder, "config.yml")); + private static Configuration language; public static void setUp() { + setUpConfigurations(); + + reloadConfig(); + config.load(); + + reloadLanguage(); + language.load(); + + uLongName.config = new Configuration(new File(ChestShop.folder, "longName.storage")); + uLongName.config.load(); + } + + private static void reloadConfig(){ config.load(); for (Property def : Property.values()) { if (config.getProperty(def.name()) == null) { writeToFile(def.name() + ": " + def.getValue() + "\n#" + def.getComment(), configFile); } } - config.load(); + } + private static void reloadLanguage(){ language.load(); for (Language def : Language.values()) { if (language.getProperty(def.name()) == null) { writeToFile(def.name() + ": \"" + def.toString() + '\"', langFile); } } - language.load(); } - public static void writeToFile(String string, File file) { + private static void setUpConfigurations(){ + configFile = new File(ChestShop.folder, "config.yml"); + langFile = new File(ChestShop.folder, "local.yml"); + + config = new Configuration(configFile); + language = new Configuration(langFile); + } + + private static void writeToFile(String string, File file) { try { FileWriter fw = new FileWriter(file, true); fw.write('\n' + string); @@ -61,7 +82,7 @@ public class Config { return config.getDouble(value.name(), -1); } - public static String getColored(String msg) { + private static String getColored(String msg) { return msg.replaceAll("&([0-9a-f])", "\u00A7$1"); } @@ -74,7 +95,9 @@ public class Config { } public static String getPreferred() { + config = new Configuration(new File("plugins/ChestShop", "config.yml")); config.load(); + return getString(Property.PREFERRED_ECONOMY_PLUGIN); } } diff --git a/com/Acrobot/ChestShop/Config/Language.java b/com/Acrobot/ChestShop/Config/Language.java index 6a6c337..1dbb4f2 100644 --- a/com/Acrobot/ChestShop/Config/Language.java +++ b/com/Acrobot/ChestShop/Config/Language.java @@ -1,15 +1,11 @@ package com.Acrobot.ChestShop.Config; -import java.util.HashMap; -import java.util.Map; - /** * @author Acrobot */ -public enum Language { +public enum Language{ prefix("&a[Shop] &f"), iteminfo("&aItem Information:&f"), - options("&aCustomizable options: "), ACCESS_DENIED("You don't have permission to do that!"), @@ -41,12 +37,10 @@ public enum Language { SHOP_CREATED("Shop successfully created!"), NO_PERMISSION("You don't have permissions to do that!"), - NAME_TOO_LONG("Unfortunately, your name is too long :( Please wait for newer shop version!"), INCORRECT_ITEM_ID("You have specified invalid item id!"); - private String text; - private static final Map names = new HashMap(); + private final String text; private Language(String def) { text = def; @@ -55,14 +49,4 @@ public enum Language { public String toString() { return text; } - - public static Language lookup(String name) { - return names.get(name); - } - - static { - for (Language def : values()) { - names.put(def.name(), def); - } - } } diff --git a/com/Acrobot/ChestShop/Config/Property.java b/com/Acrobot/ChestShop/Config/Property.java index 4126940..f32ac17 100644 --- a/com/Acrobot/ChestShop/Config/Property.java +++ b/com/Acrobot/ChestShop/Config/Property.java @@ -14,14 +14,15 @@ public enum Property { GENERATE_STATISTICS_PAGE(false, "If true, plugin will generate shop statistics webpage."), STATISTICS_PAGE_PATH("plugins/ChestShop/website.html", "Where should your generated website be saved?"), RECORD_TIME_TO_LIVE(600, "How long should transaction information be stored?"), + STATISTICS_PAGE_GENERATION_INTERVAL(60, "How often should the website be generated?"), USE_BUILT_IN_PROTECTION(true, "Do you want to use built-in protection against chest destruction?"), PROTECT_CHEST_WITH_LWC(false, "Do you want to protect shop chests with LWC?"), PROTECT_SIGN_WITH_LWC(false, "Do you want to protect shop signs with LWC?"), MASK_CHESTS_AS_OTHER_BLOCKS(false, "Do you want to mask shop chests as other blocks? HIGHLY EXPERIMENTAL, CAN LAG!"); - private Object value; - private String comment; + private final Object value; + private final String comment; private Property(Object value, String comment) { this.value = value; diff --git a/com/Acrobot/ChestShop/DB/Generator.java b/com/Acrobot/ChestShop/DB/Generator.java index 1beee2b..d0be937 100644 --- a/com/Acrobot/ChestShop/DB/Generator.java +++ b/com/Acrobot/ChestShop/DB/Generator.java @@ -13,13 +13,13 @@ import java.util.List; * @author Acrobot */ public class Generator implements Runnable { - private static String filePath = Config.getString(Property.STATISTICS_PAGE_PATH); + private static final String filePath = Config.getString(Property.STATISTICS_PAGE_PATH); private static double generationTime; - private static String header = fileToString("header"); - private static String row = fileToString("row"); - private static String footer = fileToString("footer"); + private static final String header = fileToString("header"); + private static final String row = fileToString("row"); + private static final String footer = fileToString("footer"); private static BufferedWriter buf; @@ -27,19 +27,19 @@ public class Generator implements Runnable { generateStats(); } - public static void fileStart() throws IOException { + private static void fileStart() throws IOException { FileWriter fw = new FileWriter(filePath); fw.write(header); fw.close(); } - public static void fileEnd() throws IOException { + private static void fileEnd() throws IOException { FileWriter fw = new FileWriter(filePath, true); fw.write(footer.replace("%time", String.valueOf(generationTime))); fw.close(); } - public static String fileToString(String fileName) { + private static String fileToString(String fileName) { try { File f = new File(ChestShop.folder + "/HTML/" + fileName + ".html"); FileReader rd = new FileReader(f); @@ -51,58 +51,46 @@ public class Generator implements Runnable { } } - public static double generateItemTotal(int itemID, boolean bought, boolean sold) { + private static double generateItemTotal(int itemID, boolean bought, boolean sold) { double amount = 0; List list; - if (bought) { - list = ChestShop.getDB().find(Transaction.class).where().eq("buy", 1).eq("itemID", itemID).findList(); - } else if (sold) { - list = ChestShop.getDB().find(Transaction.class).where().eq("buy", 0).eq("itemID", itemID).findList(); - } else { - list = ChestShop.getDB().find(Transaction.class).where().eq("itemID", itemID).findList(); - } - for (Transaction t : list) { - amount += t.getAmount(); - } + if (bought) + list = ChestShop.getDB().find(Transaction.class).where().eq("buy", 1).eq("itemID", itemID).findList(); + else if (sold) list = ChestShop.getDB().find(Transaction.class).where().eq("buy", 0).eq("itemID", itemID).findList(); + else list = ChestShop.getDB().find(Transaction.class).where().eq("itemID", itemID).findList(); + + for (Transaction t : list) amount += t.getAmount(); return amount; } - public static double generateTotalBought(int itemID) { + private static double generateTotalBought(int itemID) { return generateItemTotal(itemID, true, false); } - public static double generateTotalSold(int itemID) { + private static double generateTotalSold(int itemID) { return generateItemTotal(itemID, false, true); } - public static double generateItemTotal(int itemID) { + private static double generateItemTotal(int itemID) { return generateItemTotal(itemID, false, false); } - public static float generateAveragePrice(int itemID, boolean buy) { + private static float generateAveragePrice(int itemID) { float price = 0; - List prices = ChestShop.getDB().find(Transaction.class).where().eq("itemID", itemID).eq("buy", buy).findList(); - for (Transaction t : prices) { - price += t.getAveragePricePerItem(); - } + List prices = ChestShop.getDB().find(Transaction.class).where().eq("itemID", itemID).eq("buy", true).findList(); + for (Transaction t : prices) price += t.getAveragePricePerItem(); float toReturn = price / prices.size(); return (!Float.isNaN(toReturn) ? toReturn : 0); } - /*public static float generateAverageSellPrice(int itemID){ - return generateAveragePrice(itemID, false); - }*/ - - public static float generateAverageBuyPrice(int itemID) { - return generateAveragePrice(itemID, true); + private static float generateAverageBuyPrice(int itemID) { + return generateAveragePrice(itemID); } - public static void generateItemStats(int itemID) throws IOException { + private static void generateItemStats(int itemID) throws IOException { double total = generateItemTotal(itemID); - if (total == 0) { - return; - } + if (total == 0) return; double bought = generateTotalBought(itemID); double sold = generateTotalSold(itemID); @@ -123,17 +111,14 @@ public class Generator implements Runnable { .replace("%pricePerItem", String.valueOf(buyPrice))); } - public static void generateStats() { + private static void generateStats() { try { fileStart(); buf = new BufferedWriter(new FileWriter(filePath, true)); - long genTime = System.currentTimeMillis(); - - for (Material m : Material.values()) { - generateItemStats(m.getId()); - } + for (Material m : Material.values()) generateItemStats(m.getId()); + buf.close(); generationTime = (System.currentTimeMillis() - genTime) / 1000; diff --git a/com/Acrobot/ChestShop/DB/Queue.java b/com/Acrobot/ChestShop/DB/Queue.java index 94d4ffb..8917707 100644 --- a/com/Acrobot/ChestShop/DB/Queue.java +++ b/com/Acrobot/ChestShop/DB/Queue.java @@ -11,7 +11,7 @@ import java.util.List; * @author Acrobot */ public class Queue implements Runnable { - private static List queue = new LinkedList(); + private static final List queue = new LinkedList(); public static void addToQueue(Transaction t) { queue.add(t); diff --git a/com/Acrobot/ChestShop/Economy.java b/com/Acrobot/ChestShop/Economy.java index 851ef80..ca97a09 100644 --- a/com/Acrobot/ChestShop/Economy.java +++ b/com/Acrobot/ChestShop/Economy.java @@ -1,5 +1,6 @@ package com.Acrobot.ChestShop; +import com.Acrobot.ChestShop.Utils.uLongName; import com.nijikokun.register.payment.forChestShop.Method; /** @@ -10,23 +11,23 @@ public class Economy { public static Method economy; public static boolean hasAccount(String p) { - return economy.hasAccount(p); + return economy.hasAccount(uLongName.getName(p)); } public static void add(String name, float amount) { - economy.getAccount(name).add(amount); + economy.getAccount(uLongName.getName(name)).add(amount); } public static void substract(String name, float amount) { - economy.getAccount(name).subtract(amount); + economy.getAccount(uLongName.getName(name)).subtract(amount); } public static boolean hasEnough(String name, float amount) { - return economy.getAccount(name).hasEnough(amount); + return economy.getAccount(uLongName.getName(name)).hasEnough(amount); } public static double balance(String name) { - return economy.getAccount(name).balance(); + return economy.getAccount(uLongName.getName(name)).balance(); } public static String formatBalance(double amount) { diff --git a/com/Acrobot/ChestShop/Items/DataValue.java b/com/Acrobot/ChestShop/Items/DataValue.java index 03ef42d..cfb9519 100644 --- a/com/Acrobot/ChestShop/Items/DataValue.java +++ b/com/Acrobot/ChestShop/Items/DataValue.java @@ -9,11 +9,9 @@ import org.bukkit.material.*; /** * @author Acrobot */ -public class DataValue { +class DataValue { public static byte get(String arg, Material material) { - if (material == null) { - return 0; - } + if (material == null) return 0; arg = arg.toUpperCase().replace(" ", "_"); diff --git a/com/Acrobot/ChestShop/Items/Items.java b/com/Acrobot/ChestShop/Items/Items.java index 3d41430..4d399bd 100644 --- a/com/Acrobot/ChestShop/Items/Items.java +++ b/com/Acrobot/ChestShop/Items/Items.java @@ -12,12 +12,12 @@ public class Items { public static Material getMaterial(String itemName) { if (uNumber.isInteger(itemName)) return Material.getMaterial(Integer.parseInt(itemName)); - + int length = 256; Material finalMat = null; itemName = itemName.toLowerCase().replace("_", "").replace(" ", ""); for (Material m : Material.values()) { - String matName = m.name().toLowerCase().replace("_", "").replace(" ", ""); + String matName = m.name().toLowerCase().replace("_", ""); if (matName.startsWith(itemName) && (matName.length() < length)) { length = matName.length(); finalMat = m; @@ -28,12 +28,10 @@ public class Items { public static ItemStack getItemStack(String itemName) { ItemStack toReturn; - if ((toReturn = getFromOddItem(itemName)) != null) { - return toReturn; - } + if ((toReturn = getFromOddItem(itemName)) != null) return toReturn; Material material = getMaterial(itemName); - if(material != null) return new ItemStack(material, 1); + if (material != null) return new ItemStack(material, 1); return getItemStackWithDataValue(itemName); } @@ -43,23 +41,20 @@ public class Items { return Odd.returnItemStack(itemName.replace(":", ";")); } - private static ItemStack getItemStackWithDataValue(String itemName){ - if(!itemName.contains(":")) return getItemStackWithDataValueFromWord(itemName); + private static ItemStack getItemStackWithDataValue(String itemName) { + if (!itemName.contains(":")) return getItemStackWithDataValueFromWord(itemName); String[] word = itemName.split(":"); - if(word.length < 2 || !uNumber.isInteger(word[1])) return null; + if (word.length < 2 || !uNumber.isInteger(word[1])) return null; Material item = getMaterial(word[0]); - if(item == null) return null; - - short dataValue = Short.parseShort(word[1]); - return new ItemStack(item, 1, dataValue); + return item == null ? null : new ItemStack(item, 1, Short.parseShort(word[1])); } private static ItemStack getItemStackWithDataValueFromWord(String itemName) { if (!itemName.contains(" ") || getMaterial(itemName) != null) return null; String[] word = itemName.split(" "); - if(word.length < 2) return null; + if (word.length < 2) return null; String dataValue = word[0]; @@ -67,9 +62,7 @@ public class Items { System.arraycopy(word, 1, material, 0, word.length - 1); StringBuilder mat = new StringBuilder(); - for(String s : material){ - mat.append(s); - } + for (String s : material) mat.append(s); Material item = getMaterial(mat.toString()); diff --git a/com/Acrobot/ChestShop/Listeners/blockBreak.java b/com/Acrobot/ChestShop/Listeners/blockBreak.java index a30e562..eaeb40b 100644 --- a/com/Acrobot/ChestShop/Listeners/blockBreak.java +++ b/com/Acrobot/ChestShop/Listeners/blockBreak.java @@ -1,43 +1,49 @@ package com.Acrobot.ChestShop.Listeners; +import com.Acrobot.ChestShop.Config.Config; +import com.Acrobot.ChestShop.Config.Property; import com.Acrobot.ChestShop.Permission; -import com.Acrobot.ChestShop.Restrictions.RestrictedSign; import com.Acrobot.ChestShop.Utils.uBlock; +import com.Acrobot.ChestShop.Utils.uLongName; import com.Acrobot.ChestShop.Utils.uSign; import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockListener; +import org.bukkit.event.block.BlockPistonExtendEvent; +import org.bukkit.event.block.BlockPistonRetractEvent; /** * @author Acrobot */ public class blockBreak extends BlockListener { + private static boolean cancellingBlockBreak(Block block, Player player) { + if (player != null && Permission.has(player, Permission.ADMIN)) return false; + + if(uSign.isSign(block)) block.getState().update(); + + Sign sign = uBlock.findRestrictedSign(block); + if (sign != null) return true; + + sign = uBlock.findSign(block); + return sign != null && (player == null || (!player.getName().equals(sign.getLine(0)) && !uLongName.stripName(player.getName()).equals(sign.getLine(0)))); + } + public void onBlockBreak(BlockBreakEvent event) { - Block block = event.getBlock(); - Player player = event.getPlayer(); + if (cancellingBlockBreak(event.getBlock(), event.getPlayer())) event.setCancelled(true); + } - boolean isAdmin = Permission.has(player, Permission.ADMIN); + public void onBlockPistonExtend(BlockPistonExtendEvent event) { + if (!Config.getBoolean(Property.USE_BUILT_IN_PROTECTION)) return; - if (isAdmin) { - return; - } - - if (uSign.isSign(block)) { - Sign currentSign = (Sign) block.getState(); - if (RestrictedSign.isRestricted(currentSign)) { - event.setCancelled(true); - } - currentSign.update(true); - } - - Sign sign = uBlock.findSign(block); - - if (sign != null) { - if (!player.getName().equals(sign.getLine(0))) { - event.setCancelled(true); - } + for (Block b : event.getBlocks()){ + if (cancellingBlockBreak(b, null)) event.setCancelled(true); return; } } + + public void onBlockPistonRetract(BlockPistonRetractEvent event) { + if (!Config.getBoolean(Property.USE_BUILT_IN_PROTECTION)) return; + if (cancellingBlockBreak(event.getRetractLocation().getBlock(), null)) event.setCancelled(true); + } } diff --git a/com/Acrobot/ChestShop/Listeners/playerInteract.java b/com/Acrobot/ChestShop/Listeners/playerInteract.java index 39f6696..42009e6 100644 --- a/com/Acrobot/ChestShop/Listeners/playerInteract.java +++ b/com/Acrobot/ChestShop/Listeners/playerInteract.java @@ -5,9 +5,10 @@ import com.Acrobot.ChestShop.Config.Language; import com.Acrobot.ChestShop.Config.Property; import com.Acrobot.ChestShop.Permission; import com.Acrobot.ChestShop.Protection.Default; -import com.Acrobot.ChestShop.Restrictions.RestrictedSign; +import com.Acrobot.ChestShop.Signs.restrictedSign; import com.Acrobot.ChestShop.Shop.ShopManagement; import com.Acrobot.ChestShop.Utils.uBlock; +import com.Acrobot.ChestShop.Utils.uLongName; import com.Acrobot.ChestShop.Utils.uSign; import net.minecraft.server.IInventory; import net.minecraft.server.InventoryLargeChest; @@ -21,7 +22,6 @@ import org.bukkit.entity.Player; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerListener; -import org.bukkit.inventory.Inventory; import java.util.HashMap; @@ -30,18 +30,15 @@ import java.util.HashMap; */ public class playerInteract extends PlayerListener { - private HashMap time = new HashMap(); - public static int interval = 100; + private static final HashMap lastTransactionTime = new HashMap(); + private static final int interval = 100; public void onPlayerInteract(PlayerInteractEvent event) { Action action = event.getAction(); - Player player = event.getPlayer(); - - if (action != Action.LEFT_CLICK_BLOCK && action != Action.RIGHT_CLICK_BLOCK) { - return; - } + if (action != Action.LEFT_CLICK_BLOCK && action != Action.RIGHT_CLICK_BLOCK) return; Block block = event.getClickedBlock(); + Player player = event.getPlayer(); if (Config.getBoolean(Property.USE_BUILT_IN_PROTECTION) && block.getType() == Material.CHEST) { Default protection = new Default(); @@ -52,49 +49,38 @@ public class playerInteract extends PlayerListener { } } - if (!uSign.isSign(block)) { - return; - } + if (!uSign.isSign(block)) return; Sign sign = (Sign) block.getState(); - if (!uSign.isValid(sign) || time.containsKey(player) && (System.currentTimeMillis() - time.get(player)) < interval) { - return; - } - time.put(player, System.currentTimeMillis()); + if (!uSign.isValid(sign) || lastTransactionTime.containsKey(player) && (System.currentTimeMillis() - lastTransactionTime.get(player)) < interval || player.isSneaking()) return; - if (player.isSneaking()) { - return; - } + lastTransactionTime.put(player, System.currentTimeMillis()); - if (player.getName().equals(sign.getLine(0))) { + String playerName = player.getName(); + + if (playerName.equals(sign.getLine(0)) || uLongName.stripName(playerName).equals(sign.getLine(0))) { Chest chest1 = uBlock.findChest(sign); if (chest1 == null) { player.sendMessage(Config.getLocal(Language.NO_CHEST_DETECTED)); return; } - Inventory inv1 = chest1.getInventory(); - IInventory iInv1 = ((CraftInventory) inv1).getInventory(); - + IInventory inventory = ((CraftInventory) chest1.getInventory()).getInventory(); Chest chest2 = uBlock.findNeighbor(chest1); if (chest2 != null) { - Inventory inv2 = chest2.getInventory(); - IInventory iInv2 = ((CraftInventory) inv2).getInventory(); - IInventory largeChest = new InventoryLargeChest(player.getName() + "'s Shop", iInv1, iInv2); - ((CraftPlayer) player).getHandle().a(largeChest); - } else { - ((CraftPlayer) player).getHandle().a(iInv1); + IInventory iInv2 = ((CraftInventory) chest2.getInventory()).getInventory(); + inventory = new InventoryLargeChest(player.getName() + "'s Shop", inventory, iInv2); } + + ((CraftPlayer) player).getHandle().a(inventory); return; } - if (RestrictedSign.isRestricted(sign)) { - if (!RestrictedSign.canAccess(sign, player)) { - player.sendMessage(Config.getLocal(Language.ACCESS_DENIED)); - return; - } + if (restrictedSign.isRestrictedShop(sign) && !restrictedSign.canAccess(sign, player)) { + player.sendMessage(Config.getLocal(Language.ACCESS_DENIED)); + return; } Action buy = (Config.getBoolean(Property.REVERSE_BUTTONS) ? Action.LEFT_CLICK_BLOCK : Action.RIGHT_CLICK_BLOCK); diff --git a/com/Acrobot/ChestShop/Listeners/pluginEnable.java b/com/Acrobot/ChestShop/Listeners/pluginEnable.java index ceae162..bf70d8d 100644 --- a/com/Acrobot/ChestShop/Listeners/pluginEnable.java +++ b/com/Acrobot/ChestShop/Listeners/pluginEnable.java @@ -23,8 +23,7 @@ import org.yi.acru.bukkit.Lockette.Lockette; */ public class pluginEnable extends ServerListener { - public static Methods methods = new Methods(Config.getPreferred()); - + public static final Methods methods = new Methods(Config.getPreferred()); public void onPluginEnable(PluginEnableEvent event) { diff --git a/com/Acrobot/ChestShop/Listeners/signChange.java b/com/Acrobot/ChestShop/Listeners/signChange.java index d7f2b0a..6dc33f8 100644 --- a/com/Acrobot/ChestShop/Listeners/signChange.java +++ b/com/Acrobot/ChestShop/Listeners/signChange.java @@ -7,8 +7,9 @@ import com.Acrobot.ChestShop.Items.Items; import com.Acrobot.ChestShop.Permission; import com.Acrobot.ChestShop.Protection.Default; import com.Acrobot.ChestShop.Protection.Security; -import com.Acrobot.ChestShop.Restrictions.RestrictedSign; +import com.Acrobot.ChestShop.Signs.restrictedSign; import com.Acrobot.ChestShop.Utils.uBlock; +import com.Acrobot.ChestShop.Utils.uLongName; import com.Acrobot.ChestShop.Utils.uNumber; import com.Acrobot.ChestShop.Utils.uSign; import org.bukkit.Material; @@ -33,21 +34,13 @@ public class signChange extends BlockListener { Boolean isAlmostReady = uSign.isValidPreparedSign(event.getLines()); Player player = event.getPlayer(); - ItemStack stock = Items.getItemStack(line[3]); - - Material mat = stock == null ? null : stock.getType(); boolean playerIsAdmin = Permission.has(player, Permission.ADMIN); if (isAlmostReady) { - if (player.getName().length() > 15) { - player.sendMessage(Config.getLocal(Language.NAME_TOO_LONG)); - dropSign(event); - return; - } if (mat == null) { player.sendMessage(Config.getLocal(Language.INCORRECT_ITEM_ID)); dropSign(event); @@ -63,13 +56,13 @@ public class signChange extends BlockListener { return; } } else { - if (RestrictedSign.isRestricted(event.getLines())) { + if (restrictedSign.isRestricted(event.getLines())) { if (!playerIsAdmin) { player.sendMessage(Config.getLocal(Language.ACCESS_DENIED)); dropSign(event); return; } - Block secondSign = signBlock.getFace(BlockFace.DOWN); + Block secondSign = signBlock.getRelative(BlockFace.DOWN); if (!uSign.isSign(secondSign) || !uSign.isValid((Sign) secondSign.getState())) { dropSign(event); } @@ -84,7 +77,7 @@ public class signChange extends BlockListener { } line = event.getLines(); - + boolean isAdminShop = uSign.isAdminShop(line[0]); if (!isReady) { @@ -155,10 +148,11 @@ public class signChange extends BlockListener { player.sendMessage(Config.getLocal(Language.PROTECTED_SHOP)); } + uLongName.saveName(player.getName()); player.sendMessage(Config.getLocal(Language.SHOP_CREATED)); } - public static void dropSign(SignChangeEvent event) { + private static void dropSign(SignChangeEvent event) { event.setCancelled(true); Block block = event.getBlock(); diff --git a/com/Acrobot/ChestShop/Logging/FileWriterQueue.java b/com/Acrobot/ChestShop/Logging/FileWriterQueue.java index f47db46..5551ebb 100644 --- a/com/Acrobot/ChestShop/Logging/FileWriterQueue.java +++ b/com/Acrobot/ChestShop/Logging/FileWriterQueue.java @@ -3,6 +3,7 @@ package com.Acrobot.ChestShop.Logging; import com.Acrobot.ChestShop.ChestShop; import java.io.BufferedWriter; +import java.io.File; import java.io.FileWriter; import java.util.LinkedList; import java.util.List; @@ -11,8 +12,8 @@ import java.util.List; * @author Acrobot */ public class FileWriterQueue implements Runnable { - private static List queue = new LinkedList(); - public static String filePath = ChestShop.folder + "/ChestShop.log"; + private static final List queue = new LinkedList(); + private static final String filePath = new File(ChestShop.folder, "ChestShop.log").getPath(); public static void addToQueue(String message) { queue.add(message); diff --git a/com/Acrobot/ChestShop/Logging/Logging.java b/com/Acrobot/ChestShop/Logging/Logging.java index ebb6cd0..5b819c7 100644 --- a/com/Acrobot/ChestShop/Logging/Logging.java +++ b/com/Acrobot/ChestShop/Logging/Logging.java @@ -11,30 +11,32 @@ import org.bukkit.inventory.ItemStack; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; +import java.util.logging.Level; +import java.util.logging.Logger; /** * @author Acrobot */ public class Logging { - private static DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + private static final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + private static final Logger logger = Logger.getLogger("ChestShop"); - public static String getDateAndTime() { + private static String getDateAndTime() { Date date = new Date(); return dateFormat.format(date); } public static void log(String string) { - if (Config.getBoolean(Property.LOG_TO_CONSOLE)) { - System.out.println("[ChestShop] " + string); - } - FileWriterQueue.addToQueue(getDateAndTime() + ' ' + string); + if (Config.getBoolean(Property.LOG_TO_CONSOLE)) logger.log(Level.INFO,"[ChestShop] " + string); + if (Config.getBoolean(Property.LOG_TO_FILE)) FileWriterQueue.addToQueue(getDateAndTime() + ' ' + string); } public static void logTransaction(boolean isBuying, Shop shop, Player player) { log(player.getName() + (isBuying ? " bought " : " sold ") + shop.stockAmount + ' ' + shop.stock.getType() + " for " + (isBuying ? shop.buyPrice + " from " : shop.sellPrice + " to ") + shop.owner); - if (!Config.getBoolean(Property.LOG_TO_DATABASE)) { - return; - } + if (Config.getBoolean(Property.LOG_TO_DATABASE)) logToDatabase(isBuying, shop, player); + } + + private static void logToDatabase(boolean isBuying, Shop shop, Player player){ Transaction transaction = new Transaction(); transaction.setAmount(shop.stockAmount); diff --git a/com/Acrobot/ChestShop/Messaging/Message.java b/com/Acrobot/ChestShop/Messaging/Message.java deleted file mode 100644 index 0aadb17..0000000 --- a/com/Acrobot/ChestShop/Messaging/Message.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.Acrobot.ChestShop.Messaging; - -import org.bukkit.entity.Player; - -/** - * @author Acrobot - */ -public class Message { - public static void sendMsg(Player player, String msg) { - player.sendMessage(msg); - } -} diff --git a/com/Acrobot/ChestShop/Options/Option.java b/com/Acrobot/ChestShop/Options/Option.java deleted file mode 100644 index 0568972..0000000 --- a/com/Acrobot/ChestShop/Options/Option.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.Acrobot.ChestShop.Options; - - -import java.util.HashMap; -import java.util.Map; - -/** - * @author Acrobot - */ -public enum Option { - BALANCE("balance", true), - OUT_OF_STOCK("outOfStock", true), - SOMEONE_BOUGHT("someoneBought", true); - - private boolean enabled; - private String name; - private static final Map names = new HashMap(); - - private Option(String name, boolean enabled) { - this.enabled = enabled; - this.name = name; - } - - public boolean isEnabled() { - return this.enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public static Option getOption(String name) { - return names.get(name); - } - - static { - for (Option op : values()) { - names.put(op.name(), op); - } - } -} diff --git a/com/Acrobot/ChestShop/Permission.java b/com/Acrobot/ChestShop/Permission.java index 96b5319..a1c1289 100644 --- a/com/Acrobot/ChestShop/Permission.java +++ b/com/Acrobot/ChestShop/Permission.java @@ -23,16 +23,13 @@ public enum Permission { public static PermissionHandler permissions; public static boolean has(Player player, Permission permission) { - String node = permission.permission; - return has(player, node); + return has(player, permission.permission); } public static boolean has(Player player, String node) { - if (permissions != null) { - return permissions.has(player, node); - } else { - return !node.contains("exclude") && ((!node.contains("admin") && !node.contains("mod")) || player.isOp()); - } + //return !node.contains("exclude") && !node.contains ("create.") && ((!node.contains("admin") && !node.contains("mod")) || player.isOp()); + if (permissions != null) return permissions.has(player, node); + return player.hasPermission(node); } public String toString() { diff --git a/com/Acrobot/ChestShop/Protection/Default.java b/com/Acrobot/ChestShop/Protection/Default.java index 923235f..da6bfcb 100644 --- a/com/Acrobot/ChestShop/Protection/Default.java +++ b/com/Acrobot/ChestShop/Protection/Default.java @@ -1,6 +1,7 @@ package com.Acrobot.ChestShop.Protection; import com.Acrobot.ChestShop.Utils.uBlock; +import com.Acrobot.ChestShop.Utils.uLongName; import com.Acrobot.ChestShop.Utils.uSign; import org.bukkit.block.Block; import org.bukkit.block.Chest; @@ -12,30 +13,25 @@ import org.bukkit.entity.Player; */ public class Default implements Protection { public boolean isProtected(Block block) { - if ((uSign.isSign(block) && uSign.isValid((Sign) block.getState())) || uBlock.findSign(block) != null) { - return true; - } else { - if (!(block.getState() instanceof Chest)) { - return false; - } - if (uBlock.findSign(block) != null) { - return true; - } - Chest neighbor = uBlock.findNeighbor(block); - if (neighbor != null && uBlock.findSign(neighbor.getBlock()) != null) { - return true; - } - } + if ((uSign.isSign(block) && uSign.isValid((Sign) block.getState())) || uBlock.findSign(block) != null) return true; + if (!(block.getState() instanceof Chest)) return false; - return false; + Chest neighbor = uBlock.findNeighbor(block); + return neighbor != null && uBlock.findSign(neighbor.getBlock()) != null; } public boolean canAccess(Player player, Block block) { Sign sign = uBlock.findSign(block); - Chest nChest = uBlock.findNeighbor(block); - Sign nSign = (nChest != null ? uBlock.findSign(nChest.getBlock()) : null); - return ((uSign.isSign(block) && uSign.isValid((Sign) block.getState()) && ((Sign) block.getState()).getLine(0).equals(player.getName())) || (sign != null && sign.getLine(0).equals(player.getName()))) - || (nSign != null && nSign.getLine(0).equals(player.getName())); + Chest neighborChest = uBlock.findNeighbor(block); + Sign neighborSign = (neighborChest != null ? uBlock.findSign(neighborChest.getBlock()) : null); + + String playerName = player.getName(); + String signLine = ""; + if (uSign.isSign(block) && uSign.isValid((Sign) block.getState())) signLine = ((Sign) block.getState()).getLine(0); + if (sign != null) signLine = sign.getLine(0); + if (neighborSign != null) signLine = neighborSign.getLine(0); + + return playerName.equals(signLine) || uLongName.stripName(playerName).equals(signLine); } public boolean protect(String name, Block block) { diff --git a/com/Acrobot/ChestShop/Protection/LockettePlugin.java b/com/Acrobot/ChestShop/Protection/LockettePlugin.java index e0bc847..caf2032 100644 --- a/com/Acrobot/ChestShop/Protection/LockettePlugin.java +++ b/com/Acrobot/ChestShop/Protection/LockettePlugin.java @@ -15,7 +15,8 @@ public class LockettePlugin implements Protection { } public boolean canAccess(Player player, Block block) { - return player.getName().equals(Lockette.getProtectedOwner(block)); + int length = (player.getName().length() > 15? 15 : player.getName().length()); + return player.getName().substring(0, length).equals(Lockette.getProtectedOwner(block)); } public boolean protect(String name, Block block) { diff --git a/com/Acrobot/ChestShop/Protection/MaskChest.java b/com/Acrobot/ChestShop/Protection/MaskChest.java index eb76572..e64402e 100644 --- a/com/Acrobot/ChestShop/Protection/MaskChest.java +++ b/com/Acrobot/ChestShop/Protection/MaskChest.java @@ -5,6 +5,7 @@ import com.Acrobot.ChestShop.Utils.uBlock; import com.Acrobot.ChestShop.Utils.uSign; import org.bukkit.Location; import org.bukkit.Material; +import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.Chest; @@ -14,12 +15,13 @@ import org.bukkit.entity.Player; * @author Acrobot */ public class MaskChest implements Runnable { - BlockFace[] bf = {BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST, BlockFace.UP, BlockFace.DOWN}; + private final BlockFace[] bf = {BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST, BlockFace.UP, BlockFace.DOWN}; public void run() { Player[] players = ChestShop.getBukkitServer().getOnlinePlayers(); for (Player player : players) { + World world = player.getWorld(); Location location = player.getLocation(); int pX = location.getBlockX(); @@ -31,7 +33,7 @@ public class MaskChest implements Runnable { for (int x = -radius; x < radius; x++) { for (int y = -radius; y < radius; y++) { for (int z = -radius; z < radius; z++) { - Block block = player.getWorld().getBlockAt(x + pX, y + pY, z + pZ); + Block block = world.getBlockAt(x + pX, y + pY, z + pZ); if (block.getType() == Material.CHEST) { if (uBlock.findSign(block) != null) { @@ -49,13 +51,11 @@ public class MaskChest implements Runnable { } } - Material returnNearestMat(Block block) { + private Material returnNearestMat(Block block) { for (BlockFace face : bf) { - Block faceBlock = block.getFace(face); + Block faceBlock = block.getRelative(face); Material type = faceBlock.getType(); - if (type != Material.AIR && !uSign.isSign(faceBlock) && type != Material.CHEST) { - return type; - } + if (type != Material.AIR && !uSign.isSign(faceBlock) && type != Material.CHEST) return type; } return Material.CHEST; } diff --git a/com/Acrobot/ChestShop/Shop/Shop.java b/com/Acrobot/ChestShop/Shop/Shop.java index bad0e71..b43037e 100644 --- a/com/Acrobot/ChestShop/Shop/Shop.java +++ b/com/Acrobot/ChestShop/Shop/Shop.java @@ -18,45 +18,45 @@ import org.bukkit.inventory.ItemStack; * @author Acrobot */ public class Shop { - public ItemStack stock; - public short durability; - public int stockAmount; - public ChestObject chest; - public float buyPrice; - public float sellPrice; - public String owner; + public final ItemStack stock; + private final short durability; + public final int stockAmount; + private final ChestObject chest; + public final float buyPrice; + public final float sellPrice; + public final String owner; - public Shop(ChestObject chest, Sign sign, ItemStack... itemStacks) { + public Shop(ChestObject chest, boolean buy, Sign sign, ItemStack... itemStacks) { this.stock = itemStacks[0]; this.durability = stock.getDurability(); this.chest = chest; - this.buyPrice = uSign.buyPrice(sign.getLine(2)); - this.sellPrice = uSign.sellPrice(sign.getLine(2)); + this.buyPrice = (buy ? uSign.buyPrice(sign.getLine(2)) : -1); + this.sellPrice = (!buy ? uSign.sellPrice(sign.getLine(2)) : -1); this.owner = sign.getLine(0); this.stockAmount = uSign.itemAmount(sign.getLine(1)); } - public boolean buy(Player player) { + public void buy(Player player) { if (chest == null && !isAdminShop()) { player.sendMessage(Config.getLocal(Language.NO_CHEST_DETECTED)); - return false; + return; } if (buyPrice == -1) { player.sendMessage(Config.getLocal(Language.NO_BUYING_HERE)); - return false; + return; } if (!Permission.has(player, Permission.BUY)) { player.sendMessage(Config.getLocal(Language.NO_PERMISSION)); - return false; + return; } String playerName = player.getName(); if (!Economy.hasEnough(playerName, buyPrice)) { player.sendMessage(Config.getLocal(Language.NOT_ENOUGH_MONEY)); - return false; + return; } if (!stockFitsPlayer(player)) { player.sendMessage(Config.getLocal(Language.NOT_ENOUGH_SPACE_IN_INVENTORY)); - return false; + return; } String materialName = stock.getType().name(); @@ -64,18 +64,16 @@ public class Shop { if (!isAdminShop() && !hasEnoughStock()) { player.sendMessage(Config.getLocal(Language.NOT_ENOUGH_STOCK)); sendMessageToOwner(Config.getLocal(Language.NOT_ENOUGH_STOCK_IN_YOUR_SHOP).replace("%material", materialName)); - return false; + return; } String account = getOwnerAccount(); - if (!account.isEmpty() && Economy.hasAccount(account)) { - Economy.add(account, buyPrice); - } + if (!account.isEmpty() && Economy.hasAccount(account)) Economy.add(account, buyPrice); + Economy.substract(playerName, buyPrice); - if (!isAdminShop()) { - chest.removeItem(stock, durability, stockAmount); - } + if (!isAdminShop()) chest.removeItem(stock, durability, stockAmount); + String formatedPrice = Economy.formatBalance(buyPrice); player.sendMessage(Config.getLocal(Language.YOU_BOUGHT_FROM_SHOP) .replace("%amount", String.valueOf(stockAmount)) @@ -92,49 +90,42 @@ public class Shop { .replace("%item", materialName) .replace("%buyer", playerName) .replace("%price", formatedPrice)); - return true; } - public boolean sell(Player player) { + public void sell(Player player) { if (chest == null && !isAdminShop()) { player.sendMessage(Config.getLocal(Language.NO_CHEST_DETECTED)); - return false; + return; } if (sellPrice == -1) { player.sendMessage(Config.getLocal(Language.NO_SELLING_HERE)); - return false; + return; } if (!Permission.has(player, Permission.SELL)) { player.sendMessage(Config.getLocal(Language.NO_PERMISSION)); - return false; + return; } + String account = getOwnerAccount(); boolean accountExists = !account.isEmpty() && Economy.hasAccount(account); - if (accountExists) { - if (!Economy.hasEnough(account, sellPrice)) { - player.sendMessage(Config.getLocal(Language.NOT_ENOUGH_MONEY_SHOP)); - return false; - } + if (accountExists && !Economy.hasEnough(account, sellPrice)) { + player.sendMessage(Config.getLocal(Language.NOT_ENOUGH_MONEY_SHOP)); + return; } if (!isAdminShop() && !stockFitsChest(chest)) { player.sendMessage(Config.getLocal(Language.NOT_ENOUGH_SPACE_IN_CHEST)); - return false; + return; } if (uInventory.amount(player.getInventory(), stock, durability) < stockAmount) { player.sendMessage(Config.getLocal(Language.NOT_ENOUGH_ITEMS_TO_SELL)); - return false; + return; } - if (accountExists) { - Economy.substract(account, sellPrice); - } - - if (!isAdminShop()) { - chest.addItem(stock, stockAmount); - } + if (accountExists) Economy.substract(account, sellPrice); + if (!isAdminShop()) chest.addItem(stock, stockAmount); Economy.add(player.getName(), sellPrice); @@ -156,17 +147,10 @@ public class Shop { .replace("%item", materialName) .replace("%seller", player.getName()) .replace("%price", formatedBalance)); - - - return true; } private String getOwnerAccount() { - if (uSign.isAdminShop(owner)) { - return Config.getString(Property.SERVER_ECONOMY_ACCOUNT); - } else { - return owner; - } + return uSign.isAdminShop(owner) ? Config.getString(Property.SERVER_ECONOMY_ACCOUNT) : owner; } private boolean isAdminShop() { diff --git a/com/Acrobot/ChestShop/Shop/ShopManagement.java b/com/Acrobot/ChestShop/Shop/ShopManagement.java index bec3dd4..68c0b0a 100644 --- a/com/Acrobot/ChestShop/Shop/ShopManagement.java +++ b/com/Acrobot/ChestShop/Shop/ShopManagement.java @@ -13,27 +13,25 @@ import org.bukkit.inventory.ItemStack; * @author Acrobot */ public class ShopManagement { - public static boolean buy(Sign sign, Player player) { + public static void buy(Sign sign, Player player) { Chest chestMc = uBlock.findChest(sign); ItemStack item = Items.getItemStack(sign.getLine(3)); if (item == null) { player.sendMessage(ChatColor.RED + "[Shop] The item is not recognised!"); - return false; + return; } - Shop shop = new Shop(chestMc != null ? new MinecraftChest(chestMc) : null, sign, item); - - return shop.buy(player); + Shop shop = new Shop(chestMc != null ? new MinecraftChest(chestMc) : null, true, sign, item); + shop.buy(player); } - public static boolean sell(Sign sign, Player player) { + public static void sell(Sign sign, Player player) { Chest chestMc = uBlock.findChest(sign); ItemStack item = Items.getItemStack(sign.getLine(3)); if (item == null) { player.sendMessage(ChatColor.RED + "[Shop] The item is not recognised!"); - return false; + return; } - Shop shop = new Shop(chestMc != null ? new MinecraftChest(chestMc) : null, sign, item); - - return shop.sell(player); + Shop shop = new Shop(chestMc != null ? new MinecraftChest(chestMc) : null, false, sign, item); + shop.sell(player); } } diff --git a/com/Acrobot/ChestShop/Restrictions/RestrictedSign.java b/com/Acrobot/ChestShop/Signs/restrictedSign.java similarity index 61% rename from com/Acrobot/ChestShop/Restrictions/RestrictedSign.java rename to com/Acrobot/ChestShop/Signs/restrictedSign.java index 86e76d2..cbe4d3c 100644 --- a/com/Acrobot/ChestShop/Restrictions/RestrictedSign.java +++ b/com/Acrobot/ChestShop/Signs/restrictedSign.java @@ -1,4 +1,4 @@ -package com.Acrobot.ChestShop.Restrictions; +package com.Acrobot.ChestShop.Signs; import com.Acrobot.ChestShop.Permission; import com.Acrobot.ChestShop.Utils.uSign; @@ -10,9 +10,9 @@ import org.bukkit.entity.Player; /** * @author Acrobot */ -public class RestrictedSign { - public static boolean isRestricted(Sign sign) { - Block blockUp = sign.getBlock().getFace(BlockFace.UP); +public class restrictedSign { + public static boolean isRestrictedShop(Sign sign) { + Block blockUp = sign.getBlock().getRelative(BlockFace.UP); return uSign.isSign(blockUp) && isRestricted(((Sign) blockUp.getState()).getLines()); } @@ -20,20 +20,22 @@ public class RestrictedSign { return lines[0].equalsIgnoreCase("[restricted]"); } + public static boolean isRestricted(Sign sign) { + return sign.getLine(0).equalsIgnoreCase("[restricted]"); + } + public static boolean canAccess(Sign sign, Player player) { - Block blockUp = sign.getBlock().getFace(BlockFace.UP); - if (Permission.permissions == null || !uSign.isSign(blockUp) || Permission.has(player, Permission.ADMIN)) { - return true; - } + Block blockUp = sign.getBlock().getRelative(BlockFace.UP); + if (Permission.permissions == null || !uSign.isSign(blockUp) || Permission.has(player, Permission.ADMIN)) return true; + String world = blockUp.getWorld().getName(); String playerName = player.getName(); sign = (Sign) blockUp.getState(); - boolean result = false; for (int i = 1; i <= 3; i++) { - result = result || Permission.permissions.inGroup(world, playerName, sign.getLine(i)); + if(Permission.permissions.inGroup(world, playerName, sign.getLine(i))) return true; } - return result; + return false; } } diff --git a/com/Acrobot/ChestShop/Utils/uBlock.java b/com/Acrobot/ChestShop/Utils/uBlock.java index 176ab38..3485c30 100644 --- a/com/Acrobot/ChestShop/Utils/uBlock.java +++ b/com/Acrobot/ChestShop/Utils/uBlock.java @@ -1,5 +1,6 @@ package com.Acrobot.ChestShop.Utils; +import com.Acrobot.ChestShop.Signs.restrictedSign; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; @@ -11,8 +12,8 @@ import org.bukkit.block.Sign; */ public class uBlock { - static BlockFace[] chestFaces = {BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST, BlockFace.SOUTH}; - static BlockFace[] shopFaces = {BlockFace.DOWN, BlockFace.UP, BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST, BlockFace.SOUTH, BlockFace.SELF}; + private static final BlockFace[] chestFaces = {BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST, BlockFace.SOUTH}; + private static final BlockFace[] shopFaces = {BlockFace.DOWN, BlockFace.UP, BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST, BlockFace.SOUTH, BlockFace.SELF}; public static Chest findChest(Sign sign) { Block block = sign.getBlock(); @@ -21,7 +22,7 @@ public class uBlock { public static Chest findChest(Block block) { for (BlockFace bf : shopFaces) { - Block faceBlock = block.getFace(bf); + Block faceBlock = block.getRelative(bf); if (faceBlock.getType() == Material.CHEST) { return (Chest) faceBlock.getState(); } @@ -31,7 +32,7 @@ public class uBlock { public static Sign findSign(Block block) { for (BlockFace bf : shopFaces) { - Block faceBlock = block.getFace(bf); + Block faceBlock = block.getRelative(bf); if (uSign.isSign(faceBlock)) { Sign sign = (Sign) faceBlock.getState(); if (uSign.isValid(sign)) { @@ -42,9 +43,22 @@ public class uBlock { return null; } + public static Sign findRestrictedSign(Block block) { + for (BlockFace bf : shopFaces) { + Block faceBlock = block.getRelative(bf); + if (uSign.isSign(faceBlock)) { + Sign sign = (Sign) faceBlock.getState(); + if (restrictedSign.isRestricted(sign)) { + return sign; + } + } + } + return null; + } + public static Chest findNeighbor(Block block) { for (BlockFace blockFace : chestFaces) { - Block neighborBlock = block.getFace(blockFace); + Block neighborBlock = block.getRelative(blockFace); if (neighborBlock.getType() == Material.CHEST) { return (Chest) neighborBlock.getState(); } diff --git a/com/Acrobot/ChestShop/Utils/uInventory.java b/com/Acrobot/ChestShop/Utils/uInventory.java index da06ad8..ce08448 100644 --- a/com/Acrobot/ChestShop/Utils/uInventory.java +++ b/com/Acrobot/ChestShop/Utils/uInventory.java @@ -17,19 +17,13 @@ public class uInventory { Material itemMaterial = item.getType(); int first = inv.first(itemMaterial); - if (first == -1) { - return amount; - } + if (first == -1) return amount; for (int slot = first; slot < inv.getSize(); slot++) { - if (amount <= 0) { - return 0; - } + if (amount <= 0) return 0; ItemStack currentItem = inv.getItem(slot); - if (currentItem == null || currentItem.getType() == Material.AIR) { - continue; - } + if (currentItem == null || currentItem.getType() == Material.AIR) continue; if (currentItem.getType() == itemMaterial && (durability == -1 || currentItem.getDurability() == durability)) { int currentAmount = currentItem.getAmount(); @@ -53,8 +47,7 @@ public class uInventory { public static int add(Inventory inv, ItemStack item, int amount) { amount = (amount > 0 ? amount : 1); - Material itemMaterial = item.getType(); - int maxStackSize = itemMaterial.getMaxStackSize(); + int maxStackSize = item.getType().getMaxStackSize(); if (amount <= maxStackSize) { item.setAmount(amount); @@ -66,7 +59,6 @@ public class uInventory { for (int i = 0; i < Math.ceil(amount / maxStackSize); i++) { if (amount <= maxStackSize) { item.setAmount(amount); - items.add(item); return 0; } else { item.setAmount(maxStackSize); @@ -75,25 +67,17 @@ public class uInventory { } amount = 0; - for (ItemStack itemToAdd : items) { - amount += (!inv.addItem(itemToAdd).isEmpty() ? itemToAdd.getAmount() : 0); - } + for (ItemStack itemToAdd : items) amount += (!inv.addItem(itemToAdd).isEmpty() ? itemToAdd.getAmount() : 0); return amount; } public static int amount(Inventory inv, ItemStack item, short durability) { + if (!inv.contains(item.getType())) return 0; + int amount = 0; - if (!inv.contains(item.getType())) { - return amount; - } - ItemStack[] contents = inv.getContents(); - for (ItemStack i : contents) { - if (i != null) { - if (i.getType() == item.getType() && (durability == -1 || i.getDurability() == durability)) { - amount += i.getAmount(); - } - } + for (ItemStack i : inv.getContents()) { + if (i != null && i.getType() == item.getType() && (durability == -1 || i.getDurability() == durability)) amount += i.getAmount(); } return amount; } @@ -101,13 +85,10 @@ public class uInventory { public static int fits(Inventory inv, ItemStack item, int amount, short durability) { Material itemMaterial = item.getType(); int maxStackSize = itemMaterial.getMaxStackSize(); - int amountLeft = amount; for (ItemStack currentItem : inv.getContents()) { - if (amountLeft <= 0) { - return 0; - } + if (amountLeft <= 0) return 0; if (currentItem == null || currentItem.getType() == Material.AIR) { amountLeft -= maxStackSize; diff --git a/com/Acrobot/ChestShop/Utils/uLongName.java b/com/Acrobot/ChestShop/Utils/uLongName.java new file mode 100644 index 0000000..07b6dd5 --- /dev/null +++ b/com/Acrobot/ChestShop/Utils/uLongName.java @@ -0,0 +1,30 @@ +package com.Acrobot.ChestShop.Utils; + +import org.bukkit.util.config.Configuration; + +/** + * @author Acrobot + */ +public class uLongName { + public static Configuration config; + + public static String getName(final String shortName){ + return config.getString(shortName, shortName); + } + + public static void saveName(String name){ + if (!(name.length() > 15)) return; + String shortName = name.substring(0, 15); + config.setProperty(shortName, name); + reloadConfig(); + } + + public static String stripName(String name) { + return (name.length() > 15 ? name.substring(0, 15) : name); + } + + private static void reloadConfig(){ + config.save(); + config.load(); + } +} diff --git a/com/Acrobot/ChestShop/Utils/uSign.java b/com/Acrobot/ChestShop/Utils/uSign.java index f6ba4ac..c549916 100644 --- a/com/Acrobot/ChestShop/Utils/uSign.java +++ b/com/Acrobot/ChestShop/Utils/uSign.java @@ -11,10 +11,7 @@ import java.util.regex.Pattern; * @author Acrobot */ public class uSign { - - //static Pattern firstLine = Pattern.compile("^[A-Za-z0-9].+$"); - - static Pattern[] patterns = { + private static final Pattern[] patterns = { Pattern.compile("^$|^\\w.+$"), Pattern.compile("[0-9]+"), Pattern.compile(".+"), @@ -56,16 +53,16 @@ public class uSign { public static float buyPrice(String text) { text = text.replace(" ", "").toLowerCase(); - int buyPart = (text.contains("b") ? 0 : -1); - if (buyPart == -1) { - return -1; - } - text = text.replace("b", "").replace("s", ""); String[] split = text.split(":"); - if (uNumber.isFloat(split[0])) { - float buyPrice = Float.parseFloat(split[0]); + int buyPart = (text.contains("b") ? (split[0].contains("b") ? 0 : 1) : -1); + if (buyPart == -1 || (buyPart == 1 && split.length != 2)) return -1; + + split[buyPart] = split[buyPart].replace("b", ""); + + if (uNumber.isFloat(split[buyPart])) { + float buyPrice = Float.parseFloat(split[buyPart]); return (buyPrice != 0 ? buyPrice : -1); - } else if (split[0].equals("free")) { + } else if (split[buyPart].equals("free")) { return 0; } @@ -75,14 +72,12 @@ public class uSign { public static float sellPrice(String text) { text = text.replace(" ", "").toLowerCase(); - int sellPart = (text.contains("b") && text.contains("s") ? 1 : (text.contains("s") ? 0 : -1)); - text = text.replace("b", "").replace("s", ""); String[] split = text.split(":"); + int sellPart = (text.contains("s") ? (split[0].contains("s") ? 0 : 1) : -1); + if(sellPart == -1 || (sellPart == 1 && split.length != 2)) return -1; - if (sellPart == -1 || (sellPart == 1 && split.length < 2)) { - return -1; - } - + split[sellPart] = split[sellPart].replace("s", ""); + if (uNumber.isFloat(split[sellPart])) { Float sellPrice = Float.parseFloat(split[sellPart]); return (sellPrice != 0 ? sellPrice : -1); @@ -96,8 +91,6 @@ public class uSign { if (uNumber.isInteger(text)) { int amount = Integer.parseInt(text); return (amount >= 1 ? amount : 1); - } else { - return 1; - } + } else return 1; } } diff --git a/com/lennardf1989/bukkitex/Database.java b/com/lennardf1989/bukkitex/Database.java new file mode 100644 index 0000000..0bbb634 --- /dev/null +++ b/com/lennardf1989/bukkitex/Database.java @@ -0,0 +1,357 @@ +package com.lennardf1989.bukkitex; + +import com.avaje.ebean.EbeanServer; +import com.avaje.ebean.EbeanServerFactory; +import com.avaje.ebean.config.DataSourceConfig; +import com.avaje.ebean.config.ServerConfig; +import com.avaje.ebean.config.dbplatform.SQLitePlatform; +import com.avaje.ebeaninternal.api.SpiEbeanServer; +import com.avaje.ebeaninternal.server.ddl.DdlGenerator; +import com.avaje.ebeaninternal.server.lib.sql.TransactionIsolation; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.BufferedReader; +import java.io.StringReader; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.net.URLConnection; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +public abstract class Database { + private JavaPlugin javaPlugin; + private ClassLoader classLoader; + private Level loggerLevel; + private boolean usingSQLite; + private ServerConfig serverConfig; + private EbeanServer ebeanServer; + + /** + * Create an instance of Database + * + * @param javaPlugin Plugin instancing this database + */ + public Database(JavaPlugin javaPlugin) { + //Store the JavaPlugin + this.javaPlugin = javaPlugin; + + //Try to get the ClassLoader of the plugin using Reflection + try { + //Find the "getClassLoader" method and make it "public" instead of "protected" + Method method = JavaPlugin.class.getDeclaredMethod("getClassLoader"); + method.setAccessible(true); + + //Store the ClassLoader + this.classLoader = (ClassLoader) method.invoke(javaPlugin); + } catch (Exception ex) { + throw new RuntimeException("Failed to retrieve the ClassLoader of the plugin using Reflection", ex); + } + } + + /** + * Initialize the database using the passed arguments + * + * @param driver Database-driver to use. For example: org.sqlite.JDBC + * @param url Location of the database. For example: jdbc:sqlite:{DIR}{NAME}.db + * @param username Username required to access the database + * @param password Password belonging to the username, may be empty + * @param isolation Isolation type. For example: SERIALIZABLE, also see TransactionIsolation + * @param logging If set to false, all logging will be disabled + * @param rebuild If set to true, all tables will be dropped and recreated. Be sure to create a backup before doing so! + */ + public void initializeDatabase(String driver, String url, String username, String password, String isolation, boolean logging, boolean rebuild) { + //Logging needs to be set back to the original level, no matter what happens + try { + //Disable all logging + disableDatabaseLogging(logging); + + //Prepare the database + prepareDatabase(driver, url, username, password, isolation); + + //Load the database + loadDatabase(); + + //Create all tables + installDatabase(rebuild); + } catch (Exception ex) { + throw new RuntimeException("An exception has occured while initializing the database", ex); + } finally { + //Enable all logging + enableDatabaseLogging(logging); + } + } + + private void prepareDatabase(String driver, String url, String username, String password, String isolation) { + //Setup the data source + DataSourceConfig ds = new DataSourceConfig(); + ds.setDriver(driver); + ds.setUrl(replaceDatabaseString(url)); + ds.setUsername(username); + ds.setPassword(password); + ds.setIsolationLevel(TransactionIsolation.getLevel(isolation)); + + //Setup the server configuration + ServerConfig sc = new ServerConfig(); + sc.setDefaultServer(false); + sc.setRegister(false); + sc.setName(ds.getUrl().replaceAll("[^a-zA-Z0-9]", "")); + + //Get all persistent classes + List> classes = getDatabaseClasses(); + + //Do a sanity check first + if (classes.isEmpty()) throw new RuntimeException("Database has been enabled, but no classes are registered to it"); + + //Register them with the EbeanServer + sc.setClasses(classes); + + //Check if the SQLite JDBC supplied with Bukkit is being used + if (ds.getDriver().equalsIgnoreCase("org.sqlite.JDBC")) { + //Remember the database is a SQLite-database + usingSQLite = true; + + //Modify the platform, as SQLite has no AUTO_INCREMENT field + sc.setDatabasePlatform(new SQLitePlatform()); + sc.getDatabasePlatform().getDbDdlSyntax().setIdentity(""); + } + + //Finally the data source + sc.setDataSourceConfig(ds); + + //Store the ServerConfig + serverConfig = sc; + } + + private void loadDatabase() { + //Declare a few local variables for later use + ClassLoader currentClassLoader = null; + Field cacheField = null; + boolean cacheValue = true; + + try { + //Store the current ClassLoader, so it can be reverted later + currentClassLoader = Thread.currentThread().getContextClassLoader(); + + //Set the ClassLoader to Plugin ClassLoader + Thread.currentThread().setContextClassLoader(classLoader); + + //Get a reference to the private static "defaultUseCaches"-field in URLConnection + cacheField = URLConnection.class.getDeclaredField("defaultUseCaches"); + + //Make it accessible, store the default value and set it to false + cacheField.setAccessible(true); + cacheValue = cacheField.getBoolean(null); + cacheField.setBoolean(null, false); + + //Setup Ebean based on the configuration + ebeanServer = EbeanServerFactory.create(serverConfig); + } catch (Exception ex) { + throw new RuntimeException("Failed to create a new instance of the EbeanServer", ex); + } finally { + //Revert the ClassLoader back to its original value + if (currentClassLoader != null) Thread.currentThread().setContextClassLoader(currentClassLoader); + + //Revert the "defaultUseCaches"-field in URLConnection back to its original value + try { + if (cacheField != null) cacheField.setBoolean(null, cacheValue); + } catch (Exception e) { + System.out.println("Failed to revert the \"defaultUseCaches\"-field back to its original value, URLConnection-caching remains disabled."); + } + } + } + + private void installDatabase(boolean rebuild) { + //Check if the database has to be rebuild + if (!rebuild) return; + + //Create a DDL generator + SpiEbeanServer serv = (SpiEbeanServer) ebeanServer; + DdlGenerator gen = serv.getDdlGenerator(); + + //Check if the database already (partially) exists + boolean databaseExists = false; + + for (Class aClass : getDatabaseClasses()) { + try { + //Do a simple query which only throws an exception if the table does not exist + ebeanServer.find(aClass).findRowCount(); + + //Query passed without throwing an exception, a database therefore already exists + databaseExists = true; + break; + } catch (Exception ignored) {} + } + + //Fire "before drop" event + try { + beforeDropDatabase(); + } catch (Exception ex) { + //If the database exists, dropping has to be canceled to prevent data-loss + if (databaseExists) throw new RuntimeException("An unexpected exception occured", ex); + } + + //Generate a DropDDL-script + gen.runScript(true, gen.generateDropDdl()); + + //If SQLite is being used, the database has to reloaded to release all resources + if (usingSQLite) loadDatabase(); + + //Generate a CreateDDL-script + //If SQLite is being used, the CreateDLL-script has to be validated and potentially fixed to be valid + gen.runScript(false, (usingSQLite ? validateCreateDDLSqlite(gen.generateCreateDdl()) : gen.generateCreateDdl())); + + //Fire "after create" event + try { + afterCreateDatabase(); + } catch (Exception ex) { + throw new RuntimeException("An unexpected exception occured", ex); + } + } + + private String replaceDatabaseString(String input) { + input = input.replaceAll("\\{DIR\\}", javaPlugin.getDataFolder().getPath().replaceAll("\\\\", "/") + '/'); + input = input.replaceAll("\\{NAME\\}", javaPlugin.getDescription().getName().replaceAll("[^\\w_-]", "")); + + return input; + } + + private static String validateCreateDDLSqlite(String oldScript) { + try { + //Create a BufferedReader out of the potentially invalid script + BufferedReader scriptReader = new BufferedReader(new StringReader(oldScript)); + + //Create an array to store all the lines + List scriptLines = new ArrayList(); + + //Create some additional variables for keeping track of tables + HashMap foundTables = new HashMap(); + String currentTable = null; + int tableOffset = 0; + + //Loop through all lines + String currentLine; + while ((currentLine = scriptReader.readLine()) != null) { + //Trim the current line to remove trailing spaces + currentLine = currentLine.trim(); + + //Add the current line to the rest of the lines + scriptLines.add(currentLine.trim()); + + //Check if the current line is of any use + if (currentLine.startsWith("create table")) { + //Found a table, so get its name and remember the line it has been encountered on + currentTable = currentLine.split(" ", 4)[2]; + foundTables.put(currentLine.split(" ", 3)[2], scriptLines.size() - 1); + } else if (currentLine.startsWith(";") && currentTable != null && !currentTable.isEmpty()) { + //Found the end of a table definition, so update the entry + int index = scriptLines.size() - 1; + foundTables.put(currentTable, index); + + //Remove the last ")" from the previous line + String previousLine = scriptLines.get(index - 1); + previousLine = previousLine.substring(0, previousLine.length() - 1); + scriptLines.set(index - 1, previousLine); + + //Change ";" to ");" on the current line + scriptLines.set(index, ");"); + + //Reset the table-tracker + currentTable = null; + } else if (currentLine.startsWith("alter table")) { + //Found a potentially unsupported action + String[] alterTableLine = currentLine.split(" ", 4); + + if (alterTableLine[3].startsWith("add constraint")) { + //Found an unsupported action: ALTER TABLE using ADD CONSTRAINT + String[] addConstraintLine = alterTableLine[3].split(" ", 4); + + //Check if this line can be fixed somehow + if (addConstraintLine[3].startsWith("foreign key")) { + //Calculate the index of last line of the current table + int tableLastLine = foundTables.get(alterTableLine[2]) + tableOffset; + + //Add a "," to the previous line + scriptLines.set(tableLastLine - 1, scriptLines.get(tableLastLine - 1) + ','); + + //Add the constraint as a new line - Remove the ";" on the end + String constraintLine = String.format("%s %s %s", addConstraintLine[1], addConstraintLine[2], addConstraintLine[3]); + scriptLines.add(tableLastLine, constraintLine.substring(0, constraintLine.length() - 1)); + + //Remove this line and raise the table offset because a line has been inserted + scriptLines.remove(scriptLines.size() - 1); + tableOffset++; + } else { + //Exception: This line cannot be fixed but is known the be unsupported by SQLite + throw new RuntimeException("Unsupported action encountered: ALTER TABLE using ADD CONSTRAINT with " + addConstraintLine[3]); + } + } + } + } + + //Turn all the lines back into a single string + StringBuilder newScript = new StringBuilder(); + for (String newLine : scriptLines) newScript.append(newLine).append('\n'); + + //Print the new script + System.out.println(newScript); + + //Return the fixed script + return newScript.toString(); + } catch (Exception ex) { + //Exception: Failed to fix the DDL or something just went plain wrong + throw new RuntimeException("Failed to validate the CreateDDL-script for SQLite", ex); + } + } + + private void disableDatabaseLogging(boolean logging) { + //If logging is allowed, nothing has to be changed + if (logging) return; + + //Retrieve the level of the root logger + loggerLevel = Logger.getLogger("").getLevel(); + + //Set the level of the root logger to OFF + Logger.getLogger("").setLevel(Level.OFF); + } + + private void enableDatabaseLogging(boolean logging) { + //If logging is allowed, nothing has to be changed + if (logging) return; + + //Set the level of the root logger back to the original value + Logger.getLogger("").setLevel(loggerLevel); + } + + /** + * Get a list of classes which should be registered with the EbeanServer + * + * @return List List of classes which should be registered with the EbeanServer + */ + protected List> getDatabaseClasses() { + return new ArrayList>(); + } + + /** + * Method called before the loaded database is being dropped + */ + protected void beforeDropDatabase() { + } + + /** + * Method called after the loaded database has been created + */ + protected void afterCreateDatabase() { + } + + /** + * Get the instance of the EbeanServer + * + * @return EbeanServer Instance of the EbeanServer + */ + public EbeanServer getDatabase() { + return ebeanServer; + } +} diff --git a/com/nijikokun/register/payment/forChestShop/Methods.java b/com/nijikokun/register/payment/forChestShop/Methods.java index 5e15097..a6ec39c 100644 --- a/com/nijikokun/register/payment/forChestShop/Methods.java +++ b/com/nijikokun/register/payment/forChestShop/Methods.java @@ -53,7 +53,7 @@ public class Methods { return Dependencies; } - public Method createMethod(Plugin plugin) { + Method createMethod(Plugin plugin) { for (Method method: Methods) { if (method.isCompatible(plugin)) { method.setPlugin(plugin); @@ -82,7 +82,7 @@ public class Methods { Plugin plugin; PluginManager manager = method.getServer().getPluginManager(); - for(String name: this.getDependencies()) { + for(String name: this.Dependencies) { if(hasMethod()) break; if(method.getDescription().getName().equals(name)) plugin = method; else plugin = manager.getPlugin(name); if(plugin == null) continue; diff --git a/com/nijikokun/register/payment/forChestShop/methods/BOSE6.java b/com/nijikokun/register/payment/forChestShop/methods/BOSE6.java index 75b85df..f28f84f 100644 --- a/com/nijikokun/register/payment/forChestShop/methods/BOSE6.java +++ b/com/nijikokun/register/payment/forChestShop/methods/BOSE6.java @@ -59,7 +59,7 @@ public class BOSE6 implements Method { BOSEconomy = (BOSEconomy)plugin; } - public class BOSEAccount implements MethodAccount { + public static class BOSEAccount implements MethodAccount { private String name; private BOSEconomy BOSEconomy; @@ -69,7 +69,7 @@ public class BOSE6 implements Method { } public double balance() { - return Double.valueOf(this.BOSEconomy.getPlayerMoney(this.name)); + return (double) this.BOSEconomy.getPlayerMoney(this.name); } public boolean set(double amount) { @@ -121,7 +121,7 @@ public class BOSE6 implements Method { } } - public class BOSEBankAccount implements MethodBankAccount { + public static class BOSEBankAccount implements MethodBankAccount { private String bank; private BOSEconomy BOSEconomy; @@ -139,7 +139,7 @@ public class BOSE6 implements Method { } public double balance() { - return Double.valueOf(this.BOSEconomy.getBankMoney(bank)); + return (double) this.BOSEconomy.getBankMoney(bank); } public boolean set(double amount) { diff --git a/com/nijikokun/register/payment/forChestShop/methods/BOSE7.java b/com/nijikokun/register/payment/forChestShop/methods/BOSE7.java index d6a51a9..fe86557 100644 --- a/com/nijikokun/register/payment/forChestShop/methods/BOSE7.java +++ b/com/nijikokun/register/payment/forChestShop/methods/BOSE7.java @@ -63,7 +63,7 @@ public class BOSE7 implements Method { BOSEconomy = (BOSEconomy)plugin; } - public class BOSEAccount implements MethodAccount { + public static class BOSEAccount implements MethodAccount { private String name; private BOSEconomy BOSEconomy; @@ -120,7 +120,7 @@ public class BOSE7 implements Method { } } - public class BOSEBankAccount implements MethodBankAccount { + public static class BOSEBankAccount implements MethodBankAccount { private String bank; private BOSEconomy BOSEconomy; diff --git a/com/nijikokun/register/payment/forChestShop/methods/EE17.java b/com/nijikokun/register/payment/forChestShop/methods/EE17.java index 88c99de..b53ab6f 100644 --- a/com/nijikokun/register/payment/forChestShop/methods/EE17.java +++ b/com/nijikokun/register/payment/forChestShop/methods/EE17.java @@ -64,7 +64,7 @@ public class EE17 implements Method { Essentials = (Essentials)plugin; } - public class EEcoAccount implements MethodAccount { + public static class EEcoAccount implements MethodAccount { private String name; public EEcoAccount(String name) { diff --git a/com/nijikokun/register/payment/forChestShop/methods/iCo4.java b/com/nijikokun/register/payment/forChestShop/methods/iCo4.java index 9b0e3b5..00ef01e 100644 --- a/com/nijikokun/register/payment/forChestShop/methods/iCo4.java +++ b/com/nijikokun/register/payment/forChestShop/methods/iCo4.java @@ -23,7 +23,7 @@ public class iCo4 implements Method { } public String format(double amount) { - return this.iConomy.getBank().format(amount); + return iConomy.getBank().format(amount); } public boolean hasBanks() { @@ -35,7 +35,7 @@ public class iCo4 implements Method { } public boolean hasAccount(String name) { - return this.iConomy.getBank().hasAccount(name); + return iConomy.getBank().hasAccount(name); } public boolean hasBankAccount(String bank, String name) { @@ -43,7 +43,7 @@ public class iCo4 implements Method { } public MethodAccount getAccount(String name) { - return new iCoAccount(this.iConomy.getBank().getAccount(name)); + return new iCoAccount(iConomy.getBank().getAccount(name)); } public MethodBankAccount getBankAccount(String bank, String name) { @@ -58,7 +58,7 @@ public class iCo4 implements Method { iConomy = (iConomy)plugin; } - public class iCoAccount implements MethodAccount { + public static class iCoAccount implements MethodAccount { private Account account; public iCoAccount(Account account) { diff --git a/com/nijikokun/register/payment/forChestShop/methods/iCo5.java b/com/nijikokun/register/payment/forChestShop/methods/iCo5.java index c68b9e2..e7fcadf 100644 --- a/com/nijikokun/register/payment/forChestShop/methods/iCo5.java +++ b/com/nijikokun/register/payment/forChestShop/methods/iCo5.java @@ -26,7 +26,7 @@ public class iCo5 implements Method { } public String format(double amount) { - return this.iConomy.format(amount); + return iConomy.format(amount); } public boolean hasBanks() { @@ -34,23 +34,23 @@ public class iCo5 implements Method { } public boolean hasBank(String bank) { - return (!hasBanks()) ? false : this.iConomy.Banks.exists(bank); + return (hasBanks()) && iConomy.Banks.exists(bank); } public boolean hasAccount(String name) { - return this.iConomy.hasAccount(name); + return iConomy.hasAccount(name); } public boolean hasBankAccount(String bank, String name) { - return (!hasBank(bank)) ? false : this.iConomy.getBank(bank).hasAccount(name); + return (hasBank(bank)) && iConomy.getBank(bank).hasAccount(name); } public MethodAccount getAccount(String name) { - return new iCoAccount(this.iConomy.getAccount(name)); + return new iCoAccount(iConomy.getAccount(name)); } public MethodBankAccount getBankAccount(String bank, String name) { - return new iCoBankAccount(this.iConomy.getBank(bank).getAccount(name)); + return new iCoBankAccount(iConomy.getBank(bank).getAccount(name)); } public boolean isCompatible(Plugin plugin) { @@ -61,7 +61,7 @@ public class iCo5 implements Method { iConomy = (iConomy)plugin; } - public class iCoAccount implements MethodAccount { + public static class iCoAccount implements MethodAccount { private Account account; private Holdings holdings; @@ -131,7 +131,7 @@ public class iCo5 implements Method { } } - public class iCoBankAccount implements MethodBankAccount { + public static class iCoBankAccount implements MethodBankAccount { private BankAccount account; private Holdings holdings; diff --git a/plugin.yml b/plugin.yml index 0214b71..5a2f249 100644 --- a/plugin.yml +++ b/plugin.yml @@ -2,8 +2,7 @@ name: ChestShop main: com.Acrobot.ChestShop.ChestShop -database: true -version: 3.00 BETA 9 +version: 3.00 BETA 10 author: Acrobot @@ -21,9 +20,33 @@ commands: description: Shows the ChestShop's version usage: | / - chestOptions: - aliases: [coptions,cop,cpref] - description: Sets ChestShop's preferences - Not implemented yet - usage: | - / (option) (value) - () - optional \ No newline at end of file + +permissions: + ChestShop.*: + description: Gives access to all ChestShop permissions + default: op + children: + ChestShop.shop.*: true + ChestShop.admin: true + ChestShop.shop.*: + description: Gives access to all user ChestShop permissions + children: + ChestShop.shop.create: true + ChestShop.shop.buy: true + ChestShop.shop.sell: true + default: true + ChestShop.shop.create.(itemID): + description: Allows user to create a shop that sells item with itemID like in the permission node (replace (itemID) with NUMERICAL item ID) + ChestShop.shop.exclude.(itemID): + description: Denies creation of a shop that sells item with itemID like in the permission node (replace (itemID) with NUMERICAL item ID) + ChestShop.shop.create: + description: Allows user to create a shop that sells any item + ChestShop.shop.buy: + description: Allows user to buy from a shop + ChestShop.shop.sell: + description: Allows user to sell to a shop + ChestShop.admin: + description: Allows user to modify/destroy other stores and create an Admin Shops + default: op + ChestShop.mod: + description: Allows user only to view other store chests, he can't destroy them or create an Admin Shop \ No newline at end of file