Yay, it's almost relased!

This commit is contained in:
Acrobot 2011-06-09 22:54:01 +02:00
parent 444b09fe1a
commit 677fe9668b
28 changed files with 626 additions and 342 deletions

View File

@ -3,12 +3,13 @@ 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.Options;
import com.Acrobot.ChestShop.Commands.Version; import com.Acrobot.ChestShop.Commands.Version;
import com.Acrobot.ChestShop.Config.Config;
import com.Acrobot.ChestShop.DB.Generator;
import com.Acrobot.ChestShop.DB.Queue; 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.Logging.Logging;
import com.Acrobot.ChestShop.Utils.Config;
import com.avaje.ebean.EbeanServer; import com.avaje.ebean.EbeanServer;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.event.Event; import org.bukkit.event.Event;
@ -32,7 +33,10 @@ public class ChestShop extends JavaPlugin {
private final blockBreak blockBreak = new blockBreak(); private final blockBreak blockBreak = new blockBreak();
private final blockPlace blockPlace = new blockPlace(); private final blockPlace blockPlace = new blockPlace();
private final signChange signChange = new signChange(); private final signChange signChange = new signChange();
private final playerInteract playerInteract = new playerInteract(); private final playerInteract playerInteract = new playerInteract();
public static File folder;
public static EbeanServer db;
private static PluginDescriptionFile desc; private static PluginDescriptionFile desc;
private static Server server; private static Server server;
@ -53,18 +57,26 @@ public class ChestShop extends JavaPlugin {
//Set up our config file! //Set up our config file!
Config.setUp(); Config.setUp();
//Yep, set up our folder!
folder = getDataFolder();
//Now set up our database for storing transactions! //Now set up our database for storing transactions!
setupDBfile(); setupDBfile();
if(Config.getBoolean("useDB")){ if (Config.getBoolean("useDB")) {
setupDB(); setupDB();
getServer().getScheduler().scheduleAsyncRepeatingTask(this, new Queue(), 200L, 200L); getServer().getScheduler().scheduleAsyncRepeatingTask(this, new Queue(), 200L, 200L);
if (Config.getBoolean("generateStatisticsPage")) {
getServer().getScheduler().scheduleAsyncRepeatingTask(this, new Generator(), 300L, 300L);
}
db = getDatabase();
} }
//Now set up our logging to file! //Now set up our logging to file!
if(Config.getBoolean("logToFile")){ if (Config.getBoolean("logToFile")) {
getServer().getScheduler().scheduleAsyncRepeatingTask(this, new FileWriterQueue(), 201L, 201L); getServer().getScheduler().scheduleAsyncRepeatingTask(this, new FileWriterQueue(), 201L, 201L);
} }
//Register our commands! //Register our commands!
getCommand("iteminfo").setExecutor(new ItemInfo()); getCommand("iteminfo").setExecutor(new ItemInfo());
@ -91,10 +103,10 @@ public class ChestShop extends JavaPlugin {
private static void setupDBfile() { private static void setupDBfile() {
File file = new File("ebean.properties"); File file = new File("ebean.properties");
if(!file.exists()){ if (!file.exists()) {
try{ try {
file.createNewFile(); file.createNewFile();
} catch (Exception e){ } catch (Exception e) {
Logging.log("Failed to create ebean.properties file!"); Logging.log("Failed to create ebean.properties file!");
} }
} }
@ -120,7 +132,7 @@ public class ChestShop extends JavaPlugin {
return desc.getName(); return desc.getName();
} }
public static EbeanServer getDB(){ public static EbeanServer getDB() {
return new ChestShop().getDatabase(); return db;
} }
} }

View File

@ -72,7 +72,7 @@ public class MinecraftChest implements ChestObject {
public boolean fits(ItemStack item, int amount, short durability) { public boolean fits(ItemStack item, int amount, short durability) {
int firstChest = fits(item, amount, durability, main); int firstChest = fits(item, amount, durability, main);
return (firstChest > 0 && neighbor != null ? fits(item, amount, durability, neighbor) <= 0 : firstChest <= 0); return (firstChest > 0 && neighbor != null ? fits(item, firstChest, durability, neighbor) <= 0 : firstChest <= 0);
} }
public int getSize() { public int getSize() {

View File

@ -1,7 +1,7 @@
package com.Acrobot.ChestShop.Commands; package com.Acrobot.ChestShop.Commands;
import com.Acrobot.ChestShop.Config.Config;
import com.Acrobot.ChestShop.Items.Items; import com.Acrobot.ChestShop.Items.Items;
import com.Acrobot.ChestShop.Utils.Config;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;

View File

@ -1,73 +1,29 @@
package com.Acrobot.ChestShop.Commands; package com.Acrobot.ChestShop.Commands;
import com.Acrobot.ChestShop.Utils.Config; import com.Acrobot.ChestShop.Options.Option;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.HashMap;
/** /**
* @author Acrobot * @author Acrobot
*/ */
public class Options implements CommandExecutor { public class Options implements CommandExecutor {
public boolean balance;
public boolean outOfStock;
public boolean someoneBought;
public Options() {
this.balance = true;
this.outOfStock = true;
this.someoneBought = true;
}
public static boolean exists(String name) { public static boolean exists(String name) {
name = name.toLowerCase(); name = name.toLowerCase();
return name.equals("balance") || name.equals("outofstock") || name.equals("someonebought"); return Option.getOption(name) != null;
} }
public boolean getOption(String name) {
name = name.toLowerCase();
if (name.equals("balance")) {
return balance;
}
if (name.equals("outofstock")) {
return outOfStock;
}
if (name.equals("someonebought")) {
return someoneBought;
}
return false;
}
public boolean setOption(String name, boolean value) {
if (name.equals("balance")) {
balance = value;
return true;
}
if (name.equals("outofstock")) {
outOfStock = value;
return true;
}
if (name.equals("someonebought")) {
someoneBought = value;
return true;
}
return false;
}
public static HashMap<Player, Options> playerPreferences = new HashMap<Player, Options>();
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (!(sender instanceof Player)) { return false;
/*if (!(sender instanceof Player)) {
return false; return false;
} }
Player player = (Player) sender; Player player = (Player) sender;
if (!playerPreferences.containsKey(player)) { if (!playerpref.containsKey(player)) {
playerPreferences.put(player, new Options()); setDefault(player);
} }
if (args.length == 0) { if (args.length == 0) {
@ -82,21 +38,20 @@ public class Options implements CommandExecutor {
} }
if (args.length == 1) { if (args.length == 1) {
Options options = playerPreferences.get(player);
Boolean exists = exists(args[0]); Boolean exists = exists(args[0]);
if (!exists) { if (!exists) {
return false; return false;
} }
player.sendMessage(Config.getColored("&a" + args[0] + " is set to: " + options.getOption(args[0]))); player.sendMessage(Config.getColored("&a" + args[0] + " is set to: " + playerpref.get(player).getOption(args[0])));
return true; return true;
} }
if (args.length == 2) { if (args.length == 2) {
try { try {
Boolean option = Boolean.parseBoolean(args[1]); Boolean option = Boolean.parseBoolean(args[1]);
Options options = playerPreferences.get(player); Options options = playerpref.get(player);
Boolean exists = exists(args[0]); Boolean exists = exists(args[0]);
if (!exists) { if (!exists) {
@ -107,6 +62,7 @@ public class Options implements CommandExecutor {
if (!success) { if (!success) {
return false; return false;
} }
playerpref.put(player, Option.va)
player.sendMessage(Config.getColored("&aSuccessfully set " + args[0] + " to " + args[1])); player.sendMessage(Config.getColored("&aSuccessfully set " + args[0] + " to " + args[1]));
return true; return true;
@ -115,7 +71,7 @@ public class Options implements CommandExecutor {
} }
} }
return false; return false;*/
} }
private static String[] optionList() { private static String[] optionList() {

View File

@ -1,4 +1,4 @@
package com.Acrobot.ChestShop.Utils; package com.Acrobot.ChestShop.Config;
import com.Acrobot.ChestShop.Logging.Logging; import com.Acrobot.ChestShop.Logging.Logging;
import org.bukkit.util.config.Configuration; import org.bukkit.util.config.Configuration;
@ -22,18 +22,33 @@ public class Config {
public static void setUp() { public static void setUp() {
if (!configFile.exists()) { config.load();
try { for (DefaultValue def : DefaultValue.values()){
configFile.createNewFile(); if(config.getProperty(def.name()) == null){
Logging.log("Successfully created blank configuration file"); writeToFile(def.name() + ": " + def.getValue() + " #" + def.getComment(), configFile);
} catch (Exception e) {
Logging.log("Couldn't create configuration file!");
} }
} }
config.load(); config.load();
language.load();
for (DefaultLanguage def : DefaultLanguage.values()) {
if (language.getProperty(def.name()) == null) {
writeToFile(def.name() + ": \"" + def.toString() + "\"", langFile);
}
}
language.load(); language.load();
Defaults.set();
}
public static void writeToFile(String string, File file) {
try {
FileWriter fw = new FileWriter(file, true);
fw.write('\n' + string);
fw.close();
} catch (Exception e) {
Logging.log("Couldn't write to file - " + file.getName());
}
} }
public static boolean getBoolean(String node) { public static boolean getBoolean(String node) {
@ -54,17 +69,8 @@ public class Config {
private static Object getValue(String node, Configuration configuration, File file) { private static Object getValue(String node, Configuration configuration, File file) {
if (configuration.getProperty(node) == null) { if (configuration.getProperty(node) == null) {
try { writeToFile(DefaultLanguage.lookup(node).toString(), file);
Object defaultValue = defaultValues.get(node); configuration.load();
if (defaultValue != null) {
FileWriter fw = new FileWriter(file, true);
fw.write('\n' + node + ": " + defaultValue);
fw.close();
}
configuration.load();
} catch (Exception e) {
Logging.log("Failed to update config file!");
}
} }
return configuration.getProperty(node); return configuration.getProperty(node);
} }
@ -82,6 +88,10 @@ public class Config {
} }
private static Object getDefaultLocal(String node) { private static Object getDefaultLocal(String node) {
return getValue(node, language, langFile); if (language.getProperty(node) == null) {
writeToFile(DefaultLanguage.lookup(node).toString(), langFile);
language.load();
}
return language.getString(node);
} }
} }

View File

@ -0,0 +1,65 @@
package com.Acrobot.ChestShop.Config;
import java.util.HashMap;
import java.util.Map;
/**
* @author Acrobot
*/
public enum DefaultLanguage {
prefix("&a[Shop] &f"),
iteminfo("&aItem Information:&f"),
options("&aCustomizable options: "),
ACCESS_DENIED("You don't have permission to do that!"),
NOT_ENOUGH_MONEY("You have got not enough money!"),
NOT_ENOUGH_MONEY_SHOP("Shop owner doesn't have enough money!"),
NO_BUYING_HERE("You can't buy here!"),
NO_SELLING_HERE("You can't sell here!"),
NOT_ENOUGH_SPACE_IN_INVENTORY("You haven't got enough space in inventory!"),
NOT_ENOUGH_SPACE_IN_CHEST("There isn't enough space in chest!"),
NOT_ENOUGH_ITEMS_TO_SELL("You have got not enough items to sell!"),
NOT_ENOUGH_STOCK("This shop has not enough stock."),
NOT_ENOUGH_STOCK_IN_YOUR_SHOP("Your %material shop is out of stock!"),
YOU_BOUGHT_FROM_SHOP("You bought %amount %item from %owner for %price."),
SOMEBODY_BOUGHT_FROM_YOUR_SHOP("%buyer bought %amount %item for %price from you."),
YOU_SOLD_TO_SHOP("You sold %amount %item to %buyer for %price."),
SOMEBODY_SOLD_TO_YOUR_SHOP("%seller sold %amount %item for %price to you."),
YOU_CANNOT_CREATE_SHOP("You can't create this type of shop!"),
NO_CHEST_DETECTED("Couldn't find a chest!"),
ANOTHER_SHOP_DETECTED("Another player's shop detected!"),
PROTECTED_SHOP("Successfully protected the shop!"),
SHOP_CREATED("Shop successfully created!"),
INCORRECT_ITEM_ID("You have specified invalid item id!");
private String text;
private static final Map<String, DefaultLanguage> names = new HashMap<String, DefaultLanguage>();
private DefaultLanguage(String def) {
text = def;
}
public String toString() {
return text;
}
public static DefaultLanguage lookup(String name) {
return names.get(name);
}
static {
for (DefaultLanguage def : values()) {
names.put(def.name(), def);
}
}
}

View File

@ -0,0 +1,50 @@
package com.Acrobot.ChestShop.Config;
import java.util.HashMap;
import java.util.Map;
/**
* @author Acrobot
*/
public enum DefaultValue {
reverse_buttons(false, "If true, people will buy with left-click and sell with right-click."),
serverEconomyAccount("", "Economy account's name you want Admin Shops to be assigned to"),
logToFile(false, "If true, plugin will log transactions in its own file"),
useDB(false, "If true, plugin will log transactions in EBean database"),
adminShopName("Admin Shop", "First line of your admin shop should look like this"),
generateStatisticsPage(false, "If true, plugin will generate shop statistics webpage."),
DBtimeToLive(600, "How long should transaction information be stored?"),
logToConsole(true, "Do you want ChestShop's messages to show up in console?");
private Object value;
private String comment;
private static final Map<String, DefaultValue> names = new HashMap<String, DefaultValue>();
private DefaultValue(Object value, String comment) {
this.value = value;
this.comment = comment;
}
public Object getValue() {
return (value instanceof String ? "\"" + value + "\"" : value);
}
public String getComment() {
return comment;
}
public String toString() {
return name();
}
public static DefaultValue lookup(String name) {
return names.get(name);
}
static {
for (DefaultValue def : values()) {
names.put(def.name(), def);
}
}
}

View File

@ -0,0 +1,143 @@
package com.Acrobot.ChestShop.DB;
import com.Acrobot.ChestShop.ChestShop;
import com.Acrobot.ChestShop.Logging.Logging;
import org.bukkit.Material;
import java.io.*;
import java.util.List;
/**
* @author Acrobot
*/
public class Generator implements Runnable {
private static String filePath = ChestShop.folder + "/website.html";
private static double generationTime;
private static String header = fileToString("header");
private static String row = fileToString("row");
private static String footer = fileToString("footer");
private static BufferedWriter buf;
public void run() {
generateStats();
}
public static void fileStart() throws IOException {
FileWriter fw = new FileWriter(filePath);
fw.write(header);
fw.close();
}
public static void fileEnd() throws IOException {
FileWriter fw = new FileWriter(filePath, true);
fw.write(footer.replace("%time", String.valueOf(generationTime)));
fw.close();
}
public static String fileToString(String fileName) {
try {
File f = new File(ChestShop.folder + "/HTML/" + fileName + ".html");
FileReader rd = new FileReader(f);
char[] buf = new char[(int) f.length()];
rd.read(buf);
return new String(buf);
} catch (Exception e) {
return "";
}
}
public static double generateItemTotal(int itemID, boolean bought, boolean sold) {
double amount = 0;
List<Transaction> list;
if (bought) {
list = ChestShop.getDB().find(Transaction.class).where().eq("buy", 1).eq("itemID", itemID).findList();
} else if (sold) {
list = ChestShop.getDB().find(Transaction.class).where().eq("buy", 0).eq("itemID", itemID).findList();
} else {
list = ChestShop.getDB().find(Transaction.class).where().eq("itemID", itemID).findList();
}
for (Transaction t : list) {
amount += t.getAmount();
}
return amount;
}
public static double generateTotalBought(int itemID) {
return generateItemTotal(itemID, true, false);
}
public static double generateTotalSold(int itemID) {
return generateItemTotal(itemID, false, true);
}
public static double generateItemTotal(int itemID) {
return generateItemTotal(itemID, false, false);
}
public static float generateAveragePrice(int itemID, boolean buy) {
float price = 0;
List<Transaction> prices = ChestShop.getDB().find(Transaction.class).where().eq("itemID", itemID).eq("buy", buy).findList();
for (Transaction t : prices) {
price += t.getAveragePricePerItem();
}
float toReturn = price / prices.size();
return (!Float.isNaN(toReturn) ? toReturn : 0);
}
/*public static float generateAverageSellPrice(int itemID){
return generateAveragePrice(itemID, false);
}*/
public static float generateAverageBuyPrice(int itemID) {
return generateAveragePrice(itemID, true);
}
public static void generateItemStats(int itemID) throws IOException {
double total = generateItemTotal(itemID);
if (total == 0) {
return;
}
double bought = generateTotalBought(itemID);
double sold = generateTotalSold(itemID);
Material material = Material.getMaterial(itemID);
String matName = material.name().replace("_", " ").toLowerCase();
int maxStackSize = material.getMaxStackSize();
float buyPrice = generateAverageBuyPrice(itemID);
buf.write(row.replace("%material", matName)
.replace("%total", String.valueOf(total))
.replace("%bought", String.valueOf(bought))
.replace("%sold", String.valueOf(sold))
.replace("%maxStackSize", String.valueOf(maxStackSize))
.replace("%pricePerStack", String.valueOf((buyPrice * maxStackSize)))
.replace("%pricePerItem", String.valueOf(buyPrice)));
}
public static void generateStats() {
try {
fileStart();
buf = new BufferedWriter(new FileWriter(filePath, true));
long genTime = System.currentTimeMillis();
for (Material m : Material.values()) {
generateItemStats(m.getId());
}
buf.close();
generationTime = (System.currentTimeMillis() - genTime) / 1000;
fileEnd();
} catch (Exception e) {
Logging.log("Couldn't generate statistics page!");
}
}
}

View File

@ -1,7 +1,7 @@
package com.Acrobot.ChestShop.DB; package com.Acrobot.ChestShop.DB;
import com.Acrobot.ChestShop.ChestShop; import com.Acrobot.ChestShop.ChestShop;
import com.Acrobot.ChestShop.Utils.Config; import com.Acrobot.ChestShop.Config.Config;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
@ -12,17 +12,12 @@ import java.util.List;
public class Queue implements Runnable { public class Queue implements Runnable {
private static List<Transaction> queue = new LinkedList<Transaction>(); private static List<Transaction> queue = new LinkedList<Transaction>();
public static void addToQueue(Transaction t){ public static void addToQueue(Transaction t) {
queue.add(t); queue.add(t);
} }
public static void saveQueue() {
ChestShop.getBukkitServer().getScheduler().scheduleAsyncDelayedTask(new ChestShop(), new Queue());
ChestShop.getBukkitServer().broadcastMessage("Successfully saved queue!");
}
public void run() { public void run() {
List<Transaction> toDelete = ChestShop.getDB().find(Transaction.class).where().lt("sec", System.currentTimeMillis()/1000 - Config.getInteger("DBtimeToLive")).findList(); List<Transaction> toDelete = ChestShop.getDB().find(Transaction.class).where().lt("sec", System.currentTimeMillis() / 1000 - Config.getInteger("DBtimeToLive")).findList();
ChestShop.getDB().delete(toDelete); ChestShop.getDB().delete(toDelete);
ChestShop.getDB().save(queue); ChestShop.getDB().save(queue);
queue.clear(); queue.clear();

View File

@ -1,10 +1,33 @@
package com.Acrobot.ChestShop.Listeners; package com.Acrobot.ChestShop.Listeners;
import com.Acrobot.ChestShop.Permission;
import com.Acrobot.ChestShop.Utils.SearchForBlock;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockListener; import org.bukkit.event.block.BlockListener;
/** /**
* @author Acrobot * @author Acrobot
*/ */
public class blockBreak extends BlockListener { public class blockBreak extends BlockListener {
public void onBlockBreak(BlockBreakEvent event) {
Block block = event.getBlock();
Player player = event.getPlayer();
boolean isAdmin = Permission.has(player, Permission.ADMIN);
if (isAdmin) {
return;
}
Sign sign = SearchForBlock.findSign(block);
if (sign != null) {
if (!player.getName().startsWith(sign.getLine(0))) {
event.setCancelled(true);
}
}
}
} }

View File

@ -1,9 +1,9 @@
package com.Acrobot.ChestShop.Listeners; package com.Acrobot.ChestShop.Listeners;
import com.Acrobot.ChestShop.Messaging.Message; import com.Acrobot.ChestShop.Config.Config;
import com.Acrobot.ChestShop.Permission;
import com.Acrobot.ChestShop.Protection.Security; import com.Acrobot.ChestShop.Protection.Security;
import com.Acrobot.ChestShop.Shop.ShopManagement; import com.Acrobot.ChestShop.Shop.ShopManagement;
import com.Acrobot.ChestShop.Utils.Config;
import com.Acrobot.ChestShop.Utils.SearchForBlock; import com.Acrobot.ChestShop.Utils.SearchForBlock;
import com.Acrobot.ChestShop.Utils.SignUtil; import com.Acrobot.ChestShop.Utils.SignUtil;
import net.minecraft.server.IInventory; import net.minecraft.server.IInventory;
@ -41,8 +41,8 @@ public class playerInteract extends PlayerListener {
Block block = event.getClickedBlock(); Block block = event.getClickedBlock();
if (block.getType() == Material.CHEST) { if (block.getType() == Material.CHEST) {
if (Security.isProtected(block) && !Security.canAccess(player, block)) { if (!Permission.has(player, Permission.ADMIN) && Security.isProtected(block) && !Security.canAccess(player, block)) {
Message.sendMsg(player, "ACCESS_DENIED"); player.sendMessage(Config.getLocal("ACCESS_DENIED"));
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
@ -62,31 +62,35 @@ public class playerInteract extends PlayerListener {
time.put(player, System.currentTimeMillis()); time.put(player, System.currentTimeMillis());
if(player.isSneaking()){ if (player.isSneaking()) {
return; return;
} }
if(player.getName().startsWith(sign.getLine(0))){ if (player.getName().equals(sign.getLine(0))) {
Chest chest1 = SearchForBlock.findChest(sign); Chest chest1 = SearchForBlock.findChest(sign);
if (chest1 == null) {
player.sendMessage(Config.getLocal("NO_CHEST_DETECTED"));
return;
}
Inventory inv1 = chest1.getInventory(); Inventory inv1 = chest1.getInventory();
IInventory iInv1 = ((CraftInventory) inv1).getInventory(); IInventory iInv1 = ((CraftInventory) inv1).getInventory();
Chest chest2 = SearchForBlock.findNeighbor(chest1); Chest chest2 = SearchForBlock.findNeighbor(chest1);
if(chest2 != null){
if (chest2 != null) {
Inventory inv2 = chest2.getInventory(); Inventory inv2 = chest2.getInventory();
IInventory iInv2 = ((CraftInventory) inv2).getInventory(); IInventory iInv2 = ((CraftInventory) inv2).getInventory();
IInventory largeChest = new InventoryLargeChest("Shop", iInv1, iInv2); IInventory largeChest = new InventoryLargeChest(player.getName() + "'s Shop", iInv1, iInv2);
((CraftPlayer) player).getHandle().a(largeChest); ((CraftPlayer) player).getHandle().a(largeChest);
return;
} else if(chest1 != null){
((CraftPlayer) player).getHandle().a(iInv1);
return;
} else { } else {
player.sendMessage(Config.getLocal("NO_CHEST_DETECTED")); ((CraftPlayer) player).getHandle().a(iInv1);
return;
} }
return;
} }
Action buy = (Config.getBoolean("reverse_buttons") ? Action.LEFT_CLICK_BLOCK : Action.RIGHT_CLICK_BLOCK); Action buy = (Config.getBoolean("reverse_buttons") ? Action.LEFT_CLICK_BLOCK : Action.RIGHT_CLICK_BLOCK);
if (action == buy) { if (action == buy) {

View File

@ -1,9 +1,9 @@
package com.Acrobot.ChestShop.Listeners; package com.Acrobot.ChestShop.Listeners;
import com.Acrobot.ChestShop.Config.Config;
import com.Acrobot.ChestShop.Items.Items; import com.Acrobot.ChestShop.Items.Items;
import com.Acrobot.ChestShop.Permission; import com.Acrobot.ChestShop.Permission;
import com.Acrobot.ChestShop.Protection.Security; import com.Acrobot.ChestShop.Protection.Security;
import com.Acrobot.ChestShop.Utils.Config;
import com.Acrobot.ChestShop.Utils.Numerical; import com.Acrobot.ChestShop.Utils.Numerical;
import com.Acrobot.ChestShop.Utils.SearchForBlock; import com.Acrobot.ChestShop.Utils.SearchForBlock;
import com.Acrobot.ChestShop.Utils.SignUtil; import com.Acrobot.ChestShop.Utils.SignUtil;
@ -34,23 +34,21 @@ public class signChange extends BlockListener {
boolean playerIsAdmin = Permission.has(player, Permission.ADMIN); boolean playerIsAdmin = Permission.has(player, Permission.ADMIN);
Permission shopCreation = Permission.SHOP_CREATION;
if (mat == null) {
player.sendMessage(Config.getLocal("INCORRECT_ITEM_ID"));
dropSign(event);
return;
}
if (isAlmostReady) { if (isAlmostReady) {
if (!playerIsAdmin && !(Permission.has(player, shopCreation) if (!playerIsAdmin && !(Permission.has(player, Permission.SHOP_CREATION)
|| ((Permission.has(player, shopCreation.getPermission() + '.' + mat.getId()) || ((Permission.has(player, Permission.SHOP_CREATION + "." + mat.getId())
|| !Permission.has(player, Permission.EXCLUDE_ITEM.getPermission() + '.' + mat.getId()))))) { || !Permission.has(player, Permission.EXCLUDE_ITEM + "." + mat.getId()))))) {
player.sendMessage(Config.getLocal("YOU_CAN'T_CREATE_SHOP")); player.sendMessage(Config.getLocal("YOU_CAN'T_CREATE_SHOP"));
dropSign(event); dropSign(event);
return; return;
} }
if (mat == null) {
player.sendMessage(Config.getLocal("INCORRECT_ITEM_ID"));
dropSign(event);
return;
}
} else { } else {
return; return;
} }

View File

@ -1,5 +1,7 @@
package com.Acrobot.ChestShop.Logging; package com.Acrobot.ChestShop.Logging;
import com.Acrobot.ChestShop.ChestShop;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.FileWriter; import java.io.FileWriter;
import java.util.LinkedList; import java.util.LinkedList;
@ -8,25 +10,27 @@ 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 List<String> queue = new LinkedList<String>();
public static String filePath = "plugins/ChestShop/ChestShop.log"; public static String filePath = ChestShop.folder + "/ChestShop.log";
public static void addToQueue(String message){ public static void addToQueue(String message) {
queue.add(message); queue.add(message);
} }
public void run() { public void run() {
try{ try {
BufferedWriter bw = new BufferedWriter(new FileWriter(filePath, true)); BufferedWriter bw = new BufferedWriter(new FileWriter(filePath, true));
for(String msg : queue){ for (String msg : queue) {
bw.write(msg); bw.write(msg);
bw.newLine(); bw.newLine();
} }
bw.close(); bw.close();
} catch (Exception e){
queue.clear();
} catch (Exception e) {
Logging.log("Couldn't write to log file!"); Logging.log("Couldn't write to log file!");
} }
} }

View File

@ -1,9 +1,9 @@
package com.Acrobot.ChestShop.Logging; package com.Acrobot.ChestShop.Logging;
import com.Acrobot.ChestShop.Config.Config;
import com.Acrobot.ChestShop.DB.Queue; import com.Acrobot.ChestShop.DB.Queue;
import com.Acrobot.ChestShop.DB.Transaction; import com.Acrobot.ChestShop.DB.Transaction;
import com.Acrobot.ChestShop.Shop.Shop; import com.Acrobot.ChestShop.Shop.Shop;
import com.Acrobot.ChestShop.Utils.Config;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@ -21,15 +21,17 @@ public class Logging {
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) {
System.out.println("[ChestShop] " + string); if (Config.getBoolean("logToConsole")) {
System.out.println("[ChestShop] " + string);
}
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("useDB")){ if (!Config.getBoolean("useDB")) {
return; return;
} }
Transaction transaction = new Transaction(); Transaction transaction = new Transaction();
@ -42,7 +44,7 @@ public class Logging {
transaction.setItemDurability(stock.getDurability()); transaction.setItemDurability(stock.getDurability());
transaction.setItemID(stock.getTypeId()); transaction.setItemID(stock.getTypeId());
transaction.setPrice((isBuying ? shop.buyPrice : shop.sellPrice)); transaction.setPrice((isBuying ? shop.buyPrice : shop.sellPrice));
transaction.setSec(System.currentTimeMillis()/1000); transaction.setSec(System.currentTimeMillis() / 1000);
transaction.setShopOwner(shop.owner); transaction.setShopOwner(shop.owner);
transaction.setShopUser(player.getName()); transaction.setShopUser(player.getName());

View File

@ -0,0 +1,39 @@
package com.Acrobot.ChestShop.Options;
import java.util.HashMap;
import java.util.Map;
/**
* @author Acrobot
*/
public enum Option {
BALANCE(true),
OUT_OF_STOCK(true),
SOMEONE_BOUGHT(true);
private boolean enabled;
private static final Map<String, Option> names = new HashMap<String, Option>();
private Option(boolean enabled) {
this.enabled = enabled;
}
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

@ -7,9 +7,9 @@ import org.bukkit.entity.Player;
* @author Acrobot * @author Acrobot
*/ */
public enum Permission { public enum Permission {
SHOP_CREATION("iConomyChestShop.shop.create"), SHOP_CREATION("ChestShop.shop.create"),
EXCLUDE_ITEM("iConomyChestShop.shop.exclude"), EXCLUDE_ITEM("ChestShop.shop.exclude"),
ADMIN("iConomyChestShop.admin"); ADMIN("ChestShop.admin");
private final String permission; private final String permission;
@ -17,10 +17,6 @@ public enum Permission {
this.permission = permission; this.permission = permission;
} }
public String getPermission() {
return 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) {
@ -35,4 +31,8 @@ public enum Permission {
return !node.contains("exclude") && (!node.contains("admin") || player.isOp()); return !node.contains("exclude") && (!node.contains("admin") || player.isOp());
} }
} }
public String toString() {
return permission;
}
} }

View File

@ -1,5 +1,6 @@
package com.Acrobot.ChestShop.Protection; package com.Acrobot.ChestShop.Protection;
import com.Acrobot.ChestShop.Utils.SearchForBlock;
import com.Acrobot.ChestShop.Utils.SignUtil; import com.Acrobot.ChestShop.Utils.SignUtil;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.Sign; import org.bukkit.block.Sign;
@ -10,11 +11,13 @@ 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) {
return (block != null) && SignUtil.isSign(block) && SignUtil.isValid((Sign) block.getState()); Sign sign = SearchForBlock.findSign(block);
return (block != null) && ((SignUtil.isSign(block) && SignUtil.isValid((Sign) block.getState())) || sign != null);
} }
public boolean canAccess(Player player, Block block) { public boolean canAccess(Player player, Block block) {
return (block != null) && SignUtil.isSign(block) && SignUtil.isValid((Sign) block.getState()) && ((Sign) block.getState()).getLine(0).startsWith(player.getName()); Sign sign = SearchForBlock.findSign(block);
return (block != null) && (SignUtil.isSign(block) && SignUtil.isValid((Sign) block.getState()) && ((Sign) block.getState()).getLine(0).equals(player.getName())) || (sign != null && sign.getLine(0).equals(player.getName()));
} }
public boolean protect(String name, Block block) { public boolean protect(String name, Block block) {

View File

@ -2,14 +2,12 @@ package com.Acrobot.ChestShop.Shop;
import com.Acrobot.ChestShop.ChestShop; import com.Acrobot.ChestShop.ChestShop;
import com.Acrobot.ChestShop.Chests.ChestObject; import com.Acrobot.ChestShop.Chests.ChestObject;
import com.Acrobot.ChestShop.Config.Config;
import com.Acrobot.ChestShop.Economy; import com.Acrobot.ChestShop.Economy;
import com.Acrobot.ChestShop.Logging.Logging; import com.Acrobot.ChestShop.Logging.Logging;
import com.Acrobot.ChestShop.Utils.Config;
import com.Acrobot.ChestShop.Utils.InventoryUtil; import com.Acrobot.ChestShop.Utils.InventoryUtil;
import com.Acrobot.ChestShop.Utils.SignUtil; import com.Acrobot.ChestShop.Utils.SignUtil;
import net.minecraft.server.EntityPlayer;
import org.bukkit.block.Sign; import org.bukkit.block.Sign;
import org.bukkit.craftbukkit.entity.CraftPlayer;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@ -34,7 +32,7 @@ public class Shop {
} }
public boolean buy(Player player) { public boolean buy(Player player) {
if(chest == null && !isAdminShop()){ if (chest == null && !isAdminShop()) {
player.sendMessage(Config.getLocal("NO_CHEST_DETECTED")); player.sendMessage(Config.getLocal("NO_CHEST_DETECTED"));
return false; return false;
} }
@ -42,8 +40,12 @@ public class Shop {
player.sendMessage(Config.getLocal("NO_BUYING_HERE")); player.sendMessage(Config.getLocal("NO_BUYING_HERE"));
return false; return false;
} }
String playerName = player.getName();
if (!fits(stock, player)) { if (!Economy.hasEnough(playerName, buyPrice)) {
player.sendMessage(Config.getLocal("NOT_ENOUGH_MONEY"));
return false;
}
if (!stockFitsPlayer(player)) {
player.sendMessage(Config.getLocal("NOT_ENOUGH_SPACE_IN_INVENTORY")); player.sendMessage(Config.getLocal("NOT_ENOUGH_SPACE_IN_INVENTORY"));
return false; return false;
} }
@ -56,15 +58,15 @@ public class Shop {
return false; return false;
} }
if (!getOwner().isEmpty() && Economy.hasAccount(getOwner())) { String account = getOwnerAccount();
Economy.add(getOwner(), buyPrice); if (!account.isEmpty() && Economy.hasAccount(account)) {
Economy.add(account, buyPrice);
} }
Economy.substract(player.getName(), buyPrice); Economy.substract(playerName, buyPrice);
if (!isAdminShop()) { if (!isAdminShop()) {
chest.removeItem(stock, stock.getDurability(), stockAmount); chest.removeItem(stock, stock.getDurability(), stockAmount);
} }
String formatedPrice = Economy.formatBalance(buyPrice); String formatedPrice = Economy.formatBalance(buyPrice);
player.sendMessage(Config.getLocal("YOU_BOUGHT_FROM_SHOP") player.sendMessage(Config.getLocal("YOU_BOUGHT_FROM_SHOP")
.replace("%amount", String.valueOf(stockAmount)) .replace("%amount", String.valueOf(stockAmount))
@ -72,22 +74,20 @@ public class Shop {
.replace("%owner", owner) .replace("%owner", owner)
.replace("%price", formatedPrice)); .replace("%price", formatedPrice));
InventoryUtil.add(player.getInventory(), stock, stockAmount);
Logging.logTransaction(true, this, player);
player.updateInventory();
sendMessageToOwner(Config.getLocal("SOMEBODY_BOUGHT_FROM_YOUR_SHOP") sendMessageToOwner(Config.getLocal("SOMEBODY_BOUGHT_FROM_YOUR_SHOP")
.replace("%amount", String.valueOf(stockAmount)) .replace("%amount", String.valueOf(stockAmount))
.replace("%item", materialName) .replace("%item", materialName)
.replace("%buyer", player.getName()) .replace("%buyer", playerName)
.replace("%price", formatedPrice)); .replace("%price", formatedPrice));
InventoryUtil.add(player.getInventory(), stock, stockAmount);
Logging.logTransaction(true, this, player);
updateInventory(player);
return true; return true;
} }
public boolean sell(Player player) { public boolean sell(Player player) {
if(chest == null && !isAdminShop()){ if (chest == null && !isAdminShop()) {
player.sendMessage(Config.getLocal("NO_CHEST_DETECTED")); player.sendMessage(Config.getLocal("NO_CHEST_DETECTED"));
return false; return false;
} }
@ -95,8 +95,16 @@ public class Shop {
player.sendMessage(Config.getLocal("NO_SELLING_HERE")); player.sendMessage(Config.getLocal("NO_SELLING_HERE"));
return false; return false;
} }
String account = getOwnerAccount();
boolean accountExists = !account.isEmpty() && Economy.hasAccount(account);
if (!isAdminShop() && !fits(stock, chest)) { if (accountExists) {
if (!Economy.hasEnough(account, sellPrice)) {
player.sendMessage(Config.getLocal("NOT_ENOUGH_MONEY_SHOP"));
return false;
}
}
if (!isAdminShop() && !stockFitsChest(chest)) {
player.sendMessage(Config.getLocal("NOT_ENOUGH_SPACE_IN_CHEST")); player.sendMessage(Config.getLocal("NOT_ENOUGH_SPACE_IN_CHEST"));
return false; return false;
} }
@ -106,8 +114,9 @@ public class Shop {
return false; return false;
} }
if (!getOwner().isEmpty() && Economy.hasAccount(getOwner())) {
Economy.substract(getOwner(), sellPrice); if (accountExists) {
Economy.substract(account, sellPrice);
} }
if (!isAdminShop()) { if (!isAdminShop()) {
@ -125,23 +134,23 @@ public class Shop {
.replace("%buyer", owner) .replace("%buyer", owner)
.replace("%price", formatedBalance)); .replace("%price", formatedBalance));
InventoryUtil.remove(player.getInventory(), stock, stockAmount, stock.getDurability());
Logging.logTransaction(false, this, player);
player.updateInventory();
sendMessageToOwner(Config.getLocal("SOMEBODY_SOLD_TO_YOUR_SHOP") sendMessageToOwner(Config.getLocal("SOMEBODY_SOLD_TO_YOUR_SHOP")
.replace("%amount", String.valueOf(stockAmount)) .replace("%amount", String.valueOf(stockAmount))
.replace("%item", materialName) .replace("%item", materialName)
.replace("%seller", player.getName()) .replace("%seller", player.getName())
.replace("%price", formatedBalance)); .replace("%price", formatedBalance));
InventoryUtil.remove(player.getInventory(), stock, stockAmount, stock.getDurability());
Logging.logTransaction(false, this, player);
updateInventory(player);
return true; return true;
} }
private String getOwner() { private String getOwnerAccount() {
if (SignUtil.isAdminShop(owner)) { if (SignUtil.isAdminShop(owner)) {
return Config.getString("shopEconomyAccount"); return Config.getString("serverEconomyAccount");
} else { } else {
return owner; return owner;
} }
@ -155,17 +164,12 @@ public class Shop {
return chest.hasEnough(stock, stockAmount, stock.getDurability()); return chest.hasEnough(stock, stockAmount, stock.getDurability());
} }
private void updateInventory(Player player){ private boolean stockFitsPlayer(Player player) {
EntityPlayer p = ((CraftPlayer) player).getHandle(); return InventoryUtil.fits(player.getInventory(), stock, stockAmount, stock.getDurability()) <= 0;
p.a(p.activeContainer);
} }
private static boolean fits(ItemStack item, Player player) { private boolean stockFitsChest(ChestObject chest) {
return InventoryUtil.fits(player.getInventory(), item, item.getAmount(), item.getDurability()) <= 0; return chest.fits(stock, stockAmount, stock.getDurability());
}
private static boolean fits(ItemStack item, ChestObject chest) {
return chest.fits(item, item.getAmount(), item.getDurability());
} }
private void sendMessageToOwner(String msg) { private void sendMessageToOwner(String msg) {

View File

@ -1,45 +0,0 @@
package com.Acrobot.ChestShop.Utils;
/**
* @author Acrobot
*/
public class Defaults {
public static void set() {
Config.defaultValues.put("reverse_buttons", "false #If true, people buy with left click and sell with right click");
Config.defaultValues.put("shopEconomyAccount", "\"\" #Economy account's name you want Admin Shops to be assigned to");
Config.defaultValues.put("logToFile", "false #If true, plugin will log transactions in its own file");
Config.defaultValues.put("useDB", "false #If true, plugin will log transactions in EBean database");
//LANGUAGE:
Config.defaultValues.put("prefix", "\"&a[Shop] &f\"");
Config.defaultValues.put("iteminfo", "\"&aItem Information:&f\"");
Config.defaultValues.put("options", "\"&aCustomizable options: \"");
Config.defaultValues.put("NO_BUYING_HERE", "\"You can't buy here!\"");
Config.defaultValues.put("NO_SELLING_HERE", "\"You can't sell here!\"");
Config.defaultValues.put("NOT_ENOUGH_SPACE_IN_INVENTORY", "\"You haven't got enough space in inventory!\"");
Config.defaultValues.put("NOT_ENOUGH_SPACE_IN_CHEST", "\"There isn't enough space in chest!\"");
Config.defaultValues.put("NOT_ENOUGH_ITEMS_TO_SELL", "\"You have got not enough items to sell!\"");
Config.defaultValues.put("NOT_ENOUGH_STOCK", "\"This shop has not enough stock.\"");
Config.defaultValues.put("NOT_ENOUGH_STOCK_IN_YOUR_SHOP", "\"Your %material shop is out of stock!\"");
Config.defaultValues.put("YOU_BOUGHT_FROM_SHOP", "\"You bought %amount %item from %owner for %price.\"");
Config.defaultValues.put("SOMEBODY_BOUGHT_FROM_YOUR_SHOP", "\"%buyer bought %amount %item for %price from you.\"");
Config.defaultValues.put("YOU_SOLD_TO_SHOP", "\"You sold %amount %item to %buyer for %price.\"");
Config.defaultValues.put("SOMEBODY_SOLD_TO_YOUR_SHOP", "\"%seller sold %amount %item for %price to you.\"");
Config.defaultValues.put("YOU_CAN'T_CREATE_SHOP", "\"You can't create this type of shop!\"");
Config.defaultValues.put("NO_CHEST_DETECTED", "\"Couldn't find a chest!\"");
Config.defaultValues.put("ANOTHER_SHOP_DETECTED", "\"Another player's shop detected!\"");
Config.defaultValues.put("PROTECTED_SHOP", "\"Successfully protected the shop!\"");
Config.defaultValues.put("SHOP_CREATED", "\"Shop successfully created!\"");
Config.defaultValues.put("INCORRECT_ITEM_ID", "\"You have specified invalid item id!\"");
}
}

View File

@ -4,6 +4,8 @@ import org.bukkit.Material;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
/** /**
* @author Acrobot * @author Acrobot
*/ */
@ -43,46 +45,35 @@ public class InventoryUtil {
} }
public static int add(Inventory inv, ItemStack item, int amount) { public static int add(Inventory inv, ItemStack item, int amount) {
ItemStack[] contents = inv.getContents();
Material itemMaterial = item.getType(); Material itemMaterial = item.getType();
short durability = item.getDurability();
int amountLeft = amount;
int maxStackSize = itemMaterial.getMaxStackSize(); int maxStackSize = itemMaterial.getMaxStackSize();
ItemStack baseItem = item.clone();
for (int slot = 0; slot < contents.length; slot++) { if (amount <= maxStackSize) {
ItemStack itemStack = contents[slot]; item.setAmount(amount);
if (amountLeft <= 0) { inv.addItem(item);
return 0;
}
ArrayList<ItemStack> items = new ArrayList<ItemStack>();
for (int i = 0; i < Math.ceil(amount / maxStackSize); i++) {
if (amount <= maxStackSize) {
item.setAmount(amount);
items.add(item);
return 0; return 0;
} } else {
if (itemStack != null && itemStack.getType() != Material.AIR) { //Our slot is not free item.setAmount(maxStackSize);
int currentAmount = itemStack.getAmount(); items.add(item);
Material currentMaterial = itemStack.getType();
short currentDurability = itemStack.getDurability();
if (currentMaterial == itemMaterial && (currentDurability == durability)) {
if ((currentAmount + amountLeft) <= maxStackSize) {
baseItem.setAmount(currentAmount + amountLeft);
amountLeft = 0;
} else {
baseItem.setAmount(maxStackSize);
amountLeft -= (maxStackSize - currentAmount);
}
inv.setItem(slot, baseItem);
}
} else { //Free slot
if (amountLeft <= maxStackSize) { //There is less to add than whole stack
baseItem.setAmount(amountLeft);
inv.setItem(slot, baseItem);
amountLeft = 0;
} else { //We add whole stack
baseItem.setAmount(maxStackSize);
inv.setItem(slot, baseItem);
amountLeft -= maxStackSize;
}
} }
} }
return amountLeft; Object[] iArray = items.toArray();
amount = 0;
for (Object o : iArray) {
ItemStack itemToAdd = (ItemStack) o;
amount += (!inv.addItem(itemToAdd).isEmpty() ? itemToAdd.getAmount() : 0);
}
return amount;
} }
public static int amount(Inventory inv, ItemStack item, short durability) { public static int amount(Inventory inv, ItemStack item, short durability) {
@ -90,7 +81,7 @@ public class InventoryUtil {
ItemStack[] contents = inv.getContents(); ItemStack[] contents = inv.getContents();
for (ItemStack i : contents) { for (ItemStack i : contents) {
if (i != null) { if (i != null) {
if (i.getType() == item.getType() && (durability == -1 || i.getDurability() == durability || (durability == 0 && i.getDurability() == -1))) { if (i.getType() == item.getType() && (durability == -1 || i.getDurability() == durability)) {
amount += i.getAmount(); amount += i.getAmount();
} }
} }
@ -115,13 +106,9 @@ public class InventoryUtil {
} }
int currentAmount = currentItem.getAmount(); int currentAmount = currentItem.getAmount();
if (currentAmount == itemMaterial.getMaxStackSize()) {
continue;
}
if (currentItem.getType() == itemMaterial && (durability == -1 || currentItem.getDurability() == durability)) { if (currentAmount != maxStackSize && currentItem.getType() == itemMaterial && (durability == -1 || currentItem.getDurability() == durability)) {
currentAmount = currentAmount < 1 ? 1 : currentAmount; amountLeft = ((currentAmount + amountLeft) <= maxStackSize ? 0 : amountLeft - (maxStackSize - currentAmount));
amountLeft = (amountLeft <= currentAmount ? 0 : currentAmount);
} }
} }

View File

@ -38,8 +38,8 @@ public class SearchForBlock {
} }
return null; return null;
} }
public static Chest findNeighbor(Chest chest){ public static Chest findNeighbor(Chest chest) {
BlockFace[] bf = {BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST, BlockFace.SOUTH}; BlockFace[] bf = {BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST, BlockFace.SOUTH};
Block chestBlock = chest.getBlock(); Block chestBlock = chest.getBlock();
for (BlockFace blockFace : bf) { for (BlockFace blockFace : bf) {

View File

@ -1,5 +1,6 @@
package com.Acrobot.ChestShop.Utils; package com.Acrobot.ChestShop.Utils;
import com.Acrobot.ChestShop.Config.Config;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.Sign; import org.bukkit.block.Sign;
@ -14,7 +15,7 @@ public class SignUtil {
} }
public static boolean isAdminShop(String owner) { public static boolean isAdminShop(String owner) {
return owner.toLowerCase().replace(" ", "").equals("adminshop"); return owner.toLowerCase().replace(" ", "").equals(Config.getString("adminShopName").toLowerCase().replace(" ", ""));
} }
public static boolean isValid(Sign sign) { public static boolean isValid(Sign sign) {

View File

@ -12,29 +12,50 @@ import org.bukkit.plugin.Plugin;
*/ */
public interface Method { public interface Method {
public Object getPlugin(); public Object getPlugin();
public String getName(); public String getName();
public String getVersion(); public String getVersion();
public String format(double amount); public String format(double amount);
public boolean hasBanks(); public boolean hasBanks();
public boolean hasBank(String bank); public boolean hasBank(String bank);
public boolean hasAccount(String name); public boolean hasAccount(String name);
public boolean hasBankAccount(String bank, String name); public boolean hasBankAccount(String bank, String name);
public MethodAccount getAccount(String name); public MethodAccount getAccount(String name);
public MethodBankAccount getBankAccount(String bank, String name); public MethodBankAccount getBankAccount(String bank, String name);
public boolean isCompatible(Plugin plugin); public boolean isCompatible(Plugin plugin);
public void setPlugin(Plugin plugin); public void setPlugin(Plugin plugin);
public interface MethodAccount { public interface MethodAccount {
public double balance(); public double balance();
public boolean set(double amount); public boolean set(double amount);
public boolean add(double amount); public boolean add(double amount);
public boolean subtract(double amount); public boolean subtract(double amount);
public boolean multiply(double amount); public boolean multiply(double amount);
public boolean divide(double amount); public boolean divide(double amount);
public boolean hasEnough(double amount); public boolean hasEnough(double amount);
public boolean hasOver(double amount); public boolean hasOver(double amount);
public boolean hasUnder(double amount); public boolean hasUnder(double amount);
public boolean isNegative(); public boolean isNegative();
public boolean remove(); public boolean remove();
@Override @Override
@ -43,17 +64,29 @@ public interface Method {
public interface MethodBankAccount { public interface MethodBankAccount {
public double balance(); public double balance();
public String getBankName(); public String getBankName();
public int getBankId(); public int getBankId();
public boolean set(double amount); public boolean set(double amount);
public boolean add(double amount); public boolean add(double amount);
public boolean subtract(double amount); public boolean subtract(double amount);
public boolean multiply(double amount); public boolean multiply(double amount);
public boolean divide(double amount); public boolean divide(double amount);
public boolean hasEnough(double amount); public boolean hasEnough(double amount);
public boolean hasOver(double amount); public boolean hasOver(double amount);
public boolean hasUnder(double amount); public boolean hasUnder(double amount);
public boolean isNegative(); public boolean isNegative();
public boolean remove(); public boolean remove();
@Override @Override

View File

@ -28,13 +28,13 @@ public class Methods {
/** /**
* Allows you to set which economy plugin is most preferred. * Allows you to set which economy plugin is most preferred.
* *
* @param preferred * @param preferred
*/ */
public Methods(String preferred) { public Methods(String preferred) {
this._init(); this._init();
if(this.Dependencies.contains(preferred)) { if (this.Dependencies.contains(preferred)) {
this.preferred = preferred; this.preferred = preferred;
} }
} }
@ -51,7 +51,7 @@ public class Methods {
} }
public Method createMethod(Plugin plugin) { public 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);
return method; return method;
@ -71,51 +71,55 @@ public class Methods {
} }
public boolean setMethod(Plugin method) { public boolean setMethod(Plugin method) {
if(hasMethod()) return true; if (hasMethod()) return true;
if(self) { self = false; return false; } if (self) {
self = false;
return false;
}
int count = 0; int count = 0;
boolean match = false; boolean match = false;
Plugin plugin = null; Plugin plugin;
PluginManager manager = method.getServer().getPluginManager(); PluginManager manager = method.getServer().getPluginManager();
for(String name: this.Dependencies) { 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;
if(plugin == null) continue; else plugin = manager.getPlugin(name);
if (plugin == null) continue;
if(!plugin.isEnabled()) { if (!plugin.isEnabled()) {
this.self = true; this.self = true;
manager.enablePlugin(plugin); manager.enablePlugin(plugin);
} }
Method current = this.createMethod(plugin); Method current = this.createMethod(plugin);
if(current == null) continue; if (current == null) continue;
if(this.preferred.isEmpty()) if (this.preferred.isEmpty())
this.Method = current; this.Method = current;
else { else {
this.Attachables.add(current); this.Attachables.add(current);
} }
} }
if(!this.preferred.isEmpty()) { if (!this.preferred.isEmpty()) {
do { do {
if(hasMethod()) { if (hasMethod()) {
match = true; match = true;
} else { } else {
for(Method attached: this.Attachables) { for (Method attached : this.Attachables) {
if(attached == null) continue; if (attached == null) continue;
if(hasMethod()) { if (hasMethod()) {
match = true; match = true;
break; break;
} }
if(this.preferred.isEmpty()) this.Method = attached; if (this.preferred.isEmpty()) this.Method = attached;
if(count == 0) { if (count == 0) {
if(this.preferred.equalsIgnoreCase(attached.getName())) if (this.preferred.equalsIgnoreCase(attached.getName()))
this.Method = attached; this.Method = attached;
} else { } else {
this.Method = attached; this.Method = attached;
@ -124,7 +128,7 @@ public class Methods {
count++; count++;
} }
} while(!match); } while (!match);
} }
return hasMethod(); return hasMethod();
@ -135,7 +139,7 @@ public class Methods {
} }
public boolean checkDisabled(Plugin method) { public boolean checkDisabled(Plugin method) {
if(!hasMethod()) return true; if (!hasMethod()) return true;
if (Method.isCompatible(method)) Method = null; if (Method.isCompatible(method)) Method = null;
return (Method == null); return (Method == null);
} }

View File

@ -21,7 +21,7 @@ public class BOSE implements Method {
public String format(double amount) { public String format(double amount) {
String currency = this.BOSEconomy.getMoneyNamePlural(); String currency = this.BOSEconomy.getMoneyNamePlural();
if(amount == 1) currency = this.BOSEconomy.getMoneyName(); if (amount == 1) currency = this.BOSEconomy.getMoneyName();
return amount + " " + currency; return amount + " " + currency;
} }
@ -42,7 +42,7 @@ public class BOSE implements Method {
} }
public MethodAccount getAccount(String name) { public MethodAccount getAccount(String name) {
if(!hasAccount(name)) return null; if (!hasAccount(name)) return null;
return new BOSEAccount(name, this.BOSEconomy); return new BOSEAccount(name, this.BOSEconomy);
} }
@ -55,7 +55,7 @@ public class BOSE implements Method {
} }
public void setPlugin(Plugin plugin) { public void setPlugin(Plugin plugin) {
BOSEconomy = (BOSEconomy)plugin; BOSEconomy = (BOSEconomy) plugin;
} }
public static class BOSEAccount implements MethodAccount { public static class BOSEAccount implements MethodAccount {
@ -72,31 +72,30 @@ public class BOSE implements Method {
} }
public boolean set(double amount) { public boolean set(double amount) {
int IntAmount = (int)Math.ceil(amount); int IntAmount = (int) Math.ceil(amount);
return this.BOSEconomy.setPlayerMoney(this.name, IntAmount, false); return this.BOSEconomy.setPlayerMoney(this.name, IntAmount, false);
} }
public boolean add(double amount) { public boolean add(double amount) {
int IntAmount = (int)Math.ceil(amount); int IntAmount = (int) Math.ceil(amount);
int balance = (int)this.balance();
return this.BOSEconomy.addPlayerMoney(this.name, IntAmount, false); return this.BOSEconomy.addPlayerMoney(this.name, IntAmount, false);
} }
public boolean subtract(double amount) { public boolean subtract(double amount) {
int IntAmount = (int)Math.ceil(amount); int IntAmount = (int) Math.ceil(amount);
int balance = (int)this.balance(); int balance = (int) this.balance();
return this.BOSEconomy.setPlayerMoney(this.name, (balance - IntAmount), false); return this.BOSEconomy.setPlayerMoney(this.name, (balance - IntAmount), false);
} }
public boolean multiply(double amount) { public boolean multiply(double amount) {
int IntAmount = (int)Math.ceil(amount); int IntAmount = (int) Math.ceil(amount);
int balance = (int)this.balance(); int balance = (int) this.balance();
return this.BOSEconomy.setPlayerMoney(this.name, (balance * IntAmount), false); return this.BOSEconomy.setPlayerMoney(this.name, (balance * IntAmount), false);
} }
public boolean divide(double amount) { public boolean divide(double amount) {
int IntAmount = (int)Math.ceil(amount); int IntAmount = (int) Math.ceil(amount);
int balance = (int)this.balance(); int balance = (int) this.balance();
return this.BOSEconomy.setPlayerMoney(this.name, (balance / IntAmount), false); return this.BOSEconomy.setPlayerMoney(this.name, (balance / IntAmount), false);
} }
@ -145,31 +144,31 @@ public class BOSE implements Method {
} }
public boolean set(double amount) { public boolean set(double amount) {
int IntAmount = (int)Math.ceil(amount); int IntAmount = (int) Math.ceil(amount);
return this.BOSEconomy.setBankMoney(name, IntAmount, true); return this.BOSEconomy.setBankMoney(name, IntAmount, true);
} }
public boolean add(double amount) { public boolean add(double amount) {
int IntAmount = (int)Math.ceil(amount); int IntAmount = (int) Math.ceil(amount);
int balance = (int)this.balance(); int balance = (int) this.balance();
return this.BOSEconomy.setBankMoney(this.name, (balance + IntAmount), false); return this.BOSEconomy.setBankMoney(this.name, (balance + IntAmount), false);
} }
public boolean subtract(double amount) { public boolean subtract(double amount) {
int IntAmount = (int)Math.ceil(amount); int IntAmount = (int) Math.ceil(amount);
int balance = (int)this.balance(); int balance = (int) this.balance();
return this.BOSEconomy.setBankMoney(this.name, (balance - IntAmount), false); return this.BOSEconomy.setBankMoney(this.name, (balance - IntAmount), false);
} }
public boolean multiply(double amount) { public boolean multiply(double amount) {
int IntAmount = (int)Math.ceil(amount); int IntAmount = (int) Math.ceil(amount);
int balance = (int)this.balance(); int balance = (int) this.balance();
return this.BOSEconomy.setBankMoney(this.name, (balance * IntAmount), false); return this.BOSEconomy.setBankMoney(this.name, (balance * IntAmount), false);
} }
public boolean divide(double amount) { public boolean divide(double amount) {
int IntAmount = (int)Math.ceil(amount); int IntAmount = (int) Math.ceil(amount);
int balance = (int)this.balance(); int balance = (int) this.balance();
return this.BOSEconomy.setBankMoney(this.name, (balance / IntAmount), false); return this.BOSEconomy.setBankMoney(this.name, (balance / IntAmount), false);
} }

View File

@ -4,9 +4,7 @@ import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.api.Economy; import com.earth2me.essentials.api.Economy;
import com.earth2me.essentials.api.NoLoanPermittedException; import com.earth2me.essentials.api.NoLoanPermittedException;
import com.earth2me.essentials.api.UserDoesNotExistException; import com.earth2me.essentials.api.UserDoesNotExistException;
import com.nijikokun.register.payment.Method; import com.nijikokun.register.payment.Method;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
public class EE17 implements Method { public class EE17 implements Method {
@ -45,23 +43,26 @@ public class EE17 implements Method {
} }
public MethodAccount getAccount(String name) { public MethodAccount getAccount(String name) {
if(!hasAccount(name)) return null; if (!hasAccount(name)) return null;
return new EEcoAccount(name); return new EEcoAccount(name);
} }
public MethodBankAccount getBankAccount(String bank, String name) { public MethodBankAccount getBankAccount(String bank, String name) {
return null; return null;
} }
public boolean isCompatible(Plugin plugin) { public boolean isCompatible(Plugin plugin) {
try { Class.forName("com.earth2me.essentials.api.Economy"); } try {
catch(Exception e) { return false; } Class.forName("com.earth2me.essentials.api.Economy");
} catch (Exception e) {
return false;
}
return plugin.getDescription().getName().equalsIgnoreCase("essentials") && plugin instanceof Essentials; return plugin.getDescription().getName().equalsIgnoreCase("essentials") && plugin instanceof Essentials;
} }
public void setPlugin(Plugin plugin) { public void setPlugin(Plugin plugin) {
Essentials = (Essentials)plugin; Essentials = (Essentials) plugin;
} }
public static class EEcoAccount implements MethodAccount { public static class EEcoAccount implements MethodAccount {

View File

@ -2,9 +2,7 @@ package com.nijikokun.register.payment.methods;
import com.nijiko.coelho.iConomy.iConomy; import com.nijiko.coelho.iConomy.iConomy;
import com.nijiko.coelho.iConomy.system.Account; import com.nijiko.coelho.iConomy.system.Account;
import com.nijikokun.register.payment.Method; import com.nijikokun.register.payment.Method;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
public class iCo4 implements Method { public class iCo4 implements Method {
@ -49,15 +47,15 @@ public class iCo4 implements Method {
public MethodBankAccount getBankAccount(String bank, String name) { public MethodBankAccount getBankAccount(String bank, String name) {
return null; return null;
} }
public boolean isCompatible(Plugin plugin) { public boolean isCompatible(Plugin plugin) {
return plugin.getDescription().getName().equalsIgnoreCase("iconomy") && !plugin.getClass().getName().equals("com.iConomy.iConomy") && plugin instanceof iConomy; return plugin.getDescription().getName().equalsIgnoreCase("iconomy") && !plugin.getClass().getName().equals("com.iConomy.iConomy") && plugin instanceof iConomy;
} }
public void setPlugin(Plugin plugin) { public void setPlugin(Plugin plugin) {
iConomy = (iConomy)plugin; iConomy = (iConomy) plugin;
} }
public static class iCoAccount implements MethodAccount { public static class iCoAccount implements MethodAccount {
private Account account; private Account account;
@ -74,31 +72,31 @@ public class iCo4 implements Method {
} }
public boolean set(double amount) { public boolean set(double amount) {
if(this.account == null) return false; if (this.account == null) return false;
this.account.setBalance(amount); this.account.setBalance(amount);
return true; return true;
} }
public boolean add(double amount) { public boolean add(double amount) {
if(this.account == null) return false; if (this.account == null) return false;
this.account.add(amount); this.account.add(amount);
return true; return true;
} }
public boolean subtract(double amount) { public boolean subtract(double amount) {
if(this.account == null) return false; if (this.account == null) return false;
this.account.subtract(amount); this.account.subtract(amount);
return true; return true;
} }
public boolean multiply(double amount) { public boolean multiply(double amount) {
if(this.account == null) return false; if (this.account == null) return false;
this.account.multiply(amount); this.account.multiply(amount);
return true; return true;
} }
public boolean divide(double amount) { public boolean divide(double amount) {
if(this.account == null) return false; if (this.account == null) return false;
this.account.divide(amount); this.account.divide(amount);
return true; return true;
} }
@ -120,7 +118,7 @@ public class iCo4 implements Method {
} }
public boolean remove() { public boolean remove() {
if(this.account == null) return false; if (this.account == null) return false;
this.account.remove(); this.account.remove();
return true; return true;
} }

View File

@ -5,9 +5,7 @@ import com.iConomy.system.Account;
import com.iConomy.system.BankAccount; import com.iConomy.system.BankAccount;
import com.iConomy.system.Holdings; import com.iConomy.system.Holdings;
import com.iConomy.util.Constants; import com.iConomy.util.Constants;
import com.nijikokun.register.payment.Method; import com.nijikokun.register.payment.Method;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
public class iCo5 implements Method { public class iCo5 implements Method {
@ -52,13 +50,13 @@ public class iCo5 implements Method {
public MethodBankAccount getBankAccount(String bank, String name) { public MethodBankAccount getBankAccount(String bank, String name) {
return new iCoBankAccount(iConomy.getBank(bank).getAccount(name)); return new iCoBankAccount(iConomy.getBank(bank).getAccount(name));
} }
public boolean isCompatible(Plugin plugin) { public boolean isCompatible(Plugin plugin) {
return plugin.getDescription().getName().equalsIgnoreCase("iconomy") && plugin.getClass().getName().equals("com.iConomy.iConomy") && plugin instanceof iConomy; return plugin.getDescription().getName().equalsIgnoreCase("iconomy") && plugin.getClass().getName().equals("com.iConomy.iConomy") && plugin instanceof iConomy;
} }
public void setPlugin(Plugin plugin) { public void setPlugin(Plugin plugin) {
iConomy = (iConomy)plugin; iConomy = (iConomy) plugin;
} }
public static class iCoAccount implements MethodAccount { public static class iCoAccount implements MethodAccount {
@ -79,31 +77,31 @@ public class iCo5 implements Method {
} }
public boolean set(double amount) { public boolean set(double amount) {
if(this.holdings == null) return false; if (this.holdings == null) return false;
this.holdings.set(amount); this.holdings.set(amount);
return true; return true;
} }
public boolean add(double amount) { public boolean add(double amount) {
if(this.holdings == null) return false; if (this.holdings == null) return false;
this.holdings.add(amount); this.holdings.add(amount);
return true; return true;
} }
public boolean subtract(double amount) { public boolean subtract(double amount) {
if(this.holdings == null) return false; if (this.holdings == null) return false;
this.holdings.subtract(amount); this.holdings.subtract(amount);
return true; return true;
} }
public boolean multiply(double amount) { public boolean multiply(double amount) {
if(this.holdings == null) return false; if (this.holdings == null) return false;
this.holdings.multiply(amount); this.holdings.multiply(amount);
return true; return true;
} }
public boolean divide(double amount) { public boolean divide(double amount) {
if(this.holdings == null) return false; if (this.holdings == null) return false;
this.holdings.divide(amount); this.holdings.divide(amount);
return true; return true;
} }
@ -125,7 +123,7 @@ public class iCo5 implements Method {
} }
public boolean remove() { public boolean remove() {
if(this.account == null) return false; if (this.account == null) return false;
this.account.remove(); this.account.remove();
return true; return true;
} }
@ -157,31 +155,31 @@ public class iCo5 implements Method {
} }
public boolean set(double amount) { public boolean set(double amount) {
if(this.holdings == null) return false; if (this.holdings == null) return false;
this.holdings.set(amount); this.holdings.set(amount);
return true; return true;
} }
public boolean add(double amount) { public boolean add(double amount) {
if(this.holdings == null) return false; if (this.holdings == null) return false;
this.holdings.add(amount); this.holdings.add(amount);
return true; return true;
} }
public boolean subtract(double amount) { public boolean subtract(double amount) {
if(this.holdings == null) return false; if (this.holdings == null) return false;
this.holdings.subtract(amount); this.holdings.subtract(amount);
return true; return true;
} }
public boolean multiply(double amount) { public boolean multiply(double amount) {
if(this.holdings == null) return false; if (this.holdings == null) return false;
this.holdings.multiply(amount); this.holdings.multiply(amount);
return true; return true;
} }
public boolean divide(double amount) { public boolean divide(double amount) {
if(this.holdings == null) return false; if (this.holdings == null) return false;
this.holdings.divide(amount); this.holdings.divide(amount);
return true; return true;
} }
@ -203,7 +201,7 @@ public class iCo5 implements Method {
} }
public boolean remove() { public boolean remove() {
if(this.account == null) return false; if (this.account == null) return false;
this.account.remove(); this.account.remove();
return true; return true;
} }