- 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)
This commit is contained in:
Acrobot 2011-07-23 21:00:47 +02:00
parent 770b8e88cd
commit 7b6d7d59bd
39 changed files with 779 additions and 586 deletions

View File

@ -1,7 +1,6 @@
package com.Acrobot.ChestShop; package com.Acrobot.ChestShop;
import com.Acrobot.ChestShop.Commands.ItemInfo; import com.Acrobot.ChestShop.Commands.ItemInfo;
import com.Acrobot.ChestShop.Commands.Options;
import com.Acrobot.ChestShop.Commands.Version; import com.Acrobot.ChestShop.Commands.Version;
import com.Acrobot.ChestShop.Config.Config; import com.Acrobot.ChestShop.Config.Config;
import com.Acrobot.ChestShop.Config.Property; 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.DB.Transaction;
import com.Acrobot.ChestShop.Listeners.*; import com.Acrobot.ChestShop.Listeners.*;
import com.Acrobot.ChestShop.Logging.FileWriterQueue; import com.Acrobot.ChestShop.Logging.FileWriterQueue;
import com.Acrobot.ChestShop.Logging.Logging;
import com.Acrobot.ChestShop.Protection.MaskChest; import com.Acrobot.ChestShop.Protection.MaskChest;
import com.avaje.ebean.EbeanServer; import com.avaje.ebean.EbeanServer;
import com.lennardf1989.bukkitex.Database;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.config.Configuration;
import javax.persistence.PersistenceException;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.LinkedList;
import java.util.List; import java.util.List;
/** /**
@ -31,50 +30,42 @@ import java.util.List;
*/ */
public class ChestShop extends JavaPlugin { public class ChestShop extends JavaPlugin {
private final pluginEnable pluginEnable = new pluginEnable(); public static File folder = new File("plugins/ChestShop"); //In case Bukkit fails
private final blockBreak blockBreak = new blockBreak(); private static EbeanServer DB;
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; private static PluginDescriptionFile description;
public static EbeanServer db;
private static PluginDescriptionFile desc;
private static Server server; private static Server server;
public void onEnable() { public void onEnable() {
PluginManager pm = getServer().getPluginManager(); 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! //Yep, set up our folder!
folder = getDataFolder(); folder = getDataFolder();
//Set up our config file! //Set up our config file!
Config.setUp(); 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! description = this.getDescription(); //Description of the plugin
setupDBfile(); server = getServer(); //Setting out server variable
if (Config.getBoolean(Property.LOG_TO_DATABASE)) {
if (Config.getBoolean(Property.LOG_TO_DATABASE) || Config.getBoolean(Property.GENERATE_STATISTICS_PAGE)) { //Now set up our database for storing transactions!
setupDB(); setupDB();
getServer().getScheduler().scheduleAsyncRepeatingTask(this, new Queue(), 200L, 200L); getServer().getScheduler().scheduleAsyncRepeatingTask(this, new Queue(), 200L, 200L);
if (Config.getBoolean(Property.GENERATE_STATISTICS_PAGE)) { 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! //Now set up our logging to file!
@ -90,7 +81,6 @@ public class ChestShop extends JavaPlugin {
//Register our commands! //Register our commands!
getCommand("iteminfo").setExecutor(new ItemInfo()); getCommand("iteminfo").setExecutor(new ItemInfo());
getCommand("chestOptions").setExecutor(new Options());
getCommand("csVersion").setExecutor(new Version()); getCommand("csVersion").setExecutor(new Version());
System.out.println('[' + getPluginName() + "] version " + getVersion() + " initialized!"); System.out.println('[' + getPluginName() + "] version " + getVersion() + " initialized!");
@ -101,32 +91,39 @@ public class ChestShop extends JavaPlugin {
} }
///////////////////// DATABASE STUFF //////////////////////////////// ///////////////////// DATABASE STUFF ////////////////////////////////
private void setupDB() { private static Configuration getBukkitConfig() {
try { Configuration config = new Configuration(new File("bukkit.yml"));
getDatabase().find(Transaction.class).findRowCount(); config.load();
} catch (PersistenceException pe) { return config;
Logging.log("Installing database for " + getPluginName());
installDDL();
}
} }
private static void setupDBfile() { private Database database;
File file = new File("ebean.properties");
if (!file.exists()) { private void setupDB() {
try { database = new Database(this) {
file.createNewFile(); protected java.util.List<Class<?>> getDatabaseClasses() {
} catch (Exception e) { List<Class<?>> list = new LinkedList<Class<?>>();
Logging.log("Failed to create ebean.properties file!"); 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 @Override
public List<Class<?>> getDatabaseClasses() { public EbeanServer getDatabase() {
List<Class<?>> list = new ArrayList<Class<?>>(); return database.getDatabase();
list.add(Transaction.class);
return list;
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -135,14 +132,14 @@ public class ChestShop extends JavaPlugin {
} }
public static String getVersion() { public static String getVersion() {
return desc.getVersion(); return description.getVersion();
} }
public static String getPluginName() { public static String getPluginName() {
return desc.getName(); return description.getName();
} }
public static EbeanServer getDB() { public static EbeanServer getDB() {
return db; return DB;
} }
} }

View File

@ -3,15 +3,14 @@ package com.Acrobot.ChestShop.Chests;
import com.Acrobot.ChestShop.Utils.uBlock; import com.Acrobot.ChestShop.Utils.uBlock;
import com.Acrobot.ChestShop.Utils.uInventory; import com.Acrobot.ChestShop.Utils.uInventory;
import org.bukkit.block.Chest; import org.bukkit.block.Chest;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
/** /**
* @author Acrobot * @author Acrobot
*/ */
public class MinecraftChest implements ChestObject { public class MinecraftChest implements ChestObject {
Chest main; private final Chest main;
Chest neighbor; private final Chest neighbor;
public MinecraftChest(Chest chest) { public MinecraftChest(Chest chest) {
this.main = chest; this.main = chest;
@ -50,16 +49,12 @@ public class MinecraftChest implements ChestObject {
public void addItem(ItemStack item, int amount) { public void addItem(ItemStack item, int amount) {
int left = addItem(item, amount, main); int left = addItem(item, amount, main);
if (neighbor != null && left > 0) { if (neighbor != null && left > 0) addItem(item, left, neighbor);
addItem(item, left, neighbor);
}
} }
public void removeItem(ItemStack item, short durability, int amount) { public void removeItem(ItemStack item, short durability, int amount) {
int left = removeItem(item, durability, amount, main); int left = removeItem(item, durability, amount, main);
if (neighbor != null && left > 0) { if (neighbor != null && left > 0) removeItem(item, durability, left, neighbor);
removeItem(item, durability, left, neighbor);
}
} }
public int amount(ItemStack item, short durability) { 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) { private static int fits(ItemStack item, int amount, short durability, Chest chest) {
Inventory inv = chest.getInventory(); return uInventory.fits(chest.getInventory(), item, amount, durability);
return uInventory.fits(inv, item, amount, durability);
} }
private static int addItem(ItemStack item, int amount, Chest chest) { private static int addItem(ItemStack item, int amount, Chest chest) {
Inventory inv = chest.getInventory(); return uInventory.add(chest.getInventory(), item, amount);
return uInventory.add(inv, item, amount);
} }
private static int removeItem(ItemStack item, short durability, int amount, Chest chest) { private static int removeItem(ItemStack item, short durability, int amount, Chest chest) {
Inventory inv = chest.getInventory(); return uInventory.remove(chest.getInventory(), item, amount, durability);
return uInventory.remove(inv, item, amount, durability);
} }
} }

View File

@ -15,19 +15,13 @@ import org.bukkit.inventory.ItemStack;
*/ */
public class ItemInfo implements CommandExecutor { public class ItemInfo implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
boolean isPlayer = (sender instanceof Player);
if (args.length == 0) { if (args.length == 0) {
if (!isPlayer) { if (!(sender instanceof Player)) return false;
return false;
}
Player player = (Player) sender; Player player = (Player) sender;
ItemStack itemInHand = player.getItemInHand(); ItemStack itemInHand = player.getItemInHand();
if (itemInHand.getType() == Material.AIR) { if (itemInHand.getType() == Material.AIR) return false;
return false;
}
player.sendMessage(Config.getLocal(Language.iteminfo)); player.sendMessage(Config.getLocal(Language.iteminfo));
player.sendMessage(itemInHand.getTypeId() + ":" + itemInHand.getDurability() + " - " + itemInHand.getType().name()); player.sendMessage(itemInHand.getTypeId() + ":" + itemInHand.getDurability() + " - " + itemInHand.getType().name());
@ -36,9 +30,7 @@ public class ItemInfo implements CommandExecutor {
} else { } else {
ItemStack item = Items.getItemStack(args[0]); ItemStack item = Items.getItemStack(args[0]);
if (item == null) { if (item == null) return false;
return false;
}
sender.sendMessage(Config.getLocal(Language.iteminfo)); sender.sendMessage(Config.getLocal(Language.iteminfo));
sender.sendMessage(item.getTypeId() + ":" + item.getDurability() + " - " + item.getType().name()); sender.sendMessage(item.getTypeId() + ":" + item.getDurability() + " - " + item.getType().name());

View File

@ -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"
};
}
}

View File

@ -1,6 +1,8 @@
package com.Acrobot.ChestShop.Config; package com.Acrobot.ChestShop.Config;
import com.Acrobot.ChestShop.ChestShop;
import com.Acrobot.ChestShop.Logging.Logging; import com.Acrobot.ChestShop.Logging.Logging;
import com.Acrobot.ChestShop.Utils.uLongName;
import org.bukkit.util.config.Configuration; import org.bukkit.util.config.Configuration;
import java.io.File; import java.io.File;
@ -10,32 +12,51 @@ import java.io.FileWriter;
* @author Acrobot * @author Acrobot
*/ */
public class Config { public class Config {
private static File configFile = new File("plugins/ChestShop", "config.yml"); private static File configFile;
private static File langFile = new File("plugins/ChestShop", "local.yml"); private static File langFile;
private static Configuration config = new Configuration(new File(ChestShop.folder, "config.yml"));
private static Configuration config = new Configuration(configFile); private static Configuration language;
private static Configuration language = new Configuration(langFile);
public static void setUp() { 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(); config.load();
for (Property def : Property.values()) { for (Property def : Property.values()) {
if (config.getProperty(def.name()) == null) { if (config.getProperty(def.name()) == null) {
writeToFile(def.name() + ": " + def.getValue() + "\n#" + def.getComment(), configFile); writeToFile(def.name() + ": " + def.getValue() + "\n#" + def.getComment(), configFile);
} }
} }
config.load(); }
private static void reloadLanguage(){
language.load(); language.load();
for (Language def : Language.values()) { for (Language def : Language.values()) {
if (language.getProperty(def.name()) == null) { if (language.getProperty(def.name()) == null) {
writeToFile(def.name() + ": \"" + def.toString() + '\"', langFile); 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 { try {
FileWriter fw = new FileWriter(file, true); FileWriter fw = new FileWriter(file, true);
fw.write('\n' + string); fw.write('\n' + string);
@ -61,7 +82,7 @@ public class Config {
return config.getDouble(value.name(), -1); 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"); return msg.replaceAll("&([0-9a-f])", "\u00A7$1");
} }
@ -74,7 +95,9 @@ public class Config {
} }
public static String getPreferred() { public static String getPreferred() {
config = new Configuration(new File("plugins/ChestShop", "config.yml"));
config.load(); config.load();
return getString(Property.PREFERRED_ECONOMY_PLUGIN); return getString(Property.PREFERRED_ECONOMY_PLUGIN);
} }
} }

View File

@ -1,15 +1,11 @@
package com.Acrobot.ChestShop.Config; package com.Acrobot.ChestShop.Config;
import java.util.HashMap;
import java.util.Map;
/** /**
* @author Acrobot * @author Acrobot
*/ */
public enum Language { public enum Language{
prefix("&a[Shop] &f"), prefix("&a[Shop] &f"),
iteminfo("&aItem Information:&f"), iteminfo("&aItem Information:&f"),
options("&aCustomizable options: "),
ACCESS_DENIED("You don't have permission to do that!"), ACCESS_DENIED("You don't have permission to do that!"),
@ -41,12 +37,10 @@ public enum Language {
SHOP_CREATED("Shop successfully created!"), SHOP_CREATED("Shop successfully created!"),
NO_PERMISSION("You don't have permissions to do that!"), 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!"); INCORRECT_ITEM_ID("You have specified invalid item id!");
private String text; private final String text;
private static final Map<String, Language> names = new HashMap<String, Language>();
private Language(String def) { private Language(String def) {
text = def; text = def;
@ -55,14 +49,4 @@ public enum Language {
public String toString() { public String toString() {
return text; return text;
} }
public static Language lookup(String name) {
return names.get(name);
}
static {
for (Language def : values()) {
names.put(def.name(), def);
}
}
} }

View File

@ -14,14 +14,15 @@ public enum Property {
GENERATE_STATISTICS_PAGE(false, "If true, plugin will generate shop statistics webpage."), 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?"), 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?"), 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?"), 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_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?"), 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!"); MASK_CHESTS_AS_OTHER_BLOCKS(false, "Do you want to mask shop chests as other blocks? HIGHLY EXPERIMENTAL, CAN LAG!");
private Object value; private final Object value;
private String comment; private final String comment;
private Property(Object value, String comment) { private Property(Object value, String comment) {
this.value = value; this.value = value;

View File

@ -13,13 +13,13 @@ import java.util.List;
* @author Acrobot * @author Acrobot
*/ */
public class Generator implements Runnable { 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 double generationTime;
private static String header = fileToString("header"); private static final String header = fileToString("header");
private static String row = fileToString("row"); private static final String row = fileToString("row");
private static String footer = fileToString("footer"); private static final String footer = fileToString("footer");
private static BufferedWriter buf; private static BufferedWriter buf;
@ -27,19 +27,19 @@ public class Generator implements Runnable {
generateStats(); generateStats();
} }
public static void fileStart() throws IOException { private static void fileStart() throws IOException {
FileWriter fw = new FileWriter(filePath); FileWriter fw = new FileWriter(filePath);
fw.write(header); fw.write(header);
fw.close(); fw.close();
} }
public static void fileEnd() throws IOException { private static void fileEnd() throws IOException {
FileWriter fw = new FileWriter(filePath, true); FileWriter fw = new FileWriter(filePath, true);
fw.write(footer.replace("%time", String.valueOf(generationTime))); fw.write(footer.replace("%time", String.valueOf(generationTime)));
fw.close(); fw.close();
} }
public static String fileToString(String fileName) { private static String fileToString(String fileName) {
try { try {
File f = new File(ChestShop.folder + "/HTML/" + fileName + ".html"); File f = new File(ChestShop.folder + "/HTML/" + fileName + ".html");
FileReader rd = new FileReader(f); 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; double amount = 0;
List<Transaction> list; List<Transaction> list;
if (bought) { if (bought)
list = ChestShop.getDB().find(Transaction.class).where().eq("buy", 1).eq("itemID", itemID).findList(); list = ChestShop.getDB().find(Transaction.class).where().eq("buy", 1).eq("itemID", itemID).findList();
} else if (sold) { else if (sold) list = ChestShop.getDB().find(Transaction.class).where().eq("buy", 0).eq("itemID", itemID).findList();
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();
} else {
list = ChestShop.getDB().find(Transaction.class).where().eq("itemID", itemID).findList(); for (Transaction t : list) amount += t.getAmount();
}
for (Transaction t : list) {
amount += t.getAmount();
}
return amount; return amount;
} }
public static double generateTotalBought(int itemID) { private static double generateTotalBought(int itemID) {
return generateItemTotal(itemID, true, false); return generateItemTotal(itemID, true, false);
} }
public static double generateTotalSold(int itemID) { private static double generateTotalSold(int itemID) {
return generateItemTotal(itemID, false, true); return generateItemTotal(itemID, false, true);
} }
public static double generateItemTotal(int itemID) { private static double generateItemTotal(int itemID) {
return generateItemTotal(itemID, false, false); return generateItemTotal(itemID, false, false);
} }
public static float generateAveragePrice(int itemID, boolean buy) { private static float generateAveragePrice(int itemID) {
float price = 0; float price = 0;
List<Transaction> prices = ChestShop.getDB().find(Transaction.class).where().eq("itemID", itemID).eq("buy", buy).findList(); List<Transaction> prices = ChestShop.getDB().find(Transaction.class).where().eq("itemID", itemID).eq("buy", true).findList();
for (Transaction t : prices) { for (Transaction t : prices) price += t.getAveragePricePerItem();
price += t.getAveragePricePerItem();
}
float toReturn = price / prices.size(); float toReturn = price / prices.size();
return (!Float.isNaN(toReturn) ? toReturn : 0); return (!Float.isNaN(toReturn) ? toReturn : 0);
} }
/*public static float generateAverageSellPrice(int itemID){ private static float generateAverageBuyPrice(int itemID) {
return generateAveragePrice(itemID, false); return generateAveragePrice(itemID);
}*/
public static float generateAverageBuyPrice(int itemID) {
return generateAveragePrice(itemID, true);
} }
public static void generateItemStats(int itemID) throws IOException { private static void generateItemStats(int itemID) throws IOException {
double total = generateItemTotal(itemID); double total = generateItemTotal(itemID);
if (total == 0) { if (total == 0) return;
return;
}
double bought = generateTotalBought(itemID); double bought = generateTotalBought(itemID);
double sold = generateTotalSold(itemID); double sold = generateTotalSold(itemID);
@ -123,17 +111,14 @@ public class Generator implements Runnable {
.replace("%pricePerItem", String.valueOf(buyPrice))); .replace("%pricePerItem", String.valueOf(buyPrice)));
} }
public static void generateStats() { private static void generateStats() {
try { try {
fileStart(); fileStart();
buf = new BufferedWriter(new FileWriter(filePath, true)); buf = new BufferedWriter(new FileWriter(filePath, true));
long genTime = System.currentTimeMillis(); long genTime = System.currentTimeMillis();
for (Material m : Material.values()) generateItemStats(m.getId());
for (Material m : Material.values()) {
generateItemStats(m.getId());
}
buf.close(); buf.close();
generationTime = (System.currentTimeMillis() - genTime) / 1000; generationTime = (System.currentTimeMillis() - genTime) / 1000;

View File

@ -11,7 +11,7 @@ import java.util.List;
* @author Acrobot * @author Acrobot
*/ */
public class Queue implements Runnable { public class Queue implements Runnable {
private static List<Transaction> queue = new LinkedList<Transaction>(); private static final List<Transaction> queue = new LinkedList<Transaction>();
public static void addToQueue(Transaction t) { public static void addToQueue(Transaction t) {
queue.add(t); queue.add(t);

View File

@ -1,5 +1,6 @@
package com.Acrobot.ChestShop; package com.Acrobot.ChestShop;
import com.Acrobot.ChestShop.Utils.uLongName;
import com.nijikokun.register.payment.forChestShop.Method; import com.nijikokun.register.payment.forChestShop.Method;
/** /**
@ -10,23 +11,23 @@ public class Economy {
public static Method economy; public static Method economy;
public static boolean hasAccount(String p) { public static boolean hasAccount(String p) {
return economy.hasAccount(p); return economy.hasAccount(uLongName.getName(p));
} }
public static void add(String name, float amount) { 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) { 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) { 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) { public static double balance(String name) {
return economy.getAccount(name).balance(); return economy.getAccount(uLongName.getName(name)).balance();
} }
public static String formatBalance(double amount) { public static String formatBalance(double amount) {

View File

@ -9,11 +9,9 @@ import org.bukkit.material.*;
/** /**
* @author Acrobot * @author Acrobot
*/ */
public class DataValue { class DataValue {
public static byte get(String arg, Material material) { public static byte get(String arg, Material material) {
if (material == null) { if (material == null) return 0;
return 0;
}
arg = arg.toUpperCase().replace(" ", "_"); arg = arg.toUpperCase().replace(" ", "_");

View File

@ -12,12 +12,12 @@ public class Items {
public static Material getMaterial(String itemName) { public static Material getMaterial(String itemName) {
if (uNumber.isInteger(itemName)) return Material.getMaterial(Integer.parseInt(itemName)); if (uNumber.isInteger(itemName)) return Material.getMaterial(Integer.parseInt(itemName));
int length = 256; int length = 256;
Material finalMat = null; Material finalMat = null;
itemName = itemName.toLowerCase().replace("_", "").replace(" ", ""); itemName = itemName.toLowerCase().replace("_", "").replace(" ", "");
for (Material m : Material.values()) { 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)) { if (matName.startsWith(itemName) && (matName.length() < length)) {
length = matName.length(); length = matName.length();
finalMat = m; finalMat = m;
@ -28,12 +28,10 @@ public class Items {
public static ItemStack getItemStack(String itemName) { public static ItemStack getItemStack(String itemName) {
ItemStack toReturn; ItemStack toReturn;
if ((toReturn = getFromOddItem(itemName)) != null) { if ((toReturn = getFromOddItem(itemName)) != null) return toReturn;
return toReturn;
}
Material material = getMaterial(itemName); Material material = getMaterial(itemName);
if(material != null) return new ItemStack(material, 1); if (material != null) return new ItemStack(material, 1);
return getItemStackWithDataValue(itemName); return getItemStackWithDataValue(itemName);
} }
@ -43,23 +41,20 @@ public class Items {
return Odd.returnItemStack(itemName.replace(":", ";")); return Odd.returnItemStack(itemName.replace(":", ";"));
} }
private static ItemStack getItemStackWithDataValue(String itemName){ private static ItemStack getItemStackWithDataValue(String itemName) {
if(!itemName.contains(":")) return getItemStackWithDataValueFromWord(itemName); if (!itemName.contains(":")) return getItemStackWithDataValueFromWord(itemName);
String[] word = itemName.split(":"); 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]); Material item = getMaterial(word[0]);
if(item == null) return null; return item == null ? null : new ItemStack(item, 1, Short.parseShort(word[1]));
short dataValue = Short.parseShort(word[1]);
return new ItemStack(item, 1, dataValue);
} }
private static ItemStack getItemStackWithDataValueFromWord(String itemName) { private static ItemStack getItemStackWithDataValueFromWord(String itemName) {
if (!itemName.contains(" ") || getMaterial(itemName) != null) return null; if (!itemName.contains(" ") || getMaterial(itemName) != null) return null;
String[] word = itemName.split(" "); String[] word = itemName.split(" ");
if(word.length < 2) return null; if (word.length < 2) return null;
String dataValue = word[0]; String dataValue = word[0];
@ -67,9 +62,7 @@ public class Items {
System.arraycopy(word, 1, material, 0, word.length - 1); System.arraycopy(word, 1, material, 0, word.length - 1);
StringBuilder mat = new StringBuilder(); StringBuilder mat = new StringBuilder();
for(String s : material){ for (String s : material) mat.append(s);
mat.append(s);
}
Material item = getMaterial(mat.toString()); Material item = getMaterial(mat.toString());

View File

@ -1,43 +1,49 @@
package com.Acrobot.ChestShop.Listeners; 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.Permission;
import com.Acrobot.ChestShop.Restrictions.RestrictedSign;
import com.Acrobot.ChestShop.Utils.uBlock; import com.Acrobot.ChestShop.Utils.uBlock;
import com.Acrobot.ChestShop.Utils.uLongName;
import com.Acrobot.ChestShop.Utils.uSign; import com.Acrobot.ChestShop.Utils.uSign;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.Sign; import org.bukkit.block.Sign;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockListener; import org.bukkit.event.block.BlockListener;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
/** /**
* @author Acrobot * @author Acrobot
*/ */
public class blockBreak extends BlockListener { 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) { public void onBlockBreak(BlockBreakEvent event) {
Block block = event.getBlock(); if (cancellingBlockBreak(event.getBlock(), event.getPlayer())) event.setCancelled(true);
Player player = event.getPlayer(); }
boolean isAdmin = Permission.has(player, Permission.ADMIN); public void onBlockPistonExtend(BlockPistonExtendEvent event) {
if (!Config.getBoolean(Property.USE_BUILT_IN_PROTECTION)) return;
if (isAdmin) { for (Block b : event.getBlocks()){
return; if (cancellingBlockBreak(b, null)) event.setCancelled(true); 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);
}
} }
} }
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
if (!Config.getBoolean(Property.USE_BUILT_IN_PROTECTION)) return;
if (cancellingBlockBreak(event.getRetractLocation().getBlock(), null)) event.setCancelled(true);
}
} }

View File

@ -5,9 +5,10 @@ import com.Acrobot.ChestShop.Config.Language;
import com.Acrobot.ChestShop.Config.Property; import com.Acrobot.ChestShop.Config.Property;
import com.Acrobot.ChestShop.Permission; import com.Acrobot.ChestShop.Permission;
import com.Acrobot.ChestShop.Protection.Default; 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.Shop.ShopManagement;
import com.Acrobot.ChestShop.Utils.uBlock; import com.Acrobot.ChestShop.Utils.uBlock;
import com.Acrobot.ChestShop.Utils.uLongName;
import com.Acrobot.ChestShop.Utils.uSign; import com.Acrobot.ChestShop.Utils.uSign;
import net.minecraft.server.IInventory; import net.minecraft.server.IInventory;
import net.minecraft.server.InventoryLargeChest; import net.minecraft.server.InventoryLargeChest;
@ -21,7 +22,6 @@ import org.bukkit.entity.Player;
import org.bukkit.event.block.Action; import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerListener; import org.bukkit.event.player.PlayerListener;
import org.bukkit.inventory.Inventory;
import java.util.HashMap; import java.util.HashMap;
@ -30,18 +30,15 @@ import java.util.HashMap;
*/ */
public class playerInteract extends PlayerListener { public class playerInteract extends PlayerListener {
private HashMap<Player, Long> time = new HashMap<Player, Long>(); private static final HashMap<Player, Long> lastTransactionTime = new HashMap<Player, Long>();
public static int interval = 100; private static final int interval = 100;
public void onPlayerInteract(PlayerInteractEvent event) { public void onPlayerInteract(PlayerInteractEvent event) {
Action action = event.getAction(); 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(); Block block = event.getClickedBlock();
Player player = event.getPlayer();
if (Config.getBoolean(Property.USE_BUILT_IN_PROTECTION) && block.getType() == Material.CHEST) { if (Config.getBoolean(Property.USE_BUILT_IN_PROTECTION) && block.getType() == Material.CHEST) {
Default protection = new Default(); Default protection = new Default();
@ -52,49 +49,38 @@ public class playerInteract extends PlayerListener {
} }
} }
if (!uSign.isSign(block)) { if (!uSign.isSign(block)) return;
return;
}
Sign sign = (Sign) block.getState(); 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()) { lastTransactionTime.put(player, System.currentTimeMillis());
return;
}
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); Chest chest1 = uBlock.findChest(sign);
if (chest1 == null) { if (chest1 == null) {
player.sendMessage(Config.getLocal(Language.NO_CHEST_DETECTED)); player.sendMessage(Config.getLocal(Language.NO_CHEST_DETECTED));
return; return;
} }
Inventory inv1 = chest1.getInventory(); IInventory inventory = ((CraftInventory) chest1.getInventory()).getInventory();
IInventory iInv1 = ((CraftInventory) inv1).getInventory();
Chest chest2 = uBlock.findNeighbor(chest1); Chest chest2 = uBlock.findNeighbor(chest1);
if (chest2 != null) { if (chest2 != null) {
Inventory inv2 = chest2.getInventory(); IInventory iInv2 = ((CraftInventory) chest2.getInventory()).getInventory();
IInventory iInv2 = ((CraftInventory) inv2).getInventory(); inventory = new InventoryLargeChest(player.getName() + "'s Shop", inventory, iInv2);
IInventory largeChest = new InventoryLargeChest(player.getName() + "'s Shop", iInv1, iInv2);
((CraftPlayer) player).getHandle().a(largeChest);
} else {
((CraftPlayer) player).getHandle().a(iInv1);
} }
((CraftPlayer) player).getHandle().a(inventory);
return; return;
} }
if (RestrictedSign.isRestricted(sign)) { if (restrictedSign.isRestrictedShop(sign) && !restrictedSign.canAccess(sign, player)) {
if (!RestrictedSign.canAccess(sign, player)) { player.sendMessage(Config.getLocal(Language.ACCESS_DENIED));
player.sendMessage(Config.getLocal(Language.ACCESS_DENIED)); return;
return;
}
} }
Action buy = (Config.getBoolean(Property.REVERSE_BUTTONS) ? Action.LEFT_CLICK_BLOCK : Action.RIGHT_CLICK_BLOCK); Action buy = (Config.getBoolean(Property.REVERSE_BUTTONS) ? Action.LEFT_CLICK_BLOCK : Action.RIGHT_CLICK_BLOCK);

View File

@ -23,8 +23,7 @@ import org.yi.acru.bukkit.Lockette.Lockette;
*/ */
public class pluginEnable extends ServerListener { 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) { public void onPluginEnable(PluginEnableEvent event) {

View File

@ -7,8 +7,9 @@ import com.Acrobot.ChestShop.Items.Items;
import com.Acrobot.ChestShop.Permission; import com.Acrobot.ChestShop.Permission;
import com.Acrobot.ChestShop.Protection.Default; import com.Acrobot.ChestShop.Protection.Default;
import com.Acrobot.ChestShop.Protection.Security; 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.uBlock;
import com.Acrobot.ChestShop.Utils.uLongName;
import com.Acrobot.ChestShop.Utils.uNumber; import com.Acrobot.ChestShop.Utils.uNumber;
import com.Acrobot.ChestShop.Utils.uSign; import com.Acrobot.ChestShop.Utils.uSign;
import org.bukkit.Material; import org.bukkit.Material;
@ -33,21 +34,13 @@ public class signChange extends BlockListener {
Boolean isAlmostReady = uSign.isValidPreparedSign(event.getLines()); Boolean isAlmostReady = uSign.isValidPreparedSign(event.getLines());
Player player = event.getPlayer(); Player player = event.getPlayer();
ItemStack stock = Items.getItemStack(line[3]); ItemStack stock = Items.getItemStack(line[3]);
Material mat = stock == null ? null : stock.getType(); Material mat = stock == null ? null : stock.getType();
boolean playerIsAdmin = Permission.has(player, Permission.ADMIN); boolean playerIsAdmin = Permission.has(player, Permission.ADMIN);
if (isAlmostReady) { if (isAlmostReady) {
if (player.getName().length() > 15) {
player.sendMessage(Config.getLocal(Language.NAME_TOO_LONG));
dropSign(event);
return;
}
if (mat == null) { if (mat == null) {
player.sendMessage(Config.getLocal(Language.INCORRECT_ITEM_ID)); player.sendMessage(Config.getLocal(Language.INCORRECT_ITEM_ID));
dropSign(event); dropSign(event);
@ -63,13 +56,13 @@ public class signChange extends BlockListener {
return; return;
} }
} else { } else {
if (RestrictedSign.isRestricted(event.getLines())) { if (restrictedSign.isRestricted(event.getLines())) {
if (!playerIsAdmin) { if (!playerIsAdmin) {
player.sendMessage(Config.getLocal(Language.ACCESS_DENIED)); player.sendMessage(Config.getLocal(Language.ACCESS_DENIED));
dropSign(event); dropSign(event);
return; return;
} }
Block secondSign = signBlock.getFace(BlockFace.DOWN); Block secondSign = signBlock.getRelative(BlockFace.DOWN);
if (!uSign.isSign(secondSign) || !uSign.isValid((Sign) secondSign.getState())) { if (!uSign.isSign(secondSign) || !uSign.isValid((Sign) secondSign.getState())) {
dropSign(event); dropSign(event);
} }
@ -84,7 +77,7 @@ public class signChange extends BlockListener {
} }
line = event.getLines(); line = event.getLines();
boolean isAdminShop = uSign.isAdminShop(line[0]); boolean isAdminShop = uSign.isAdminShop(line[0]);
if (!isReady) { if (!isReady) {
@ -155,10 +148,11 @@ public class signChange extends BlockListener {
player.sendMessage(Config.getLocal(Language.PROTECTED_SHOP)); player.sendMessage(Config.getLocal(Language.PROTECTED_SHOP));
} }
uLongName.saveName(player.getName());
player.sendMessage(Config.getLocal(Language.SHOP_CREATED)); player.sendMessage(Config.getLocal(Language.SHOP_CREATED));
} }
public static void dropSign(SignChangeEvent event) { private static void dropSign(SignChangeEvent event) {
event.setCancelled(true); event.setCancelled(true);
Block block = event.getBlock(); Block block = event.getBlock();

View File

@ -3,6 +3,7 @@ package com.Acrobot.ChestShop.Logging;
import com.Acrobot.ChestShop.ChestShop; import com.Acrobot.ChestShop.ChestShop;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter; import java.io.FileWriter;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
@ -11,8 +12,8 @@ import java.util.List;
* @author Acrobot * @author Acrobot
*/ */
public class FileWriterQueue implements Runnable { public class FileWriterQueue implements Runnable {
private static List<String> queue = new LinkedList<String>(); private static final List<String> queue = new LinkedList<String>();
public static String filePath = ChestShop.folder + "/ChestShop.log"; private static final String filePath = new File(ChestShop.folder, "ChestShop.log").getPath();
public static void addToQueue(String message) { public static void addToQueue(String message) {
queue.add(message); queue.add(message);

View File

@ -11,30 +11,32 @@ import org.bukkit.inventory.ItemStack;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
/** /**
* @author Acrobot * @author Acrobot
*/ */
public class Logging { 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(); Date date = new Date();
return dateFormat.format(date); return dateFormat.format(date);
} }
public static void log(String string) { public static void log(String string) {
if (Config.getBoolean(Property.LOG_TO_CONSOLE)) { if (Config.getBoolean(Property.LOG_TO_CONSOLE)) logger.log(Level.INFO,"[ChestShop] " + string);
System.out.println("[ChestShop] " + string); if (Config.getBoolean(Property.LOG_TO_FILE)) FileWriterQueue.addToQueue(getDateAndTime() + ' ' + string);
}
FileWriterQueue.addToQueue(getDateAndTime() + ' ' + string);
} }
public static void logTransaction(boolean isBuying, Shop shop, Player player) { 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); 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)) { if (Config.getBoolean(Property.LOG_TO_DATABASE)) logToDatabase(isBuying, shop, player);
return; }
}
private static void logToDatabase(boolean isBuying, Shop shop, Player player){
Transaction transaction = new Transaction(); Transaction transaction = new Transaction();
transaction.setAmount(shop.stockAmount); transaction.setAmount(shop.stockAmount);

View File

@ -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);
}
}

View File

@ -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<String, Option> names = new HashMap<String, Option>();
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);
}
}
}

View File

@ -23,16 +23,13 @@ public enum Permission {
public static PermissionHandler permissions; public static PermissionHandler permissions;
public static boolean has(Player player, Permission permission) { public static boolean has(Player player, Permission permission) {
String node = permission.permission; return has(player, permission.permission);
return has(player, node);
} }
public static boolean has(Player player, String node) { public static boolean has(Player player, String node) {
if (permissions != null) { //return !node.contains("exclude") && !node.contains ("create.") && ((!node.contains("admin") && !node.contains("mod")) || player.isOp());
return permissions.has(player, node); if (permissions != null) return permissions.has(player, node);
} else { return player.hasPermission(node);
return !node.contains("exclude") && ((!node.contains("admin") && !node.contains("mod")) || player.isOp());
}
} }
public String toString() { public String toString() {

View File

@ -1,6 +1,7 @@
package com.Acrobot.ChestShop.Protection; package com.Acrobot.ChestShop.Protection;
import com.Acrobot.ChestShop.Utils.uBlock; import com.Acrobot.ChestShop.Utils.uBlock;
import com.Acrobot.ChestShop.Utils.uLongName;
import com.Acrobot.ChestShop.Utils.uSign; import com.Acrobot.ChestShop.Utils.uSign;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.Chest; import org.bukkit.block.Chest;
@ -12,30 +13,25 @@ import org.bukkit.entity.Player;
*/ */
public class Default implements Protection { public class Default implements Protection {
public boolean isProtected(Block block) { public boolean isProtected(Block block) {
if ((uSign.isSign(block) && uSign.isValid((Sign) block.getState())) || uBlock.findSign(block) != null) { if ((uSign.isSign(block) && uSign.isValid((Sign) block.getState())) || uBlock.findSign(block) != null) return true;
return true; if (!(block.getState() instanceof Chest)) return false;
} 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;
}
}
return false; Chest neighbor = uBlock.findNeighbor(block);
return neighbor != null && uBlock.findSign(neighbor.getBlock()) != null;
} }
public boolean canAccess(Player player, Block block) { public boolean canAccess(Player player, Block block) {
Sign sign = uBlock.findSign(block); Sign sign = uBlock.findSign(block);
Chest nChest = uBlock.findNeighbor(block); Chest neighborChest = uBlock.findNeighbor(block);
Sign nSign = (nChest != null ? uBlock.findSign(nChest.getBlock()) : null); Sign neighborSign = (neighborChest != null ? uBlock.findSign(neighborChest.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())); 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) { public boolean protect(String name, Block block) {

View File

@ -15,7 +15,8 @@ public class LockettePlugin implements Protection {
} }
public boolean canAccess(Player player, Block block) { 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) { public boolean protect(String name, Block block) {

View File

@ -5,6 +5,7 @@ import com.Acrobot.ChestShop.Utils.uBlock;
import com.Acrobot.ChestShop.Utils.uSign; import com.Acrobot.ChestShop.Utils.uSign;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockFace; import org.bukkit.block.BlockFace;
import org.bukkit.block.Chest; import org.bukkit.block.Chest;
@ -14,12 +15,13 @@ import org.bukkit.entity.Player;
* @author Acrobot * @author Acrobot
*/ */
public class MaskChest implements Runnable { 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() { public void run() {
Player[] players = ChestShop.getBukkitServer().getOnlinePlayers(); Player[] players = ChestShop.getBukkitServer().getOnlinePlayers();
for (Player player : players) { for (Player player : players) {
World world = player.getWorld();
Location location = player.getLocation(); Location location = player.getLocation();
int pX = location.getBlockX(); int pX = location.getBlockX();
@ -31,7 +33,7 @@ public class MaskChest implements Runnable {
for (int x = -radius; x < radius; x++) { for (int x = -radius; x < radius; x++) {
for (int y = -radius; y < radius; y++) { for (int y = -radius; y < radius; y++) {
for (int z = -radius; z < radius; z++) { 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 (block.getType() == Material.CHEST) {
if (uBlock.findSign(block) != null) { 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) { for (BlockFace face : bf) {
Block faceBlock = block.getFace(face); Block faceBlock = block.getRelative(face);
Material type = faceBlock.getType(); Material type = faceBlock.getType();
if (type != Material.AIR && !uSign.isSign(faceBlock) && type != Material.CHEST) { if (type != Material.AIR && !uSign.isSign(faceBlock) && type != Material.CHEST) return type;
return type;
}
} }
return Material.CHEST; return Material.CHEST;
} }

View File

@ -18,45 +18,45 @@ import org.bukkit.inventory.ItemStack;
* @author Acrobot * @author Acrobot
*/ */
public class Shop { public class Shop {
public ItemStack stock; public final ItemStack stock;
public short durability; private final short durability;
public int stockAmount; public final int stockAmount;
public ChestObject chest; private final ChestObject chest;
public float buyPrice; public final float buyPrice;
public float sellPrice; public final float sellPrice;
public String owner; 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.stock = itemStacks[0];
this.durability = stock.getDurability(); this.durability = stock.getDurability();
this.chest = chest; this.chest = chest;
this.buyPrice = uSign.buyPrice(sign.getLine(2)); this.buyPrice = (buy ? uSign.buyPrice(sign.getLine(2)) : -1);
this.sellPrice = uSign.sellPrice(sign.getLine(2)); this.sellPrice = (!buy ? uSign.sellPrice(sign.getLine(2)) : -1);
this.owner = sign.getLine(0); this.owner = sign.getLine(0);
this.stockAmount = uSign.itemAmount(sign.getLine(1)); this.stockAmount = uSign.itemAmount(sign.getLine(1));
} }
public boolean buy(Player player) { public void buy(Player player) {
if (chest == null && !isAdminShop()) { if (chest == null && !isAdminShop()) {
player.sendMessage(Config.getLocal(Language.NO_CHEST_DETECTED)); player.sendMessage(Config.getLocal(Language.NO_CHEST_DETECTED));
return false; return;
} }
if (buyPrice == -1) { if (buyPrice == -1) {
player.sendMessage(Config.getLocal(Language.NO_BUYING_HERE)); player.sendMessage(Config.getLocal(Language.NO_BUYING_HERE));
return false; return;
} }
if (!Permission.has(player, Permission.BUY)) { if (!Permission.has(player, Permission.BUY)) {
player.sendMessage(Config.getLocal(Language.NO_PERMISSION)); player.sendMessage(Config.getLocal(Language.NO_PERMISSION));
return false; return;
} }
String playerName = player.getName(); String playerName = player.getName();
if (!Economy.hasEnough(playerName, buyPrice)) { if (!Economy.hasEnough(playerName, buyPrice)) {
player.sendMessage(Config.getLocal(Language.NOT_ENOUGH_MONEY)); player.sendMessage(Config.getLocal(Language.NOT_ENOUGH_MONEY));
return false; return;
} }
if (!stockFitsPlayer(player)) { if (!stockFitsPlayer(player)) {
player.sendMessage(Config.getLocal(Language.NOT_ENOUGH_SPACE_IN_INVENTORY)); player.sendMessage(Config.getLocal(Language.NOT_ENOUGH_SPACE_IN_INVENTORY));
return false; return;
} }
String materialName = stock.getType().name(); String materialName = stock.getType().name();
@ -64,18 +64,16 @@ public class Shop {
if (!isAdminShop() && !hasEnoughStock()) { if (!isAdminShop() && !hasEnoughStock()) {
player.sendMessage(Config.getLocal(Language.NOT_ENOUGH_STOCK)); player.sendMessage(Config.getLocal(Language.NOT_ENOUGH_STOCK));
sendMessageToOwner(Config.getLocal(Language.NOT_ENOUGH_STOCK_IN_YOUR_SHOP).replace("%material", materialName)); sendMessageToOwner(Config.getLocal(Language.NOT_ENOUGH_STOCK_IN_YOUR_SHOP).replace("%material", materialName));
return false; return;
} }
String account = getOwnerAccount(); String account = getOwnerAccount();
if (!account.isEmpty() && Economy.hasAccount(account)) { if (!account.isEmpty() && Economy.hasAccount(account)) Economy.add(account, buyPrice);
Economy.add(account, buyPrice);
}
Economy.substract(playerName, buyPrice); Economy.substract(playerName, buyPrice);
if (!isAdminShop()) { if (!isAdminShop()) chest.removeItem(stock, durability, stockAmount);
chest.removeItem(stock, durability, stockAmount);
}
String formatedPrice = Economy.formatBalance(buyPrice); String formatedPrice = Economy.formatBalance(buyPrice);
player.sendMessage(Config.getLocal(Language.YOU_BOUGHT_FROM_SHOP) player.sendMessage(Config.getLocal(Language.YOU_BOUGHT_FROM_SHOP)
.replace("%amount", String.valueOf(stockAmount)) .replace("%amount", String.valueOf(stockAmount))
@ -92,49 +90,42 @@ public class Shop {
.replace("%item", materialName) .replace("%item", materialName)
.replace("%buyer", playerName) .replace("%buyer", playerName)
.replace("%price", formatedPrice)); .replace("%price", formatedPrice));
return true;
} }
public boolean sell(Player player) { public void sell(Player player) {
if (chest == null && !isAdminShop()) { if (chest == null && !isAdminShop()) {
player.sendMessage(Config.getLocal(Language.NO_CHEST_DETECTED)); player.sendMessage(Config.getLocal(Language.NO_CHEST_DETECTED));
return false; return;
} }
if (sellPrice == -1) { if (sellPrice == -1) {
player.sendMessage(Config.getLocal(Language.NO_SELLING_HERE)); player.sendMessage(Config.getLocal(Language.NO_SELLING_HERE));
return false; return;
} }
if (!Permission.has(player, Permission.SELL)) { if (!Permission.has(player, Permission.SELL)) {
player.sendMessage(Config.getLocal(Language.NO_PERMISSION)); player.sendMessage(Config.getLocal(Language.NO_PERMISSION));
return false; return;
} }
String account = getOwnerAccount(); String account = getOwnerAccount();
boolean accountExists = !account.isEmpty() && Economy.hasAccount(account); boolean accountExists = !account.isEmpty() && Economy.hasAccount(account);
if (accountExists) { if (accountExists && !Economy.hasEnough(account, sellPrice)) {
if (!Economy.hasEnough(account, sellPrice)) { player.sendMessage(Config.getLocal(Language.NOT_ENOUGH_MONEY_SHOP));
player.sendMessage(Config.getLocal(Language.NOT_ENOUGH_MONEY_SHOP)); return;
return false;
}
} }
if (!isAdminShop() && !stockFitsChest(chest)) { if (!isAdminShop() && !stockFitsChest(chest)) {
player.sendMessage(Config.getLocal(Language.NOT_ENOUGH_SPACE_IN_CHEST)); player.sendMessage(Config.getLocal(Language.NOT_ENOUGH_SPACE_IN_CHEST));
return false; return;
} }
if (uInventory.amount(player.getInventory(), stock, durability) < stockAmount) { if (uInventory.amount(player.getInventory(), stock, durability) < stockAmount) {
player.sendMessage(Config.getLocal(Language.NOT_ENOUGH_ITEMS_TO_SELL)); player.sendMessage(Config.getLocal(Language.NOT_ENOUGH_ITEMS_TO_SELL));
return false; return;
} }
if (accountExists) { if (accountExists) Economy.substract(account, sellPrice);
Economy.substract(account, sellPrice); if (!isAdminShop()) chest.addItem(stock, stockAmount);
}
if (!isAdminShop()) {
chest.addItem(stock, stockAmount);
}
Economy.add(player.getName(), sellPrice); Economy.add(player.getName(), sellPrice);
@ -156,17 +147,10 @@ public class Shop {
.replace("%item", materialName) .replace("%item", materialName)
.replace("%seller", player.getName()) .replace("%seller", player.getName())
.replace("%price", formatedBalance)); .replace("%price", formatedBalance));
return true;
} }
private String getOwnerAccount() { private String getOwnerAccount() {
if (uSign.isAdminShop(owner)) { return uSign.isAdminShop(owner) ? Config.getString(Property.SERVER_ECONOMY_ACCOUNT) : owner;
return Config.getString(Property.SERVER_ECONOMY_ACCOUNT);
} else {
return owner;
}
} }
private boolean isAdminShop() { private boolean isAdminShop() {

View File

@ -13,27 +13,25 @@ import org.bukkit.inventory.ItemStack;
* @author Acrobot * @author Acrobot
*/ */
public class ShopManagement { public class ShopManagement {
public static boolean buy(Sign sign, Player player) { public static void buy(Sign sign, Player player) {
Chest chestMc = uBlock.findChest(sign); Chest chestMc = uBlock.findChest(sign);
ItemStack item = Items.getItemStack(sign.getLine(3)); ItemStack item = Items.getItemStack(sign.getLine(3));
if (item == null) { if (item == null) {
player.sendMessage(ChatColor.RED + "[Shop] The item is not recognised!"); 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); Shop shop = new Shop(chestMc != null ? new MinecraftChest(chestMc) : null, true, sign, item);
shop.buy(player);
return shop.buy(player);
} }
public static boolean sell(Sign sign, Player player) { public static void sell(Sign sign, Player player) {
Chest chestMc = uBlock.findChest(sign); Chest chestMc = uBlock.findChest(sign);
ItemStack item = Items.getItemStack(sign.getLine(3)); ItemStack item = Items.getItemStack(sign.getLine(3));
if (item == null) { if (item == null) {
player.sendMessage(ChatColor.RED + "[Shop] The item is not recognised!"); 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); Shop shop = new Shop(chestMc != null ? new MinecraftChest(chestMc) : null, false, sign, item);
shop.sell(player);
return shop.sell(player);
} }
} }

View File

@ -1,4 +1,4 @@
package com.Acrobot.ChestShop.Restrictions; package com.Acrobot.ChestShop.Signs;
import com.Acrobot.ChestShop.Permission; import com.Acrobot.ChestShop.Permission;
import com.Acrobot.ChestShop.Utils.uSign; import com.Acrobot.ChestShop.Utils.uSign;
@ -10,9 +10,9 @@ import org.bukkit.entity.Player;
/** /**
* @author Acrobot * @author Acrobot
*/ */
public class RestrictedSign { public class restrictedSign {
public static boolean isRestricted(Sign sign) { public static boolean isRestrictedShop(Sign sign) {
Block blockUp = sign.getBlock().getFace(BlockFace.UP); Block blockUp = sign.getBlock().getRelative(BlockFace.UP);
return uSign.isSign(blockUp) && isRestricted(((Sign) blockUp.getState()).getLines()); return uSign.isSign(blockUp) && isRestricted(((Sign) blockUp.getState()).getLines());
} }
@ -20,20 +20,22 @@ public class RestrictedSign {
return lines[0].equalsIgnoreCase("[restricted]"); 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) { public static boolean canAccess(Sign sign, Player player) {
Block blockUp = sign.getBlock().getFace(BlockFace.UP); Block blockUp = sign.getBlock().getRelative(BlockFace.UP);
if (Permission.permissions == null || !uSign.isSign(blockUp) || Permission.has(player, Permission.ADMIN)) { if (Permission.permissions == null || !uSign.isSign(blockUp) || Permission.has(player, Permission.ADMIN)) return true;
return true;
}
String world = blockUp.getWorld().getName(); String world = blockUp.getWorld().getName();
String playerName = player.getName(); String playerName = player.getName();
sign = (Sign) blockUp.getState(); sign = (Sign) blockUp.getState();
boolean result = false;
for (int i = 1; i <= 3; i++) { 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;
} }
} }

View File

@ -1,5 +1,6 @@
package com.Acrobot.ChestShop.Utils; package com.Acrobot.ChestShop.Utils;
import com.Acrobot.ChestShop.Signs.restrictedSign;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockFace; import org.bukkit.block.BlockFace;
@ -11,8 +12,8 @@ import org.bukkit.block.Sign;
*/ */
public class uBlock { public class uBlock {
static BlockFace[] chestFaces = {BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST, BlockFace.SOUTH}; private static final 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[] shopFaces = {BlockFace.DOWN, BlockFace.UP, BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST, BlockFace.SOUTH, BlockFace.SELF};
public static Chest findChest(Sign sign) { public static Chest findChest(Sign sign) {
Block block = sign.getBlock(); Block block = sign.getBlock();
@ -21,7 +22,7 @@ public class uBlock {
public static Chest findChest(Block block) { public static Chest findChest(Block block) {
for (BlockFace bf : shopFaces) { for (BlockFace bf : shopFaces) {
Block faceBlock = block.getFace(bf); Block faceBlock = block.getRelative(bf);
if (faceBlock.getType() == Material.CHEST) { if (faceBlock.getType() == Material.CHEST) {
return (Chest) faceBlock.getState(); return (Chest) faceBlock.getState();
} }
@ -31,7 +32,7 @@ public class uBlock {
public static Sign findSign(Block block) { public static Sign findSign(Block block) {
for (BlockFace bf : shopFaces) { for (BlockFace bf : shopFaces) {
Block faceBlock = block.getFace(bf); Block faceBlock = block.getRelative(bf);
if (uSign.isSign(faceBlock)) { if (uSign.isSign(faceBlock)) {
Sign sign = (Sign) faceBlock.getState(); Sign sign = (Sign) faceBlock.getState();
if (uSign.isValid(sign)) { if (uSign.isValid(sign)) {
@ -42,9 +43,22 @@ public class uBlock {
return null; 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) { public static Chest findNeighbor(Block block) {
for (BlockFace blockFace : chestFaces) { for (BlockFace blockFace : chestFaces) {
Block neighborBlock = block.getFace(blockFace); Block neighborBlock = block.getRelative(blockFace);
if (neighborBlock.getType() == Material.CHEST) { if (neighborBlock.getType() == Material.CHEST) {
return (Chest) neighborBlock.getState(); return (Chest) neighborBlock.getState();
} }

View File

@ -17,19 +17,13 @@ public class uInventory {
Material itemMaterial = item.getType(); Material itemMaterial = item.getType();
int first = inv.first(itemMaterial); int first = inv.first(itemMaterial);
if (first == -1) { if (first == -1) return amount;
return amount;
}
for (int slot = first; slot < inv.getSize(); slot++) { for (int slot = first; slot < inv.getSize(); slot++) {
if (amount <= 0) { if (amount <= 0) return 0;
return 0;
}
ItemStack currentItem = inv.getItem(slot); ItemStack currentItem = inv.getItem(slot);
if (currentItem == null || currentItem.getType() == Material.AIR) { if (currentItem == null || currentItem.getType() == Material.AIR) continue;
continue;
}
if (currentItem.getType() == itemMaterial && (durability == -1 || currentItem.getDurability() == durability)) { if (currentItem.getType() == itemMaterial && (durability == -1 || currentItem.getDurability() == durability)) {
int currentAmount = currentItem.getAmount(); int currentAmount = currentItem.getAmount();
@ -53,8 +47,7 @@ public class uInventory {
public static int add(Inventory inv, ItemStack item, int amount) { public static int add(Inventory inv, ItemStack item, int amount) {
amount = (amount > 0 ? amount : 1); amount = (amount > 0 ? amount : 1);
Material itemMaterial = item.getType(); int maxStackSize = item.getType().getMaxStackSize();
int maxStackSize = itemMaterial.getMaxStackSize();
if (amount <= maxStackSize) { if (amount <= maxStackSize) {
item.setAmount(amount); item.setAmount(amount);
@ -66,7 +59,6 @@ public class uInventory {
for (int i = 0; i < Math.ceil(amount / maxStackSize); i++) { for (int i = 0; i < Math.ceil(amount / maxStackSize); i++) {
if (amount <= maxStackSize) { if (amount <= maxStackSize) {
item.setAmount(amount); item.setAmount(amount);
items.add(item);
return 0; return 0;
} else { } else {
item.setAmount(maxStackSize); item.setAmount(maxStackSize);
@ -75,25 +67,17 @@ public class uInventory {
} }
amount = 0; amount = 0;
for (ItemStack itemToAdd : items) { for (ItemStack itemToAdd : items) amount += (!inv.addItem(itemToAdd).isEmpty() ? itemToAdd.getAmount() : 0);
amount += (!inv.addItem(itemToAdd).isEmpty() ? itemToAdd.getAmount() : 0);
}
return amount; return amount;
} }
public static int amount(Inventory inv, ItemStack item, short durability) { public static int amount(Inventory inv, ItemStack item, short durability) {
if (!inv.contains(item.getType())) return 0;
int amount = 0; int amount = 0;
if (!inv.contains(item.getType())) { for (ItemStack i : inv.getContents()) {
return amount; if (i != null && i.getType() == item.getType() && (durability == -1 || i.getDurability() == durability)) amount += i.getAmount();
}
ItemStack[] contents = inv.getContents();
for (ItemStack i : contents) {
if (i != null) {
if (i.getType() == item.getType() && (durability == -1 || i.getDurability() == durability)) {
amount += i.getAmount();
}
}
} }
return amount; return amount;
} }
@ -101,13 +85,10 @@ public class uInventory {
public static int fits(Inventory inv, ItemStack item, int amount, short durability) { public static int fits(Inventory inv, ItemStack item, int amount, short durability) {
Material itemMaterial = item.getType(); Material itemMaterial = item.getType();
int maxStackSize = itemMaterial.getMaxStackSize(); int maxStackSize = itemMaterial.getMaxStackSize();
int amountLeft = amount; int amountLeft = amount;
for (ItemStack currentItem : inv.getContents()) { for (ItemStack currentItem : inv.getContents()) {
if (amountLeft <= 0) { if (amountLeft <= 0) return 0;
return 0;
}
if (currentItem == null || currentItem.getType() == Material.AIR) { if (currentItem == null || currentItem.getType() == Material.AIR) {
amountLeft -= maxStackSize; amountLeft -= maxStackSize;

View File

@ -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();
}
}

View File

@ -11,10 +11,7 @@ import java.util.regex.Pattern;
* @author Acrobot * @author Acrobot
*/ */
public class uSign { public class uSign {
private static final Pattern[] patterns = {
//static Pattern firstLine = Pattern.compile("^[A-Za-z0-9].+$");
static Pattern[] patterns = {
Pattern.compile("^$|^\\w.+$"), Pattern.compile("^$|^\\w.+$"),
Pattern.compile("[0-9]+"), Pattern.compile("[0-9]+"),
Pattern.compile(".+"), Pattern.compile(".+"),
@ -56,16 +53,16 @@ public class uSign {
public static float buyPrice(String text) { public static float buyPrice(String text) {
text = text.replace(" ", "").toLowerCase(); 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(":"); String[] split = text.split(":");
if (uNumber.isFloat(split[0])) { int buyPart = (text.contains("b") ? (split[0].contains("b") ? 0 : 1) : -1);
float buyPrice = Float.parseFloat(split[0]); 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); return (buyPrice != 0 ? buyPrice : -1);
} else if (split[0].equals("free")) { } else if (split[buyPart].equals("free")) {
return 0; return 0;
} }
@ -75,14 +72,12 @@ public class uSign {
public static float sellPrice(String text) { public static float sellPrice(String text) {
text = text.replace(" ", "").toLowerCase(); 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(":"); 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)) { split[sellPart] = split[sellPart].replace("s", "");
return -1;
}
if (uNumber.isFloat(split[sellPart])) { if (uNumber.isFloat(split[sellPart])) {
Float sellPrice = Float.parseFloat(split[sellPart]); Float sellPrice = Float.parseFloat(split[sellPart]);
return (sellPrice != 0 ? sellPrice : -1); return (sellPrice != 0 ? sellPrice : -1);
@ -96,8 +91,6 @@ public class uSign {
if (uNumber.isInteger(text)) { if (uNumber.isInteger(text)) {
int amount = Integer.parseInt(text); int amount = Integer.parseInt(text);
return (amount >= 1 ? amount : 1); return (amount >= 1 ? amount : 1);
} else { } else return 1;
return 1;
}
} }
} }

View File

@ -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<Class<?>> 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<String> scriptLines = new ArrayList<String>();
//Create some additional variables for keeping track of tables
HashMap<String, Integer> foundTables = new HashMap<String, Integer>();
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<Class<?>> getDatabaseClasses() {
return new ArrayList<Class<?>>();
}
/**
* 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;
}
}

View File

@ -53,7 +53,7 @@ public class Methods {
return Dependencies; return Dependencies;
} }
public Method createMethod(Plugin plugin) { Method createMethod(Plugin plugin) {
for (Method method: Methods) { for (Method method: Methods) {
if (method.isCompatible(plugin)) { if (method.isCompatible(plugin)) {
method.setPlugin(plugin); method.setPlugin(plugin);
@ -82,7 +82,7 @@ public class Methods {
Plugin plugin; Plugin plugin;
PluginManager manager = method.getServer().getPluginManager(); PluginManager manager = method.getServer().getPluginManager();
for(String name: this.getDependencies()) { for(String name: this.Dependencies) {
if(hasMethod()) break; if(hasMethod()) break;
if(method.getDescription().getName().equals(name)) plugin = method; else plugin = manager.getPlugin(name); if(method.getDescription().getName().equals(name)) plugin = method; else plugin = manager.getPlugin(name);
if(plugin == null) continue; if(plugin == null) continue;

View File

@ -59,7 +59,7 @@ public class BOSE6 implements Method {
BOSEconomy = (BOSEconomy)plugin; BOSEconomy = (BOSEconomy)plugin;
} }
public class BOSEAccount implements MethodAccount { public static class BOSEAccount implements MethodAccount {
private String name; private String name;
private BOSEconomy BOSEconomy; private BOSEconomy BOSEconomy;
@ -69,7 +69,7 @@ public class BOSE6 implements Method {
} }
public double balance() { public double balance() {
return Double.valueOf(this.BOSEconomy.getPlayerMoney(this.name)); return (double) this.BOSEconomy.getPlayerMoney(this.name);
} }
public boolean set(double amount) { 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 String bank;
private BOSEconomy BOSEconomy; private BOSEconomy BOSEconomy;
@ -139,7 +139,7 @@ public class BOSE6 implements Method {
} }
public double balance() { public double balance() {
return Double.valueOf(this.BOSEconomy.getBankMoney(bank)); return (double) this.BOSEconomy.getBankMoney(bank);
} }
public boolean set(double amount) { public boolean set(double amount) {

View File

@ -63,7 +63,7 @@ public class BOSE7 implements Method {
BOSEconomy = (BOSEconomy)plugin; BOSEconomy = (BOSEconomy)plugin;
} }
public class BOSEAccount implements MethodAccount { public static class BOSEAccount implements MethodAccount {
private String name; private String name;
private BOSEconomy BOSEconomy; 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 String bank;
private BOSEconomy BOSEconomy; private BOSEconomy BOSEconomy;

View File

@ -64,7 +64,7 @@ public class EE17 implements Method {
Essentials = (Essentials)plugin; Essentials = (Essentials)plugin;
} }
public class EEcoAccount implements MethodAccount { public static class EEcoAccount implements MethodAccount {
private String name; private String name;
public EEcoAccount(String name) { public EEcoAccount(String name) {

View File

@ -23,7 +23,7 @@ public class iCo4 implements Method {
} }
public String format(double amount) { public String format(double amount) {
return this.iConomy.getBank().format(amount); return iConomy.getBank().format(amount);
} }
public boolean hasBanks() { public boolean hasBanks() {
@ -35,7 +35,7 @@ public class iCo4 implements Method {
} }
public boolean hasAccount(String name) { public boolean hasAccount(String name) {
return this.iConomy.getBank().hasAccount(name); return iConomy.getBank().hasAccount(name);
} }
public boolean hasBankAccount(String bank, String name) { public boolean hasBankAccount(String bank, String name) {
@ -43,7 +43,7 @@ public class iCo4 implements Method {
} }
public MethodAccount getAccount(String name) { 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) { public MethodBankAccount getBankAccount(String bank, String name) {
@ -58,7 +58,7 @@ public class iCo4 implements Method {
iConomy = (iConomy)plugin; iConomy = (iConomy)plugin;
} }
public class iCoAccount implements MethodAccount { public static class iCoAccount implements MethodAccount {
private Account account; private Account account;
public iCoAccount(Account account) { public iCoAccount(Account account) {

View File

@ -26,7 +26,7 @@ public class iCo5 implements Method {
} }
public String format(double amount) { public String format(double amount) {
return this.iConomy.format(amount); return iConomy.format(amount);
} }
public boolean hasBanks() { public boolean hasBanks() {
@ -34,23 +34,23 @@ public class iCo5 implements Method {
} }
public boolean hasBank(String bank) { public boolean hasBank(String bank) {
return (!hasBanks()) ? false : this.iConomy.Banks.exists(bank); return (hasBanks()) && iConomy.Banks.exists(bank);
} }
public boolean hasAccount(String name) { public boolean hasAccount(String name) {
return this.iConomy.hasAccount(name); return iConomy.hasAccount(name);
} }
public boolean hasBankAccount(String bank, String 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) { 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) { 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) { public boolean isCompatible(Plugin plugin) {
@ -61,7 +61,7 @@ public class iCo5 implements Method {
iConomy = (iConomy)plugin; iConomy = (iConomy)plugin;
} }
public class iCoAccount implements MethodAccount { public static class iCoAccount implements MethodAccount {
private Account account; private Account account;
private Holdings holdings; 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 BankAccount account;
private Holdings holdings; private Holdings holdings;

View File

@ -2,8 +2,7 @@ name: ChestShop
main: com.Acrobot.ChestShop.ChestShop main: com.Acrobot.ChestShop.ChestShop
database: true version: 3.00 BETA 10
version: 3.00 BETA 9
author: Acrobot author: Acrobot
@ -21,9 +20,33 @@ commands:
description: Shows the ChestShop's version description: Shows the ChestShop's version
usage: | usage: |
/<command> /<command>
chestOptions:
aliases: [coptions,cop,cpref] permissions:
description: Sets ChestShop's preferences - Not implemented yet ChestShop.*:
usage: | description: Gives access to all ChestShop permissions
/<command> (option) (value) default: op
() - optional 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