Merge branch 'master' into 1.8.8-hotfix

# Conflicts:
#	pom.xml
#	src/main/java/com/Acrobot/Breeze/Utils/InventoryUtil.java
#	src/main/java/com/Acrobot/Breeze/Utils/MaterialUtil.java
#	src/main/java/com/Acrobot/ChestShop/Listeners/Player/PlayerInteract.java
This commit is contained in:
Phoenix616 2018-06-23 15:11:51 +01:00
commit b3e300893e
27 changed files with 243 additions and 166 deletions

View File

@ -6,7 +6,7 @@
<groupId>com.acrobot.chestshop</groupId>
<artifactId>chestshop</artifactId>
<version>3.9.1-1.8.8-hotfix</version>
<version>3.9.2-1.8.8-hotfix</version>
<description>Chest-and-sign shop plugin for Bukkit</description>
<name>ChestShop</name>
@ -62,7 +62,7 @@
<dependency>
<groupId>com.j256.ormlite</groupId>
<artifactId>ormlite-jdbc</artifactId>
<version>4.48</version>
<version>5.1</version>
<scope>compile</scope>
</dependency>
@ -70,7 +70,7 @@
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.0-beta9</version>
<version>2.1</version>
<scope>provided</scope>
</dependency>
@ -101,7 +101,7 @@
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit-lite</artifactId>
<version>1.1</version>
<version>1.2</version>
<scope>compile</scope>
</dependency>
@ -250,6 +250,7 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.bekvon.bukkit</groupId>
<artifactId>residence</artifactId>

View File

@ -47,6 +47,8 @@ public class Configuration {
try {
if (config.isSet(path)) {
field.set(null, ValueParser.parseToJava(config.get(path)));
} else if (config.isSet(path.toLowerCase())) {
field.set(null, ValueParser.parseToJava(config.get(path.toLowerCase())));
} else {
if (field.isAnnotationPresent(PrecededBySpace.class)) {
writer.newLine();

View File

@ -17,6 +17,10 @@ public class FieldParser {
public static String parse(Field field) {
StringBuilder builder = new StringBuilder(50);
if (field.isAnnotationPresent(ConfigurationComment.class)) {
builder.append('#').append(field.getAnnotation(ConfigurationComment.class).value()).append('\n');
}
try {
builder.append(field.getName()).append(": ").append(ValueParser.parseToYAML(field.get(null)));
} catch (IllegalAccessException e) {
@ -24,10 +28,6 @@ public class FieldParser {
return "";
}
if (field.isAnnotationPresent(ConfigurationComment.class)) {
builder.append('\n').append('#').append(field.getAnnotation(ConfigurationComment.class).value());
}
return builder.toString();
}
}

View File

@ -19,6 +19,12 @@ public class ValueParser {
public static String parseToYAML(Object object) {
if (object instanceof Number || object instanceof Boolean) {
return String.valueOf(object);
} else if (object instanceof List) {
StringBuilder sb = new StringBuilder();
for (Object o : (List) object) {
sb.append("\n- ").append(parseToYAML(o));
}
return sb.toString();
} else {
return '\"' + String.valueOf(object) + '\"';
}

View File

@ -34,7 +34,7 @@ package com.Acrobot.Breeze.Utils.Encoding;
* @version 2.3.7
*/
public class Base64 {
/* ******** P U B L I C F I E L D S ******** */
@ -87,8 +87,8 @@ public class Base64 {
* <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
*/
public final static int ORDERED = 32;
/* ******** P R I V A T E F I E L D S ******** */
@ -119,7 +119,7 @@ public class Base64 {
private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
/* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
/**
@ -178,7 +178,7 @@ public class Base64 {
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255
};
/* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */
/**
@ -305,7 +305,7 @@ public class Base64 {
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255
};
/* ******** D E T E R M I N E W H I C H A L H A B E T ******** */
@ -349,10 +349,10 @@ public class Base64 {
* Defeats instantiation.
*/
private Base64() {}
/* ******** E N C O D I N G M E T H O D S ******** */
@ -903,11 +903,11 @@ public class Base64 {
} // end else: don't compress
} // end encodeBytesToBytes
/* ******** D E C O D I N G M E T H O D S ******** */
@ -1547,8 +1547,8 @@ public class Base64 {
}
} // end finally
} // end decodeFileToFile
/* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
@ -1754,12 +1754,12 @@ public class Base64 {
} // end read
} // end inner class InputStream
/* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */

View File

@ -14,7 +14,7 @@ import org.bukkit.inventory.ItemStack;
* @author Acrobot
*/
public class InventoryUtil {
private static ItemStack[] getStorageContents(Inventory inventory) {
return inventory.getContents();
}
@ -64,7 +64,7 @@ public class InventoryUtil {
return true;
}
/**
* Count amount of empty slots in an inventory
*
@ -78,7 +78,7 @@ public class InventoryUtil {
emptyAmount++;
}
}
return emptyAmount;
}
@ -99,7 +99,7 @@ public class InventoryUtil {
return true;
}
/**
* Checks if items fit in the inventory
*
@ -114,7 +114,7 @@ public class InventoryUtil {
return false;
}
}
return true;
}
@ -196,8 +196,7 @@ public class InventoryUtil {
}
// Don't use the armor slots or extra slots
private static int effectiveSize(Inventory inventory)
{
private static int effectiveSize(Inventory inventory) {
return getStorageContents(inventory).length;
}
@ -323,15 +322,17 @@ public class InventoryUtil {
/**
* Get the max size an item stack is allowed to stack to while respecting the STACK_TO_64 config property
*
* @param item The item to get the max stacksize of
* @return The max stacksize of the item stack's type or 64 if STACK_TO_64 is enabled
*/
public static int getMaxStackSize(ItemStack item) {
return Properties.STACK_TO_64 ? 64 : item.getMaxStackSize();
}
/**
* Get an array of different item stacks that are properly stacked to their max stack size
*
* @param items The items to stack
* @return An array of item stacks which's amount is a maximum of the allowed stack size
*/

View File

@ -41,7 +41,7 @@ public class MaterialUtil {
public static final boolean LONG_NAME = true;
public static final boolean SHORT_NAME = false;
public static final short MAXIMUM_SIGN_LETTERS = 15;
private static final SimpleCache<String, Material> MATERIAL_CACHE = new SimpleCache<>(Properties.CACHE_SIZE);
/**
@ -68,7 +68,7 @@ public class MaterialUtil {
if (one.isSimilar(two)) {
return true;
}
// Special check for banners as they might include the deprecated base color
if (one.getType() == two.getType()
&& one.getType() == Material.BANNER
@ -79,7 +79,7 @@ public class MaterialUtil {
Object c2 = m2.remove("base-color");
return (one.getData().equals(two.getData()) || c1.equals(c2)) && m1.equals(m2);
}
// Special check for books as their pages might change when serialising (See SPIGOT-3206)
return one.getType() == two.getType()
&& one.getDurability() == two.getDurability()
@ -156,7 +156,7 @@ public class MaterialUtil {
public static String getSignName(ItemStack itemStack) {
return getName(itemStack, MAXIMUM_SIGN_LETTERS);
}
/**
* Returns item's name, with a maximum length
*
@ -167,7 +167,10 @@ public class MaterialUtil {
public static String getName(ItemStack itemStack, int maxLength) {
String alias = Odd.getAlias(itemStack);
String itemName = alias != null ? alias : itemStack.getType().toString();
if (itemStack.getType() != Material.HUGE_MUSHROOM_2 && itemName.endsWith("_2")) {
itemName = itemName.substring(0, itemName.length() - 2);
}
String data = DataValue.name(itemStack);
String durability = "";
if (data == null) {
@ -181,16 +184,16 @@ public class MaterialUtil {
if (itemStack.hasItemMeta()) {
metaData = "#" + Metadata.getItemCode(itemStack);
}
int codeLength = (data + itemName + durability + metaData).length();
String code = data + itemName;
if (maxLength > 0 && codeLength > maxLength) {
int exceeding = codeLength - maxLength;
code = getShortenedName(code, code.length() - exceeding);
}
code = StringUtil.capitalizeFirstLetter(code, '_') + durability + metaData;
ItemStack codeItem = getItem(code);
if (!equals(itemStack, codeItem)) {
throw new IllegalArgumentException("Cannot generate code for item " + itemStack + " with maximum length of " + maxLength
@ -199,9 +202,10 @@ public class MaterialUtil {
return code;
}
/**
* Get an item name shortened to a max length that is still reversable by {@link #getMaterial(String)}
*
* @param itemName The name of the item
* @param maxLength The max length
* @return The name shortened to the max length
@ -245,7 +249,7 @@ public class MaterialUtil {
}
return String.join("_", itemParts);
}
/**
* Gives you an ItemStack from a String
*
@ -267,7 +271,7 @@ public class MaterialUtil {
Material material = getMaterial(split[0]);
short durability = getDurability(itemName);
MaterialData data = null;
if (material == null) {
if (!split[0].contains(" ")) {
return null;
@ -278,6 +282,7 @@ public class MaterialUtil {
if (material != null) {
data = DataValue.getData(split[0].substring(0, index), material);
material = data.getItemType();
break;
}
@ -289,9 +294,6 @@ public class MaterialUtil {
}
itemStack = new ItemStack(material);
if (data == null && durability > 0 && material.getMaxDurability() == 0) {
data = material.getNewData((byte) durability);
}
if (data != null) {
itemStack.setData(data);
durability = data.getData();
@ -366,13 +368,15 @@ public class MaterialUtil {
MaterialData data = getData(type, material);
return data != null ? data.getData() : 0;
}
/**
* Gets the dat from a string
*
* @param type Data Value string
* @param material Material
* @return data
* @return data The Material data with that name, under some circumstances the type of the data might be
* different from the inputted Material. (e.g. with LOG_2 or similar alternatives)
* It's advised to use the type of the MaterialData going forward when using the data
*/
public static MaterialData getData(String type, Material material) {
@ -395,6 +399,23 @@ public class MaterialUtil {
TreeSpecies species = new EnumParser<TreeSpecies>().parse(type, TreeSpecies.values());
if (species != null) {
((Tree) materialData).setSpecies(species);
try {
((Tree) materialData).setSpecies(species);
} catch (IllegalArgumentException e) {
String materialName = material.toString();
if (materialName.endsWith("_2")) {
Material mat = Material.getMaterial(materialName.substring(0, materialName.length() - 2));
if (mat != null) {
materialData = new ItemStack(mat).getData();
}
} else {
Material mat = Material.getMaterial(materialName + "_2");
if (mat != null) {
materialData = new ItemStack(mat).getData();
}
}
((Tree) materialData).setSpecies(species);
}
}
} else if (materialData instanceof SpawnEgg) {
EntityType entityType = new EnumParser<EntityType>().parse(type, EntityType.values());
@ -415,7 +436,7 @@ public class MaterialUtil {
return materialData;
}
/**
* Returns a string with the DataValue
*
@ -428,7 +449,7 @@ public class MaterialUtil {
if (data == null) {
return null;
}
if (data instanceof TexturedMaterial) {
return ((TexturedMaterial) data).getMaterial().name();
} else if (data instanceof Colorable) {
@ -452,11 +473,11 @@ public class MaterialUtil {
}
}
}
private static class EnumParser<E extends Enum<E>> {
private E parse(String name, E[] values) {
name = name.toUpperCase();
try {
return E.valueOf(values[0].getDeclaringClass(), name);
} catch (IllegalArgumentException exception) {
@ -468,7 +489,7 @@ public class MaterialUtil {
if (enumName.length() < length && enumName.startsWith(name)) {
length = (short) enumName.length();
currentEnum = e;
} else if (typeParts.length > 1) {
} else if (typeParts.length > 1) {
String[] nameParts = enumName.split("_");
if (typeParts.length == nameParts.length) {
boolean matched = true;
@ -562,10 +583,10 @@ public class MaterialUtil {
isInitialized = true;
}
}
public static class Show {
private static ShowItem showItem = null;
/**
* Lets the class know that it's safe to use the ShowItem methods now
*
@ -574,7 +595,7 @@ public class MaterialUtil {
public static void initialize(Plugin plugin) {
showItem = (ShowItem) plugin;
}
/**
* Send a message with hover info and icons
*
@ -586,7 +607,7 @@ public class MaterialUtil {
if (showItem == null) {
return false;
}
List<String> itemJson = new ArrayList<>();
for (ItemStack item : InventoryUtil.mergeSimilarStacks(stock)) {
try {
@ -596,20 +617,20 @@ public class MaterialUtil {
return false;
}
}
String joinedItemJson = itemJson.stream().collect(Collectors.joining("," + new JSONObject(ImmutableMap.of("text", " ")).toJSONString() + ", "));
String messageJsonString = Arrays.stream(message.split("%item"))
.map(s -> new JSONObject(ImmutableMap.of("text", s)).toJSONString())
.collect(Collectors.joining("," + joinedItemJson + ","));
while (messageJsonString.startsWith(",")) {
messageJsonString = messageJsonString.substring(1);
}
while (messageJsonString.endsWith(",")) {
messageJsonString = messageJsonString.substring(0, messageJsonString.length() - 1);
}
showItem.tellRaw(player, messageJsonString);
return true;
}

View File

@ -269,7 +269,7 @@ public class ChestShop extends JavaPlugin {
registerEvent(new ItemInfoListener());
registerEvent(new GarbageTextListener());
Plugin authMe = getServer().getPluginManager().getPlugin("AuthMe");
if (authMe != null && authMe.isEnabled()) {
registerEvent(new AuthMeChestShopListener());
@ -356,7 +356,7 @@ public class ChestShop extends JavaPlugin {
} catch (IOException ex) {
ChestShop.getBukkitLogger().severe("There was an error while submitting MCStats statistics.");
}
new org.bstats.MetricsLite(this);
new org.bstats.bukkit.MetricsLite(this);
}
private static final int PROJECT_BUKKITDEV_ID = 31263;

View File

@ -41,7 +41,7 @@ public class ItemInfo implements CommandExecutor {
} catch (IllegalArgumentException e) {
sender.sendMessage(ChatColor.RED + "Full Name Error: " + e.getMessage());
}
try {
sender.sendMessage(ChatColor.WHITE + "Shop Sign: " + ChatColor.GRAY + MaterialUtil.getSignName(item));
} catch (IllegalArgumentException e) {

View File

@ -49,11 +49,11 @@ public class Messages {
public static String NO_CHEST_DETECTED = "Couldn't find a chest!";
public static String INVALID_SHOP_DETECTED = "The shop cannot be used!";
public static String CANNOT_ACCESS_THE_CHEST = "You don't have permissions to access this chest!";
@PrecededBySpace
public static String CLICK_TO_AUTOFILL_ITEM = "Click the sign with the item that this shop is for!";
public static String NO_ITEM_IN_HAND = "You don't have an item in your hand to autofill!";
@PrecededBySpace
public static String PROTECTED_SHOP = "Successfully protected the shop with LWC!";
public static String SHOP_CREATED = "Shop successfully created!";
@ -78,6 +78,6 @@ public class Messages {
public static String TOGGLE_MESSAGES_ON = "You will now receive messages from your shop(s).";
public static String prefix(String message) {
return Configuration.getColoured( prefix + message);
return Configuration.getColoured(prefix + message);
}
}

View File

@ -3,6 +3,9 @@ package com.Acrobot.ChestShop.Configuration;
import com.Acrobot.Breeze.Configuration.Annotations.ConfigurationComment;
import com.Acrobot.Breeze.Configuration.Annotations.PrecededBySpace;
import java.util.Arrays;
import java.util.List;
/**
* @author Acrobot
*/
@ -43,6 +46,9 @@ public class Properties {
@ConfigurationComment("If true, if the REMOVE_EMPTY_SHOPS option is turned on, the chest is also destroyed.")
public static boolean REMOVE_EMPTY_CHESTS = false;
@ConfigurationComment("A list of worlds in which to remove empty shops with the previous config. Case sensitive. An empty list means all worlds.")
public static List<String> REMOVE_EMPTY_WORLDS = Arrays.asList("world1", "world2");
@PrecededBySpace
@ConfigurationComment("First line of your Admin Shop's sign should look like this:")
public static String ADMIN_SHOP_NAME = "Admin Shop";
@ -149,7 +155,7 @@ public class Properties {
@PrecededBySpace
@ConfigurationComment("How much Heroes exp should people get for creating a ChestShop?")
public static double HEROES_EXP = 100;
@PrecededBySpace
@ConfigurationComment("Add icons and make item names hoverable in transaction messages when ShowItem is installed?")
public static boolean SHOWITEM_MESSAGE = true;

View File

@ -5,6 +5,7 @@ import com.j256.ormlite.dao.CloseableIterator;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.GenericRawResults;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.UUID;
@ -104,7 +105,11 @@ public class Migrations {
lastInfo = System.currentTimeMillis();
}
}
results.close();
try {
results.close();
} catch (IOException e1) {
ChestShop.getBukkitLogger().log(Level.WARNING, "Error while closing results! " + e.getMessage());
}
ChestShop.getBukkitLogger().log(Level.INFO, success + " accounts successfully migrated. " + error + " accounts failed to migrate!");
}
ChestShop.getBukkitLogger().log(Level.INFO, "Migration of accounts table finished in " + (System.currentTimeMillis() - start) / 1000.0 + "s!");

View File

@ -134,7 +134,7 @@ public class Dependencies {
WorldGuard,
Heroes,
ShowItem
}
}

View File

@ -141,7 +141,7 @@ public class PreShopCreationEvent extends Event {
INVALID_ITEM,
INVALID_PRICE,
INVALID_QUANTITY,
ITEM_AUTOFILL,
UNKNOWN_PLAYER,

View File

@ -22,7 +22,11 @@ import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.material.Directional;
import org.bukkit.material.PistonBaseMaterial;
import org.bukkit.metadata.FixedMetadataValue;
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import static com.Acrobot.Breeze.Utils.BlockUtil.getAttachedBlock;
import static com.Acrobot.Breeze.Utils.BlockUtil.isSign;
@ -192,7 +196,7 @@ public class SignBreak implements Listener {
return attachedSigns;
}
}
private static List<Block> getRetractBlocks(BlockPistonRetractEvent event) {
try {
return event.getBlocks();
@ -205,41 +209,41 @@ public class SignBreak implements Listener {
return blocks;
}
}
//Those are fixes for a very old CraftBukkit's piston bug, where piston appears not to be a piston.
private static BlockFace getPistonDirection(Block block) {
return block.getState().getData() instanceof PistonBaseMaterial ? ((Directional) block.getState().getData()).getFacing() : null;
}
private static Block getRetractLocationBlock(BlockPistonRetractEvent event) {
BlockFace pistonDirection = getPistonDirection(event.getBlock());
return pistonDirection != null ? event.getBlock().getRelative((pistonDirection), 2).getLocation().getBlock() : null;
}
private static List<Block> getExtendBlocks(BlockPistonExtendEvent event) {
try {
return event.getBlocks();
} catch (NoSuchMethodError outdated) { // backwards compatiblity
BlockFace pistonDirection = getPistonDirection(event.getBlock());
if (pistonDirection == null) {
return new ArrayList<>();
}
Block piston = event.getBlock();
List<Block> pushedBlocks = new ArrayList<>();
for (int currentBlock = 1; currentBlock < event.getLength() + 1; currentBlock++) {
Block block = piston.getRelative(pistonDirection, currentBlock);
Material blockType = block.getType();
if (blockType == Material.AIR) {
break;
}
pushedBlocks.add(block);
}
return pushedBlocks;
}
}

View File

@ -33,11 +33,11 @@ public class SignCreate implements Listener {
PreShopCreationEvent preEvent = new PreShopCreationEvent(event.getPlayer(), (Sign) signBlock.getState(), line);
ChestShop.callEvent(preEvent);
for (byte i = 0; i < event.getLines().length; ++i) {
event.setLine(i, preEvent.getSignLine(i));
}
if (preEvent.isCancelled()) {
return;
}

View File

@ -43,7 +43,7 @@ public class ServerAccountCorrector implements Listener {
if (!NameManager.isAdminShop(target) || NameManager.isServerEconomyAccount(target)) {
return;
}
Account account = NameManager.getServerEconomyAccount();
target = account != null ? account.getUuid() : null;
@ -59,14 +59,14 @@ public class ServerAccountCorrector implements Listener {
@EventHandler(priority = EventPriority.LOWEST)
public static void onCurrencyCheck(CurrencyCheckEvent event) {
UUID target = event.getAccount();
if (!NameManager.isAdminShop(target) || NameManager.isServerEconomyAccount(target)) {
return;
}
Account account = NameManager.getServerEconomyAccount();
target = account != null ? account.getUuid() : null;
if (target == null) {
event.hasEnough(true);
return;
@ -81,7 +81,7 @@ public class ServerAccountCorrector implements Listener {
@EventHandler(priority = EventPriority.LOWEST)
public static void onCurrencyHoldCheck(CurrencyHoldEvent event) {
UUID target = event.getAccount();
if (!NameManager.isAdminShop(target) || NameManager.isServerEconomyAccount(target)) {
return;
}
@ -100,7 +100,7 @@ public class ServerAccountCorrector implements Listener {
Account account = NameManager.getServerEconomyAccount();
target = account != null ? account.getUuid() : null;
if (target == null) {
event.setAmount(BigDecimal.valueOf(Double.MAX_VALUE));
return;

View File

@ -8,6 +8,8 @@ import org.bukkit.enchantments.Enchantment;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionEffect;
@ -24,12 +26,17 @@ public class ItemInfoListener implements Listener {
@EventHandler
public static void addEnchantment(ItemInfoEvent event) {
ItemStack item = event.getItem();
ItemMeta meta = item.getItemMeta();
CommandSender sender = event.getSender();
Map<Enchantment, Integer> enchantments = item.getEnchantments();
for (Map.Entry<Enchantment, Integer> enchantment : item.getEnchantments().entrySet()) {
sender.sendMessage(ChatColor.AQUA + capitalizeFirstLetter(enchantment.getKey().getName(), '_') + ' ' + toRoman(enchantment.getValue()));
}
for (Map.Entry<Enchantment, Integer> enchantment : enchantments.entrySet()) {
sender.sendMessage(ChatColor.DARK_GRAY + capitalizeFirstLetter(enchantment.getKey().getName(), '_') + ' ' + toRoman(enchantment.getValue()));
if (meta instanceof EnchantmentStorageMeta) {
for (Map.Entry<Enchantment, Integer> enchantment : ((EnchantmentStorageMeta) meta).getStoredEnchants().entrySet()) {
sender.sendMessage(ChatColor.YELLOW + capitalizeFirstLetter(enchantment.getKey().getName(), '_') + ' ' + toRoman(enchantment.getValue()));
}
}
}

View File

@ -36,7 +36,7 @@ public class PriceRestrictionModule implements Listener {
if (!file.exists()) {
configuration.addDefault("uses_materials", true);
configuration.addDefault("max.buy_price.item_type", 5.53);
configuration.addDefault("max.buy_price.piston_head", 3.51);
configuration.addDefault("max.sell_price.placed_banner", 3.52);
@ -72,7 +72,7 @@ public class PriceRestrictionModule implements Listener {
}
}
}
private void convertToMaterial(String sectionPath) {
ConfigurationSection section = configuration.getConfigurationSection(sectionPath);
if (section != null) {
@ -87,7 +87,7 @@ public class PriceRestrictionModule implements Listener {
}
}
}
@EventHandler
public void onPreShopCreation(PreShopCreationEvent event) {
ItemStack material = MaterialUtil.getItem(event.getSignLine(ITEM_LINE));

View File

@ -46,8 +46,7 @@ import static org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK;
public class PlayerInteract implements Listener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public static void onInteract(PlayerInteractEvent event)
{
public static void onInteract(PlayerInteractEvent event) {
Block block = event.getClickedBlock();
if (block == null)
return;
@ -77,15 +76,15 @@ public class PlayerInteract implements Listener {
}
boolean canAccess = ChestShopSign.canAccess(player, sign);
if (Properties.ALLOW_AUTO_ITEM_FILL && ChatColor.stripColor(sign.getLine(ITEM_LINE)).equals(AUTOFILL_CODE)) {
if (canAccess) {
ItemStack item = player.getInventory().getItemInHand();
if (item != null) {
if (!MaterialUtil.isEmpty(item)) {
String itemCode = MaterialUtil.getSignName(item);
String[] lines = sign.getLines();
lines[ITEM_LINE] = itemCode;
SignChangeEvent changeEvent = new SignChangeEvent(block, player, lines);
com.Acrobot.ChestShop.ChestShop.callEvent(changeEvent);
if (!changeEvent.isCancelled()) {
@ -102,7 +101,7 @@ public class PlayerInteract implements Listener {
}
return;
}
if (canAccess) {
if (!Properties.ALLOW_SIGN_CHEST_OPEN || player.isSneaking() || player.isInsideVehicle() || player.getGameMode() == GameMode.CREATIVE) {
return;
@ -148,7 +147,7 @@ public class PlayerInteract implements Listener {
boolean adminShop = ChestShopSign.isAdminShop(sign);
// check if player exists in economy
if(!adminShop && !VaultListener.getProvider().hasAccount(account.getName())) {
if (!adminShop && !VaultListener.getProvider().hasAccount(account.getName())) {
player.sendMessage(Messages.prefix(Messages.NO_ECONOMY_ACCOUNT));
return null;
}

View File

@ -35,6 +35,10 @@ public class EmptyShopDeleter implements Listener {
return;
}
if (!isInRemoveWorld(sign)) {
return;
}
ShopDestroyedEvent destroyedEvent = new ShopDestroyedEvent(null, event.getSign(), connectedChest);
ChestShop.callEvent(destroyedEvent);
@ -50,4 +54,8 @@ public class EmptyShopDeleter implements Listener {
private static boolean shopShouldBeRemoved(Inventory inventory, ItemStack[] stock) {
return Properties.REMOVE_EMPTY_SHOPS && !ChestShopSign.isAdminShop(inventory) && !InventoryUtil.hasItems(stock, inventory);
}
private static boolean isInRemoveWorld(Sign sign) {
return Properties.REMOVE_EMPTY_WORLDS.isEmpty() || Properties.REMOVE_EMPTY_WORLDS.contains(sign.getWorld().getName());
}
}

View File

@ -25,7 +25,7 @@ import static com.Acrobot.ChestShop.Signs.ChestShopSign.AUTOFILL_CODE;
* @author Acrobot
*/
public class ItemChecker implements Listener {
@EventHandler(priority = EventPriority.LOWEST)
public static void onPreShopCreation(PreShopCreationEvent event) {
String itemCode = event.getSignLine(ITEM_LINE);
@ -39,15 +39,15 @@ public class ItemChecker implements Listener {
for (ItemStack stack : chest.getInventory().getContents()) {
if (!MaterialUtil.isEmpty(stack)) {
itemCode = MaterialUtil.getSignName(stack);
event.setSignLine(ITEM_LINE, itemCode);
foundItem = true;
break;
}
}
}
if (!foundItem) {
event.setSignLine(ITEM_LINE, ChatColor.BOLD + ChestShopSign.AUTOFILL_CODE);
event.setOutcome(ITEM_AUTOFILL);
@ -59,7 +59,7 @@ public class ItemChecker implements Listener {
return;
}
}
if (itemCode.length() > MAXIMUM_SIGN_LETTERS) {
event.setOutcome(INVALID_ITEM);
return;

View File

@ -59,20 +59,20 @@ public class PartialTransactionModule implements Listener {
event.setPrice(amountAffordable * pricePerItem);
event.setStock(getCountedItemStack(event.getStock(), amountAffordable));
}
if (!InventoryUtil.hasItems(event.getStock(), event.getOwnerInventory())) {
ItemStack[] itemsHad = getItems(event.getStock(), event.getOwnerInventory());
int possessedItemCount = InventoryUtil.countItems(itemsHad);
if (possessedItemCount <= 0) {
event.setCancelled(NOT_ENOUGH_STOCK_IN_CHEST);
return;
}
event.setPrice(pricePerItem * possessedItemCount);
event.setStock(itemsHad);
}
if (!InventoryUtil.fits(event.getStock(), event.getClientInventory())) {
ItemStack[] itemsFit = getItemsThatFit(event.getStock(), event.getClientInventory());
int possessedItemCount = InventoryUtil.countItems(itemsFit);
@ -80,11 +80,11 @@ public class PartialTransactionModule implements Listener {
event.setCancelled(NOT_ENOUGH_SPACE_IN_INVENTORY);
return;
}
event.setStock(itemsFit);
event.setPrice(pricePerItem * possessedItemCount);
}
UUID seller = event.getOwnerAccount().getUuid();
CurrencyHoldEvent currencyHoldEvent = new CurrencyHoldEvent(BigDecimal.valueOf(event.getPrice()), seller, client.getWorld());
@ -94,7 +94,7 @@ public class PartialTransactionModule implements Listener {
event.setCancelled(SHOP_DEPOSIT_FAILED);
}
}
@EventHandler(priority = EventPriority.LOW)
public static void onPreSellTransaction(PreTransactionEvent event) {
if (event.isCancelled() || event.getTransactionType() != SELL) {
@ -127,20 +127,20 @@ public class PartialTransactionModule implements Listener {
event.setStock(getCountedItemStack(event.getStock(), amountAffordable));
}
}
if (!InventoryUtil.hasItems(event.getStock(), event.getClientInventory())) {
ItemStack[] itemsHad = getItems(event.getStock(), event.getClientInventory());
int possessedItemCount = InventoryUtil.countItems(itemsHad);
if (possessedItemCount <= 0) {
event.setCancelled(NOT_ENOUGH_STOCK_IN_INVENTORY);
return;
}
event.setPrice(pricePerItem * possessedItemCount);
event.setStock(itemsHad);
}
if (!InventoryUtil.fits(event.getStock(), event.getOwnerInventory())) {
ItemStack[] itemsFit = getItemsThatFit(event.getStock(), event.getOwnerInventory());
int possessedItemCount = InventoryUtil.countItems(itemsFit);
@ -148,7 +148,7 @@ public class PartialTransactionModule implements Listener {
event.setCancelled(NOT_ENOUGH_SPACE_IN_CHEST);
return;
}
event.setStock(itemsFit);
event.setPrice(pricePerItem * possessedItemCount);
}
@ -200,7 +200,7 @@ public class PartialTransactionModule implements Listener {
boolean added = false;
int maxStackSize = InventoryUtil.getMaxStackSize(stack);
for (ItemStack iStack : stacks) {
if (iStack.getAmount() < maxStackSize && MaterialUtil.equals(toAdd, iStack)) {
int newAmount = iStack.getAmount() + toAdd.getAmount();
@ -226,7 +226,7 @@ public class PartialTransactionModule implements Listener {
return stacks.toArray(new ItemStack[stacks.size()]);
}
/**
* Make an array of items fit into an inventory.
*
@ -236,9 +236,9 @@ public class PartialTransactionModule implements Listener {
*/
private static ItemStack[] getItemsThatFit(ItemStack[] stock, Inventory inventory) {
List<ItemStack> resultStock = new LinkedList<>();
int emptySlots = InventoryUtil.countEmpty(inventory);
for (ItemStack item : InventoryUtil.mergeSimilarStacks(stock)) {
int maxStackSize = InventoryUtil.getMaxStackSize(item);
int free = 0;
@ -247,11 +247,11 @@ public class PartialTransactionModule implements Listener {
free += (maxStackSize - itemInInventory.getAmount()) % maxStackSize;
}
}
if (free == 0 && emptySlots == 0) {
continue;
}
if (item.getAmount() > free) {
if (emptySlots > 0) {
int requiredSlots = (int) Math.ceil(((double) item.getAmount() - free) / maxStackSize);
@ -267,7 +267,7 @@ public class PartialTransactionModule implements Listener {
}
Collections.addAll(resultStock, InventoryUtil.getItemsStacked(item));
}
return resultStock.toArray(new ItemStack[resultStock.size()]);
}
}

View File

@ -10,6 +10,7 @@ import com.Acrobot.ChestShop.Events.Economy.CurrencySubtractEvent;
import com.Acrobot.ChestShop.Events.ShopDestroyedEvent;
import com.Acrobot.ChestShop.Permission;
import com.Acrobot.ChestShop.UUIDs.NameManager;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
@ -18,6 +19,8 @@ import java.math.BigDecimal;
import java.util.UUID;
import static com.Acrobot.ChestShop.Permission.NOFEE;
import static com.Acrobot.ChestShop.Signs.ChestShopSign.AUTOFILL_CODE;
import static com.Acrobot.ChestShop.Signs.ChestShopSign.ITEM_LINE;
import static com.Acrobot.ChestShop.Signs.ChestShopSign.NAME_LINE;
/**
@ -32,6 +35,10 @@ public class ShopRefundListener implements Listener {
return;
}
if (ChatColor.stripColor(event.getSign().getLine(ITEM_LINE)).equals(AUTOFILL_CODE)) {
return;
}
Account account = NameManager.getAccountFromShortName(event.getSign().getLine(NAME_LINE));
if (account == null) {
return;

View File

@ -32,7 +32,7 @@ public class ChestShopSign {
Pattern.compile("^[\\w? #:-]+$")
};
public static final String AUTOFILL_CODE = "?";
public static boolean isAdminShop(Inventory ownerInventory) {
return ownerInventory instanceof AdminInventory;
}

View File

@ -40,8 +40,9 @@ public class NameManager {
/**
* Get account info from a UUID
* @param uuid The UUID of the player to get the account info
* @return The account info or <tt>null</tt> if none was found
*
* @param uuid The UUID of the player to get the account info
* @return The account info or <tt>null</tt> if none was found
*/
public static Account getAccount(UUID uuid) {
try {
@ -49,7 +50,7 @@ public class NameManager {
try {
Account account = accounts.queryBuilder().orderBy("lastSeen", false).where().eq("uuid", uuid).queryForFirst();
if (account != null) {
account.setUuid(uuid); //HOW IS IT EVEN POSSIBLE THAT UUID IS NOT SET EVEN IF WE HAVE FOUND THE PLAYER?!
account.setUuid(uuid); // HOW IS IT EVEN POSSIBLE THAT UUID IS NOT SET EVEN IF WE HAVE FOUND THE PLAYER?!
shortToAccount.put(account.getShortName(), account);
usernameToAccount.put(account.getName(), account);
return account;
@ -66,8 +67,9 @@ public class NameManager {
/**
* Get account info from a non-shortened username
* @param fullName The full name of the player to get the account info
* @return The account info or <tt>null</tt> if none was found
*
* @param fullName The full name of the player to get the account info
* @return The account info or <tt>null</tt> if none was found
* @throws IllegalArgumentException if the username is empty or null
*/
public static Account getAccount(String fullName) {
@ -77,7 +79,7 @@ public class NameManager {
try {
Account account = accounts.queryBuilder().orderBy("lastSeen", false).where().eq("name", fullName).queryForFirst();
if (account != null) {
account.setName(fullName); //HOW IS IT EVEN POSSIBLE THAT UUID IS NOT SET EVEN IF WE HAVE FOUND THE PLAYER?!
account.setName(fullName); // HOW IS IT EVEN POSSIBLE THAT THE NAME IS NOT SET EVEN IF WE HAVE FOUND THE PLAYER?!
shortToAccount.put(account.getShortName(), account);
return account;
}
@ -93,8 +95,9 @@ public class NameManager {
/**
* Get account info from a username that might be shortened
*
* @param shortName The name of the player to get the account info
* @return The account info or <tt>null</tt> if none was found
* @return The account info or <tt>null</tt> if none was found
* @throws IllegalArgumentException if the username is empty
*/
public static Account getAccountFromShortName(String shortName) {
@ -108,7 +111,7 @@ public class NameManager {
try {
Account account = accounts.queryBuilder().where().eq("shortName", shortName).queryForFirst();
if (account != null) {
account.setShortName(shortName); //HOW IS IT EVEN POSSIBLE THAT UUID IS NOT SET EVEN IF WE HAVE FOUND THE PLAYER?!
account.setShortName(shortName); // HOW IS IT EVEN POSSIBLE THAT THE NAME IS NOT SET EVEN IF WE HAVE FOUND THE PLAYER?!
return account;
}
} catch (SQLException e) {
@ -120,11 +123,12 @@ public class NameManager {
return null;
}
}
/**
* Get the information from the last time a player logged in that previously used the shortened name
*
* @param shortName The name of the player to get the last account for
* @return The last account or <tt>null</tt> if none was found
* @return The last account or <tt>null</tt> if none was found
* @throws IllegalArgumentException if the username is not a shortened name and longer than 15 chars
*/
public static Account getLastAccountFromShortName(String shortName) {
@ -137,9 +141,10 @@ public class NameManager {
/**
* Get the UUID from a player's (non-shortened) username
* @param username The player's username
* @return The UUID or <tt>null</tt> if the UUID can't be found or an error occurred
* @deprecated Use {@link NameManager#getAccount(String)}
*
* @param username The player's username
* @return The UUID or <tt>null</tt> if the UUID can't be found or an error occurred
* @deprecated Use {@link NameManager#getAccount(String)}
*/
@Deprecated
public static UUID getUUID(String username) {
@ -161,9 +166,10 @@ public class NameManager {
/**
* Get the username from a player's UUID
* @param uuid The UUID of the player
* @return The username that is stored or <tt>null</tt> if none was found
* @deprecated Use {@link NameManager#getAccount(UUID)}
*
* @param uuid The UUID of the player
* @return The username that is stored or <tt>null</tt> if none was found
* @deprecated Use {@link NameManager#getAccount(UUID)}
*/
@Deprecated
public static String getUsername(UUID uuid) {
@ -184,10 +190,11 @@ public class NameManager {
/**
* Get the full username from another username that might be shortened
*
* @param shortName The name of the player to get the full username for
* @return The full username or <tt>null</tt> if none was found
* @return The full username or <tt>null</tt> if none was found
* @throws IllegalArgumentException if the username is not a shortened name and longer than 15 chars
* @deprecated Use {@link NameManager#getAccountFromShortName(String)}
* @deprecated Use {@link NameManager#getAccountFromShortName(String)}
*/
@Deprecated
public static String getFullUsername(String shortName) {
@ -200,9 +207,10 @@ public class NameManager {
/**
* Get the short username from a full username
* @param fullName The name of the player to get the short username for
* @return The short username or <tt>null</tt> if none was found
* @deprecated Use {@link NameManager#getAccount(String)}
*
* @param fullName The name of the player to get the short username for
* @return The short username or <tt>null</tt> if none was found
* @deprecated Use {@link NameManager#getAccount(String)}
*/
@Deprecated
public static String getShortUsername(String fullName) {
@ -212,7 +220,8 @@ public class NameManager {
/**
* Store the username of a player into the database and the username-uuid cache
* @param player The data transfer object of the player to store
*
* @param player The data transfer object of the player to store
*/
public static void storeUsername(final PlayerDTO player) {
final UUID uuid = player.getUniqueId();
@ -243,8 +252,9 @@ public class NameManager {
/**
* Get a new unique shortened name that hasn't been used by another player yet
* @param player The player data to get the shortened name for
* @return A new shortened name that hasn't been used before and is a maximum of 15 chars long
*
* @param player The player data to get the shortened name for
* @return A new shortened name that hasn't been used before and is a maximum of 15 chars long
*/
private static String getNewShortenedName(PlayerDTO player) {
String shortenedName = NameUtil.stripUsername(player.getName());
@ -302,9 +312,9 @@ public class NameManager {
e.printStackTrace();
}
}
public static Account getServerEconomyAccount() {
return serverEconomyAccount;
}
}

View File

@ -29,17 +29,17 @@ public class uBlock {
return sign;
}
public static Sign getConnectedSign(Block block) {
Sign sign = uBlock.findAnyNearbyShopSign(block);
if (sign == null) {
Block neighbor = findNeighbor(block);
if (neighbor != null) {
sign = uBlock.findAnyNearbyShopSign(neighbor);
}
}
return sign;
}
@ -61,15 +61,15 @@ public class uBlock {
}
return findConnectedChest(block, signFace);
}
private static Chest findConnectedChest(Block block, BlockFace signFace) {
if (signFace != null ) {
if (signFace != null) {
Block faceBlock = block.getRelative(signFace);
if (BlockUtil.isChest(faceBlock)) {
return (Chest) faceBlock.getState();
}
}
for (BlockFace bf : SHOP_FACES) {
if (bf != signFace) {
Block faceBlock = block.getRelative(bf);
@ -121,12 +121,12 @@ public class uBlock {
}
return null;
}
public static Chest findNeighbor(Chest chest) {
Block neighbor = findNeighbor(chest.getBlock());
return neighbor != null ? (Chest) neighbor.getState() : null;
}
public static Block findNeighbor(Block block) {
for (BlockFace blockFace : CHEST_EXTENSION_FACES) {
Block neighborBlock = block.getRelative(blockFace);