Makes ItemCase compile for Minecraft 1.17

This commit is contained in:
Kristian Knarvik 2021-10-27 17:27:34 +02:00
parent a9f1d9e5e7
commit 90b0223d8d
28 changed files with 1671 additions and 1989 deletions

View File

@ -16,11 +16,12 @@ Compiling
---------
ItemCase uses Maven to handle its dependencies.
* Install [Maven 2 or 3](http://maven.apache.org/download.html)
* Install [Maven 2 or 3](http://maven.apache.org/download.html)
* Checkout this repo and run: `mvn clean`
Coding and Pull Request Formatting
----------------------------------
* Generally follow the Oracle coding standards.
* Use spaces not tabs.
* No trailing whitespaces.
@ -31,6 +32,9 @@ Coding and Pull Request Formatting
**Please try to follow the above conventions if you want your pull request(s) accepted.**
[License]: http://www.gnu.org/licenses/gpl.html
[GitHub]: http://github.com/BleedObsidian/ItemCase/
[Bukkit]: http://dev.bukkit.org/bukkit-plugins/itemcase/
[Javadoc]: http://bleedobsidian.github.io/ItemCase/

114
pom.xml
View File

@ -1,85 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gmail.bleedobsidian</groupId>
<artifactId>ItemCase</artifactId>
<name>ItemCase</name>
<description>ItemCase is a Bukkit plugin allowing you to showcase items on slabs, that can also be used as shops.</description>
<description>ItemCase is a Bukkit plugin allowing you to showcase items on slabs, that can also be used as shops.
</description>
<version>2.0.0</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>16</maven.compiler.source>
<maven.compiler.target>16</maven.compiler.target>
</properties>
<repositories>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
<id>sk89q-repo</id>
<url>https://maven.enginehub.org/repo/</url>
</repository>
<repository>
<id>bstats-repo</id>
<url>http://repo.bstats.org/content/repositories/releases/</url>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
</repository>
<repository>
<id>vault-repo</id>
<url>http://nexus.hc.to/content/repositories/pub_releases</url>
</repository>
<repository>
<id>sk89q-repo</id>
<url>http://maven.sk89q.com/repo/</url>
<id>OnARandomBox</id>
<url>https://repo.onarandombox.com/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.12.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.12.2-R0.1-SNAPSHOT</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId>
<version>1.2</version>
<scope>compile</scope>
<version>1.17.1-R0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.onarandombox.multiversecore</groupId>
<artifactId>Multiverse-Core</artifactId>
<version>2.5.0</version>
<version>4.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.6</version>
<version>1.7</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard</artifactId>
<version>6.2.1</version>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.7.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.7.1</version>
<scope>test</scope>
<artifactId>worldguard-bukkit</artifactId>
<version>7.0.7-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>
@ -108,52 +87,19 @@
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<addMavenDescriptor>false</addMavenDescriptor>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
<version>3.2.0</version>
<configuration>
<finalName>${artifactId}</finalName>
<artifactSet>
<excludes>
<exclude>org.bukkit</exclude>
<exclude>net.milkbowl.vault</exclude>
<exclude>junit</exclude>
<exclude>com.sk89q.worldguard</exclude>
</excludes>
<includes>
<include>org.bstats:*</include>
</includes>
</artifactSet>
<relocations>
<relocation>
<pattern>org.bstats</pattern>
<shadedPattern>com.gmail.bleedobsidian</shadedPattern>
</relocation>
</relocations>
<archive>
<addMavenDescriptor>false</addMavenDescriptor>
</archive>
</configuration>
</plugin>
</plugins>

View File

@ -18,17 +18,17 @@ import org.bukkit.command.CommandSender;
/**
* An interface for all ItemCase commands.
*
*
* @author Jesse Prescott (BleedObsidian)
*/
public interface Command {
/**
* Execute this command with the given arguments.
*
*
* @param sender The command sender.
* @param label The label used,
* @param args Any arguments.
* @param label The label used,
* @param args Any arguments.
*/
public void execute(CommandSender sender, String label, String[] args);
void execute(CommandSender sender, String label, String[] args);
}

View File

@ -14,42 +14,43 @@
*/
package com.gmail.bleedobsidian.itemcase;
import com.gmail.bleedobsidian.itemcase.loggers.GenericLogger;
import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import com.gmail.bleedobsidian.itemcase.commands.CreateCommand;
import com.gmail.bleedobsidian.itemcase.commands.ModifyCommand;
import com.gmail.bleedobsidian.itemcase.commands.DestroyCommand;
import com.gmail.bleedobsidian.itemcase.commands.ModifyCommand;
import com.gmail.bleedobsidian.itemcase.commands.OrderCommand;
import com.gmail.bleedobsidian.itemcase.commands.StorageCommand;
import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import com.gmail.bleedobsidian.itemcase.loggers.GenericLogger;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
/**
* The central command handler for all ItemCase commands.
*
*
* @author Jesse Prescott (BleedObsidian)
*/
public final class CommandHandler implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command,
@NotNull String label, String[] args) {
// Check we have atleast 1 argument (sub-command label).
if(args.length <= 0) {
if (args.length <= 0) {
// Show help message.
this.showHelp(sender, label);
// We have handled this error.
return true;
}
// Direct sub-command to corresponding command handler.
switch(args[0]) {
switch (args[0]) {
case "create":
new CreateCommand().execute(sender, label, args);
break;
@ -69,59 +70,58 @@ public final class CommandHandler implements CommandExecutor {
this.showHelp(sender, label);
break;
}
// We have handled this command.
return true;
}
/**
* Show help for main command to given sender.
*
*
* @param sender CommandSender.
*/
private void showHelp(CommandSender sender, String label) {
// Get translator.
LanguageTranslator translator = ItemCaseCore.instance.getTranslator();
// Set placeholder to blank.
translator.setPlaceholder("%COMMAND%", "");
// Set label placeholder.
translator.setPlaceholder("%LABEL%", label);
// Set placeholder.
String command = "/" + label + " [create/order/destroy/modify/storage]";
// Check if sender is a player or console.
if(sender instanceof Player) {
if (sender instanceof Player player) {
// Cast sender to player.
Player player = (Player) sender;
// Get chat logger.
ChatLogger logger = ItemCaseCore.instance.getChatLogger();
// Send message to player.
logger.message(player, "command.itemcase-help");
// Send message to player.
logger.message(player, command);
// Send message to player.
logger.message(player, "command.command-help");
} else {
// Get console logger.
GenericLogger logger = ItemCaseCore.instance.getGenericLogger();
// Send console message.
logger.message(sender, "command.itemcase-help");
// Send console message.
logger.message(sender, command);
// Send console message.
logger.message(sender, "command.command-help");
}

View File

@ -14,202 +14,200 @@
*/
package com.gmail.bleedobsidian.itemcase;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
/**
* An object with a corresponding configuration file that can be loaded/saved.
*
*
* @author Jesse Prescott (BleedObsidian)
*/
public class ConfigurationFile {
/**
* FileConfiguration handle.
*/
protected FileConfiguration file;
/**
* The name of this configuration file.
*/
private String name;
private final String name;
/**
* The name of the default file in the jar.
*/
private String defaultName;
private final String defaultName;
/**
* If this configuration file can be copied outside of the jar.
*/
private boolean canCopy = true;
/**
* @param name The name of this configuration file.
* @param name The name of this configuration file.
* @param defaultName The name of the default file in the jar.
*/
public ConfigurationFile(String name, String defaultName) {
// Set name.
this.name = name;
this.defaultName = defaultName;
}
/**
* @param name The name of this configuration file.
*/
public ConfigurationFile(String name) {
// Set name.
this.name = name;
this.defaultName = name;
}
/**
* @param name The name of this configuration file.
* @param name The name of this configuration file.
* @param canCopy If configuration file can be copied outside of the jar.
*/
public ConfigurationFile(String name, boolean canCopy) {
// Set name.
this.defaultName = name;
this.name = name;
// Set canCopy.
this.canCopy = canCopy;
}
/**
* Loads this configuration file from the given plugin's data folder, if it
* does not exist, it is copied from the plugins jar.
*
*
* @param plugin JavaPlugin.
* @throws IOException.
*/
public void load(JavaPlugin plugin) throws IOException {
// If this configuration file can be copied outside of the jar...
if(this.canCopy) {
if (this.canCopy) {
// Create file reference.
File fileReference = new File(plugin.getDataFolder(), this.name);
// If the file doesn't exist...
if(!fileReference.exists() && this.canCopy) {
if (!fileReference.exists() && this.canCopy) {
// Copy default config from jar to data folder.
this.copyDefault(plugin);
}
// Attempt to load it.
this.file = YamlConfiguration.loadConfiguration(fileReference);
// Exit.
return;
}
// Attempt to create an input stream reader of the file in the jar.
InputStreamReader inputStreamReader =
InputStreamReader inputStreamReader =
new InputStreamReader(plugin.getResource(this.name));
// Attempt to load it.
this.file = YamlConfiguration.loadConfiguration(inputStreamReader);
}
/**
* Delete this configuration file, non-jar only.
*
*
* @param plugin JavaPlugin.
*/
public void delete(JavaPlugin plugin) {
// Create file reference.
File fileReference = new File(plugin.getDataFolder(), this.name);
// Nullify reference.
this.file = null;
// Delete file.
fileReference.delete();
}
/**
* Attempt to copy the default configuration file from the given plugin's
* jar to the data folder.
*
*
* @param plugin JavaPlugin.
* @throws IOException.
*/
private void copyDefault(JavaPlugin plugin) throws IOException {
// Create reference to output file.
File outputFile = new File(plugin.getDataFolder(), this.name);
// Attempt to create an input stream of the default file in the jar.
InputStream inputStream = plugin.getResource(this.defaultName);
// Check if we succeeded.
if(inputStream == null) {
if (inputStream == null) {
// Throw exception.
throw new IOException("Failed to create input stream to default"
+ " file.");
}
// Create initial file.
outputFile.getParentFile().mkdirs();
// Copy file.
Files.copy(inputStream, outputFile.toPath(),
Files.copy(inputStream, outputFile.toPath(),
StandardCopyOption.REPLACE_EXISTING);
}
/**
* Save this configuration file in the given plugin's data folder.
*
*
* @param plugin Plugin.
* @throws IOException.
*/
public void save(JavaPlugin plugin) throws IOException {
// If this configuration file can not be copied outside of the jar...
if(!this.canCopy) {
if (!this.canCopy) {
// Exit.
return;
}
// Create reference to output file.
File outputFile = new File(plugin.getDataFolder(), this.name);
// Attempt to save file.
this.file.save(outputFile);
}
/**
* Check if this file contains the given key.
*
*
* @param key Key.
* @return Boolean.
*/
public boolean hasKey(String key) {
// Return if key exists.
return this.file.contains(key);
}
/**
* @return If file is loaded.
*/
public boolean isLoaded() {
// Return true if file is not null.
return this.file != null;
}

View File

@ -19,40 +19,40 @@ import org.bukkit.inventory.ItemStack;
/**
* Static utility helper methods for inventories.
*
*
* @author Jesse Prescott (BleedObsidian).
*/
public final class InventoryUtils {
/**
* Count the number of given ItemStacks exist in the given Inventory.
*
*
* @param inventory Inventory.
* @param itemstack ItemStack to count.
* @return Count.
*/
public static int count(Inventory inventory, ItemStack itemstack) {
// Define stock.
int stock = 0;
// For every itemstack.
for(ItemStack content : inventory.getContents()) {
for (ItemStack content : inventory.getContents()) {
// If content is null, skip.
if(content == null)
if (content == null)
continue;
// If itemstacks match.
if(content.isSimilar(itemstack)) {
if (content.isSimilar(itemstack)) {
// Add amount to stock.
stock += content.getAmount();
}
}
// Return stock.
return stock;
}
}

View File

@ -15,20 +15,21 @@
package com.gmail.bleedobsidian.itemcase;
import com.gmail.bleedobsidian.itemcase.loggers.ConsoleLogger;
import com.gmail.bleedobsidian.itemcase.loggers.GenericLogger;
import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import com.gmail.bleedobsidian.itemcase.Itemcase.ItemcaseListener;
import com.gmail.bleedobsidian.itemcase.configurations.ConfigFile;
import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import com.gmail.bleedobsidian.itemcase.loggers.ConsoleLogger;
import com.gmail.bleedobsidian.itemcase.loggers.GenericLogger;
import com.gmail.bleedobsidian.itemcase.managers.ItemcaseManager;
import com.gmail.bleedobsidian.itemcase.managers.OrderManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import java.io.IOException;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.IOException;
/**
* ItemCase is a Bukkit plugin allowing you to showcase items on slabs, that
* can also be used as shops.
@ -36,63 +37,63 @@ import org.bukkit.plugin.java.JavaPlugin;
* @author Jesse Prescott (BleedObsidian)
*/
public final class ItemCaseCore extends JavaPlugin {
/**
* Current running instance of ItemCaseCore.
*/
public static ItemCaseCore instance;
/**
* Main ItemCase configuration file.
*/
private final ConfigFile configFile = new ConfigFile();
/**
* The language translator.
*/
private final LanguageTranslator translator = new LanguageTranslator();
/**
* Custom plugin console logger.
*/
private final ConsoleLogger consoleLogger = new ConsoleLogger(this,
translator);
/**
* Chat logger.
*/
private final ChatLogger chatLogger = new ChatLogger(translator);
/**
* Generic Logger.
*/
private final GenericLogger genericLogger = new GenericLogger(translator);
/**
* ItemcaseManager.
*/
private final ItemcaseManager itemcaseManager = new ItemcaseManager();
private final ItemcaseManager itemcaseManager = new ItemcaseManager();
/**
* OrderManager.
*/
private final OrderManager orderManager = new OrderManager();
/**
* If the server has Vault.
*/
private boolean hasVault;
/**
* If the server has WorldGuard.
*/
private boolean hasWorldGuard;
/**
* The economy provider if there is one.
*/
private Economy economyProvider;
/**
* WorldGuard.
*/
@ -100,216 +101,212 @@ public final class ItemCaseCore extends JavaPlugin {
@Override
public void onEnable() {
// Set current instance.
ItemCaseCore.instance = this;
// Start metrics.
PluginMetrics metrics = new PluginMetrics(this);
// Attempt to load configuration file.
try {
// Load configuration file.
this.configFile.load(this);
} catch (IOException e) {
// Display error.
this.consoleLogger.severe("Failed to load configuration file.", e);
// Stop loading.
return;
}
// Attempt to load translator with given locale.
if(!this.translator.load(this, this.configFile.getLocale())) {
if (!this.translator.load(this, this.configFile.getLocale())) {
// Failed to load, stop loading.
return;
}
// Log.
this.consoleLogger.info("console.info.config-loaded");
// Set language placeholder and log.
this.translator.setPlaceholder("%LANGUAGE%",
this.configFile.getLocale().name());
this.consoleLogger.info("console.info.locale");
// Initialize ItemcaseManager.
this.itemcaseManager.registerListener();
// Register ItemcaseListener.
this.getServer().getPluginManager().registerEvents(
new ItemcaseListener(), this);
// Load itemcases for already loaded worlds.
this.itemcaseManager.initialize();
// Set command executor.
this.getCommand("itemcase").setExecutor(new CommandHandler());
// Attempt to load Vault.
this.loadVault();
// Attempt to load WorldGuard.
this.loadWorldGuard();
// Set version placeholder and log.
this.translator.setPlaceholder("%VERSION%",
this.getDescription().getVersion());
this.consoleLogger.info("console.info.enabled");
}
@Override
public void onDisable() {
// Unload all itemcases.
this.itemcaseManager.unloadItemcases();
// Log.
this.consoleLogger.info("console.info.unloaded");
}
/**
* Attempt to load Vault.
*/
private void loadVault() {
// Check if this server has Vault installed.
if(getServer().getPluginManager().getPlugin("Vault") == null) {
if (getServer().getPluginManager().getPlugin("Vault") == null) {
// Set false.
this.hasVault = false;
// Exit.
return;
}
// Get server provider of economy class.
RegisteredServiceProvider<Economy> rsp =
getServer().getServicesManager().getRegistration(Economy.class);
// If could not find economy service provider.
if(rsp == null) {
if (rsp == null) {
// Set false.
this.hasVault = false;
// Exit.
return;
}
// Log.
this.consoleLogger.info("console.info.vault-hooked");
// Set economy provider.
this.economyProvider = rsp.getProvider();
// Set true.
this.hasVault = true;
}
/**
* Attempt to load WorldGuard.
*/
private void loadWorldGuard() {
// Get plugin.
Plugin plugin = getServer().getPluginManager().getPlugin("WorldGuard");
// Check if the server has WorldGuard installed.
if(plugin == null) {
if (plugin == null) {
// Set false.
this.hasWorldGuard = false;
// Exit.
return;
}
// Log.
this.consoleLogger.info("console.info.worldguard-hooked");
// Set true.
this.hasWorldGuard = true;
// Set worldguard.
this.worldGuard = (WorldGuardPlugin) plugin;
}
/**
/**
* @return Main ItemCase configuration file.
*/
public ConfigFile getConfigFile() {
return this.configFile;
}
/**
* @return Language translator.
*/
public LanguageTranslator getTranslator() {
return this.translator;
}
/**
* @return Custom plugin console logger.
*/
public ConsoleLogger getConsoleLogger() {
return this.consoleLogger;
}
/**
* @return Chat logger.
*/
public ChatLogger getChatLogger() {
return this.chatLogger;
}
/**
* @return Generic Logger.
*/
public GenericLogger getGenericLogger() {
return this.genericLogger;
}
/**
* @return Itemcase manager.
*/
public ItemcaseManager getItemcaseManager() {
return this.itemcaseManager;
}
/**
* @return OrderManager.
*/
public OrderManager getOrderManager() {
return this.orderManager;
}
/**
* @return If vault is setup on this server.
*/
public boolean hasVault() {
return this.hasVault;
}
/**
* @return If WorldGuard is setup on this server.
*/
public boolean hasWorldGuard() {
return this.hasWorldGuard;
}
/**
* @return EconomyProvider.
*/
public Economy getEconomyProvider() {
return this.economyProvider;
}
/**
* @return WorldGuard.
*/

View File

@ -16,15 +16,13 @@
package com.gmail.bleedobsidian.itemcase;
import com.gmail.bleedobsidian.itemcase.managers.ItemcaseManager;
import java.util.ArrayList;
import java.util.Collection;
import java.util.UUID;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.Tag;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
@ -45,314 +43,318 @@ import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import java.util.Collection;
import java.util.UUID;
/**
* Handler of an Itemcase.
*
* @author Jesse Prescott (BleedObsidian)
*/
public final class Itemcase {
/**
* The name of the inventory for Itemcase storage.
*/
public static final String INVENTORY_NAME = "ItemCase Storage";
/**
* Types of Itemcase.
*/
public static enum Type {
public enum Type {
SHOWCASE,
SHOP_BUY,
SHOP_SELL,
SHOP_MULTI
};
}
/**
* Storage types.
*/
public static enum StorageType {
public enum StorageType {
FINITE,
INFINITE
}
/**
* The ItemStack that this itemcase is showing.
*/
private final ItemStack itemStack;
/**
* The Location of this itemcase.
*/
private final Location location;
/**
* The chunk that this itemcase is in.
*/
private final Chunk chunk;
/**
* The owner of this itemcase.
*/
private final OfflinePlayer owner;
/**
* This itemcase's task.
*/
private ItemcaseTask task;
/**
* The active item that is currently on display.
*/
private Item displayItem;
/**
* This itemcase's Type.
*/
private Type type = Type.SHOWCASE;
private Type type;
/**
* The storage type of this itemcase.
*/
private StorageType storageType = StorageType.FINITE;
/**
* The storage of this itemcase.
*/
private Inventory storage;
/**
* The buy price of this itemcase.
*/
private double buyPrice = 0;
/**
* The sell price of this itemcase.
*/
private double sellPrice = 0;
/**
* Constructor.
*
* @param type The type of Itemcase.
*
* @param type The type of Itemcase.
* @param itemStack The ItemStack to be displayed.
* @param location The location of the itemcase.
* @param owner The owner of this itemcase.
* @param location The location of the itemcase.
* @param owner The owner of this itemcase.
*/
public Itemcase(Type type, ItemStack itemStack, Location location,
OfflinePlayer owner) {
OfflinePlayer owner) {
// Check params are not null.
Validate.notNull(type, "Itemcase type can not be null.");
Validate.notNull(itemStack, "Itemstack can not be null.");
Validate.notNull(location, "Location can not be null.");
Validate.notNull(owner, "Owner can not be null.");
// Set type.
this.type = type;
// Set item stack and ensure stack size is 1.
this.itemStack = itemStack.clone();
this.itemStack.setAmount(1);
// Set location.
this.location = location;
// Set the chunk. Accessing the chunk with location.getChunk() when we
// need it causes the chunk to load, meaning the chunk appears as always
// loaded. Storing it now means we can actually see when it becomes
// unloaded.
this.chunk = location.getChunk();
// Set owner.
this.owner = owner;
}
/**
* Spawn the display item.
*/
public void spawnItem() {
public void spawnItem() {
// Get the world that this itemcase is in.
World world = this.location.getWorld();
// If task task was previously cancelled or never made.
if(this.task == null || this.task.isCancelled()) {
if (this.task == null || this.task.isCancelled()) {
// Schedule itemcase task to execute every 200 server
// ticks (10 secs).
this.task = new ItemcaseTask(this);
this.task.runTaskTimer(ItemCaseCore.instance, 0, 200);
}
// Check if the chunk is currently loaded.
if(!world.isChunkLoaded(this.chunk)) {
if (!world.isChunkLoaded(this.chunk)) {
// Not loaded, so don't try to spawn display item.
return;
}
// If there was a display item previously.
if(this.displayItem != null) {
if (this.displayItem != null) {
// Remove this item.
this.displayItem.remove();
}
// Get the location to spawn the display item at.
Location displayItemSpawnLocation = this.getDisplayItemSpawnLocation();
// Get itemstack.
ItemStack itemStack = this.itemStack.clone();
// Set display name to random UUID to prevent graphical item stacking.
ItemMeta metadata = itemStack.getItemMeta();
metadata.setDisplayName("com.gmail.bleedobsidian.itemcase:" +
UUID.randomUUID().toString());
UUID.randomUUID());
itemStack.setItemMeta(metadata);
// Spawn the item.
this.displayItem = this.location.getWorld().dropItem(
displayItemSpawnLocation, itemStack);
// Add custom metadata so we know that this item is a display item and
// shouldn't be picked up by players and which itemcase it belongs to.
this.displayItem.setMetadata("ItemCase", new FixedMetadataValue(
ItemCaseCore.instance, this.location.toVector()));
// Prevent the item from having a random veloctiy when spawning so that
// it falls directly down in to the middle of the block.
this.displayItem.setVelocity(new Vector(0, 0, 0));
}
/**
* Despawn the display item for this itemcase.
*/
public void despawnItem() {
// Cancel running task.
this.task.cancel();
// Remove current display item from world.
this.displayItem.remove();
}
/**
* Checks if a given item entity is an itemcase display item of any kind.
*
*
* @param item Item.
* @return Boolean.
*/
private static boolean isItemcaseDisplayItem(Item item) {
// If item does not have a display name, it can't be a display item.
if(!item.getItemStack().getItemMeta().hasDisplayName()) {
if (!item.getItemStack().getItemMeta().hasDisplayName()) {
return false;
}
// Attempt to split display name by ':'
String[] displayNameParts =
String[] displayNameParts =
item.getItemStack().getItemMeta().getDisplayName().split(":");
// If display name does not have exactly two parts, it can't be a
// display item.
if(displayNameParts.length != 2) {
if (displayNameParts.length != 2) {
return false;
}
// Check if item belongs to us, if it does return true.
return displayNameParts[0].equals("com.gmail.bleedobsidian.itemcase");
}
/**
* Take stock from storage.
*
*
* @param amount Amount to take.
*/
public void takeStock(int amount) {
// If storage is infinite.
if(this.storageType == StorageType.INFINITE) {
if (this.storageType == StorageType.INFINITE) {
// Exit.
return;
}
// Get items.
ItemStack items = this.itemStack.clone();
items.setAmount(amount);
// Remove from storage.
this.storage.removeItem(items);
// Save.
ItemCaseCore.instance.getItemcaseManager().saveItemcases(this);
}
/**
/**
* Add stock to storage.
*
*
* @param amount Amount to add.
*/
public void addStock(int amount) {
// If storage is infinite.
if(this.storageType == StorageType.INFINITE) {
if (this.storageType == StorageType.INFINITE) {
// Exit.
return;
}
// Get items.
ItemStack items = this.itemStack.clone();
items.setAmount(amount);
// Add to storage.
this.storage.addItem(items);
// Save.
ItemCaseCore.instance.getItemcaseManager().saveItemcases(this);
}
/**
* @param amount The amount of items needed.
* @return If the itemcase has enough in stock.
*/
public boolean hasEnough(int amount) {
// If storage is infinite.
if(this.storageType == StorageType.INFINITE) {
if (this.storageType == StorageType.INFINITE) {
// Return true.
return true;
}
// Return if storage contains enough.
return this.storage.containsAtLeast(this.itemStack, amount);
}
/**
* @return The amount of stock this itemcase has.
*/
public int getStockLevel() {
// Return count.
return InventoryUtils.count(this.storage, this.itemStack);
}
/**
* @return The ItemStack that this itemcase is showing.
*/
public ItemStack getItemStack() {
// The ItemStack of this Itemcase.
return this.itemStack;
}
/**
* @return The Location of this itemcase.
*/
public Location getLocation() {
// Location of this itemcase.
return this.location;
}
@ -361,158 +363,154 @@ public final class Itemcase {
* @return The owner of this itemcase.
*/
public OfflinePlayer getOwner() {
// Owner of this itemcase.
return this.owner;
}
/**
* @return Display item.
*/
public Item getDisplayItem() {
// Display item.
return this.displayItem;
}
/**
* @param type Type.
*/
public void setType(Type type) {
// Set type.
this.type = type;
}
/**
* @return Type.
*/
public Type getType() {
// Return type.
return this.type;
}
/**
* @param storageType StorageType.
*/
public void setStorageType(StorageType storageType) {
// If toggling from finite to infinite.
if(this.storageType == StorageType.FINITE &&
if (this.storageType == StorageType.FINITE &&
storageType == StorageType.INFINITE) {
// Set storage.
this.storage =
this.storage =
Bukkit.createInventory(null, 54, Itemcase.INVENTORY_NAME);
}
// Set storage type.
this.storageType= storageType;
this.storageType = storageType;
}
/**
* @return Storage Type.
*/
public StorageType getStorageType() {
// Return storage type.
return this.storageType;
}
/**
* @param inventory Inventory.
*/
public void setStorage(Inventory inventory) {
// Set inventory.
this.storage = inventory;
}
/**
* @return Inventory.
*/
public Inventory getStorage() {
// Return inventory.
return this.storage;
}
/**
* @param buyPrice Buy price.
*/
public void setBuyPrice(double buyPrice) {
// Set price.
this.buyPrice = buyPrice;
}
/**
* @return Buy price.
*/
public double getBuyPrice() {
// Return price.
return this.buyPrice;
}
/**
* @param buyPrice Sell price.
* @param sellPrice Sell price.
*/
public void setSellPrice(double sellPrice) {
// Set price.
this.sellPrice = sellPrice;
}
/**
* @return Sell price.
*/
public double getSellPrice() {
// Return price.
return this.sellPrice;
}
/**
* @return The default location to spawn the display item.
*/
public Location getDisplayItemSpawnLocation() {
// Get block type of this itemcase.
Material type = this.location.getBlock().getType();
// The relative Y coordinate.
double relY = 0;
double relY;
// If block is a slab.
if(type == Material.STEP ||
type == Material.STONE_SLAB2 ||
type == Material.WOOD_STEP ||
type == Material.PURPUR_SLAB) {
if (Tag.SLABS.isTagged(type)) {
// Set relY.
relY = 0.6;
} else {
// Set relY.
relY = 1.6;
}
// Create a location that is in the centre of the block and slightly
// above.
Location displayItemLocation = new Location(
// Return the default location to spawn the display item.
return new Location(
this.location.getWorld(),
this.location.getBlockX() + 0.5,
this.location.getBlockY() + relY,
this.location.getBlockZ() + 0.5);
// Return the default location to spawn the display item.
return displayItemLocation;
}
/**
* A listener used for the functionality of an itemcase. This listener is
* A listener used for the functionality of an itemcase. This listener is
* used to prevent display items from being picked up or despawned.
*/
public static final class ItemcaseListener implements Listener {
@ -521,71 +519,68 @@ public final class Itemcase {
public void onEntityPickupItem(EntityPickupItemEvent event) {
// If this item entity is a display item.
if(Itemcase.isItemcaseDisplayItem(event.getItem())) {
if (Itemcase.isItemcaseDisplayItem(event.getItem())) {
// Prevent this item from being picked up.
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onItemDespawn(ItemDespawnEvent event) {
// If this item entity is a display item.
if(Itemcase.isItemcaseDisplayItem(event.getEntity())) {
if (Itemcase.isItemcaseDisplayItem(event.getEntity())) {
// Prevent this item from despawning.
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onBlockBreakEvent(BlockBreakEvent event) {
// Get ItemcaseManager.
ItemcaseManager itemcaseManager =
ItemcaseManager itemcaseManager =
ItemCaseCore.instance.getItemcaseManager();
// For every Itemcase.
for(Itemcase itemcase : itemcaseManager.getItemcases()) {
for (Itemcase itemcase : itemcaseManager.getItemcases()) {
// Check if this block was an itemcase.
if(itemcase.location.equals(event.getBlock().getLocation())) {
if (itemcase.location.equals(event.getBlock().getLocation())) {
// Cancel the event.
event.setCancelled(true);
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onBlockPlaceEvent(BlockPlaceEvent event) {
// Get ItemcaseManager.
ItemcaseManager itemcaseManager =
ItemcaseManager itemcaseManager =
ItemCaseCore.instance.getItemcaseManager();
// For every Itemcase.
for(Itemcase itemcase : itemcaseManager.getItemcases()) {
for (Itemcase itemcase : itemcaseManager.getItemcases()) {
// Get block type.
Material type = itemcase.getLocation().getBlock().getType();
// Check if the block placed was on an itemcase.
if(itemcase.location.equals(event.getBlock().getLocation())) {
if (itemcase.location.equals(event.getBlock().getLocation())) {
// Cancel the event.
event.setCancelled(true);
}
// If not a slab.
if(type != Material.STEP &&
type != Material.WOOD_STEP &&
type != Material.STONE_SLAB2 &&
type != Material.PURPUR_SLAB) {
if (Tag.SLABS.isTagged(type)) {
// Check if the block placed was 1 above an itemcase.
if(itemcase.location.clone().add(0, 1, 0)
if (itemcase.location.clone().add(0, 1, 0)
.equals(event.getBlock().getLocation())) {
// Cancel the event.
@ -594,179 +589,178 @@ public final class Itemcase {
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerInteractEvent(PlayerInteractEvent event) {
// Check if block was involved.
if(!event.hasBlock()) {
if (!event.hasBlock()) {
// Exit.
return;
}
// Check if action was correct.
if(event.getAction() != Action.RIGHT_CLICK_BLOCK) {
if (event.getAction() != Action.RIGHT_CLICK_BLOCK) {
// Exit.
return;
}
// If off-hand, skip.
if(event.getHand() == EquipmentSlot.OFF_HAND) {
if (event.getHand() == EquipmentSlot.OFF_HAND) {
// Exit.
return;
}
// If player is sneaking.
if(event.getPlayer().isSneaking()) {
if (event.getPlayer().isSneaking()) {
// Exit.
return;
}
// If block is not an ItemCase.
if(!ItemCaseCore.instance.getItemcaseManager().isItemcase(
if (!ItemCaseCore.instance.getItemcaseManager().isItemcase(
event.getClickedBlock().getLocation())) {
// Exit.
return;
// Exit.
return;
}
// Get itemcase.
Itemcase itemcase = ItemCaseCore.instance.getItemcaseManager()
.getItemcase(event.getClickedBlock().getLocation());
// If itemcase is not a shop.
if(itemcase.getType() == Type.SHOWCASE) {
if (itemcase.getType() == Type.SHOWCASE) {
// Exit.
return;
}
// Create new order.
ItemCaseCore.instance.getOrderManager().createOrder(itemcase,
ItemCaseCore.instance.getOrderManager().createOrder(itemcase,
event.getPlayer());
// Cancel event.
event.setCancelled(true);
}
}
/**
* A runnable task that is executed every 10 seconds to check if an
* A runnable task that is executed every 10 seconds to check if an
* itemcase's display item is for some reason dead or has been moved. This
* is particularly useful when servers use anti-lag plugins that forcibly
* kill entities or a player has somehow caused an item to move.
*/
public final class ItemcaseTask extends BukkitRunnable {
public static final class ItemcaseTask extends BukkitRunnable {
/**
* The itemcase that this task is for.
*/
private final Itemcase itemcase;
/**
* Constructor.
*
*
* @param itemcase The itemcase this task is for.
*/
public ItemcaseTask(Itemcase itemcase) {
// Set itemcase.
this.itemcase = itemcase;
}
@Override
public void run() {
// If chunk is not currently loaded.
if(!this.itemcase.chunk.isLoaded()) {
if (!this.itemcase.chunk.isLoaded()) {
// Dont bother running this task.
return;
}
// Get the default display item location.
Location location = this.itemcase.getLocation();
// List of valid materials.
ArrayList<Material> materials =
ArrayList<Material> materials =
ItemCaseCore.instance.getConfigFile().getMaterials();
// Check if this block still exists.
if(!materials.contains(location.getBlock().getType())) {
if (!materials.contains(location.getBlock().getType())) {
// Set to default.
location.getBlock().setType(materials.get(0));
}
// Get all entites near itemcase. (Uses quite a large area just in
// case item is not where it should be).
Collection<Entity> entities = location.getWorld().getNearbyEntities(
location, 5f, 5f, 5f);
// A counter to count how many itemcase items are nearby.
int numberOfItemcaseItems = 0;
// Loop through every entity.
for(Entity entity : entities) {
for (Entity entity : entities) {
// If the entity is not an item, skip.
if(!(entity instanceof Item)) {
if (!(entity instanceof Item)) {
continue;
}
// Check the entity is an ItemCase display item.
if(entity.hasMetadata("ItemCase")) {
if (entity.hasMetadata("ItemCase")) {
// Get the vector location that belongs to this itemcase
// item.
Vector entityVector = (Vector) ((FixedMetadataValue)
entity.getMetadata("ItemCase").get(0)).value();
Vector entityVector = (Vector) entity.getMetadata("ItemCase").get(0).value();
// Check that the entity is an item for this itemcase only.
if(entityVector.getBlockX() !=
if (entityVector.getBlockX() !=
this.itemcase.location.getBlockX() ||
entityVector.getBlockY() !=
this.itemcase.location.getBlockY() ||
entityVector.getBlockZ() !=
this.itemcase.location.getBlockZ()) {
entityVector.getBlockY() !=
this.itemcase.location.getBlockY() ||
entityVector.getBlockZ() !=
this.itemcase.location.getBlockZ()) {
// Skip if not.
continue;
}
// Increment counter.
numberOfItemcaseItems++;
// If the entity is not the current item we know about, we
// must have a duplicate caused by nms.
if(this.itemcase.getDisplayItem().getUniqueId().compareTo(
if (this.itemcase.getDisplayItem().getUniqueId().compareTo(
entity.getUniqueId()) != 0) {
// Remove this item.
entity.remove();
} else {
// If the item on the floor has the same UUID, update
// the reference just in case it has changed.
this.itemcase.displayItem = (Item) entity;
}
// If the item has no metadata but is some form of display item.
} else if(Itemcase.isItemcaseDisplayItem((Item) entity)) {
// If the item has no metadata but is some form of display item.
} else if (Itemcase.isItemcaseDisplayItem((Item) entity)) {
// Remove this item as it is probably left over from a
// restart hence no metadata.
entity.remove();
}
}
// If there were no itemcase items nearby.
if(numberOfItemcaseItems == 0) {
if (numberOfItemcaseItems == 0) {
// Spawn a new item as for some reason the item has despawned
// (usually because of anti-lag plugins.)
this.itemcase.spawnItem();
@ -776,13 +770,13 @@ public final class Itemcase {
double x = this.itemcase.getDisplayItem().getLocation().getX();
double y = this.itemcase.getDisplayItem().getLocation().getBlockY();
double z = this.itemcase.getDisplayItem().getLocation().getZ();
// Get the correct spawn location of the display item.
Location displayItemSpawnLocation =
Location displayItemSpawnLocation =
this.itemcase.getDisplayItemSpawnLocation();
// Check if the display item has for some reason moved.
if(x != displayItemSpawnLocation.getX() ||
if (x != displayItemSpawnLocation.getX() ||
y != displayItemSpawnLocation.getBlockY() ||
z != displayItemSpawnLocation.getZ()) {

View File

@ -15,117 +15,118 @@
package com.gmail.bleedobsidian.itemcase;
import com.gmail.bleedobsidian.itemcase.configurations.LanguageFile;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;
import org.bukkit.plugin.java.JavaPlugin;
/**
* Utility class used for communicating in different dialects.
*
*
* @author Jesse Prescott (BleedObsidian).
*/
public final class LanguageTranslator {
/**
* Supported languages.
*/
public static enum Language {
public enum Language {
EN
};
}
/**
* The language file for the chosen language.
*/
private LanguageFile file;
/**
* A hash map of placeholders.
*/
private HashMap<String, String> placeholders = new HashMap<>();
private final HashMap<String, String> placeholders = new HashMap<>();
/**
* Load corresponding language file.
*
* @param plugin JavaPlugin.
*
* @param plugin JavaPlugin.
* @param language Language to communicate in.
* @return If loading was successful.
*/
public boolean load(JavaPlugin plugin, Language language) {
// Create language file.
this.file = new LanguageFile(language);
// Attempt to load language file.
try {
// Load language file.
this.file.load(plugin);
} catch (IOException e) {
// Display error.
ItemCaseCore.instance.getConsoleLogger().severe(
"Failed to load configuration file.", e);
// Failed to load.
return false;
}
// Successfully loaded.
return true;
}
/**
* Get translation.
*
*
* @param key Message key.
* @return String.
*/
public String getTranslation(String key) {
// Get raw translation.
String translation = this.file.getRawTranslation(key);
// For every placeholder.
for(Entry<String, String> entry : this.placeholders.entrySet()) {
for (Entry<String, String> entry : this.placeholders.entrySet()) {
// Replace the placeholder with given value if placeholder is
// present in string.
translation = translation.replace(entry.getKey(), entry.getValue());
}
// Return translation.
return translation;
}
/**
* Set the value of a given placeholder.
*
*
* @param placeholder Placeholder.
* @param value Value.
* @param value Value.
*/
public void setPlaceholder(String placeholder, String value) {
// Update HashMap.
this.placeholders.put(placeholder, value);
}
/**
* If given string is a valid message key.
*
*
* @param string String.
* @return Boolean.
*/
public boolean isKey(String string) {
// If the file is not loaded yet.
if(!this.file.isLoaded()) {
if (!this.file.isLoaded()) {
// Return false as we cant do translations yet.
return false;
}
// Check if key exists and return result.
return this.file.hasKey(string);
}

View File

@ -1,38 +0,0 @@
/*
* ItemCase is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/gpl.html>.
*/
package com.gmail.bleedobsidian.itemcase;
import org.bstats.bukkit.Metrics;
import org.bukkit.plugin.java.JavaPlugin;
/**
* Handles bStats plugin metrics and any custom graphs.
*
* @author Jesse Prescott (BleedObsidian)
*/
public final class PluginMetrics {
/**
* Constructor, starts bStats.
*
* @param plugin The Bukkit JavaPlugin.
*/
public PluginMetrics(JavaPlugin plugin) {
// Start bStats.
Metrics metrics = new Metrics(plugin);
}
}

View File

@ -15,87 +15,90 @@
package com.gmail.bleedobsidian.itemcase.commands;
import com.gmail.bleedobsidian.itemcase.Command;
import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import com.gmail.bleedobsidian.itemcase.ItemCaseCore;
import com.gmail.bleedobsidian.itemcase.LanguageTranslator;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import java.util.ArrayList;
import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
/**
* A command handler for the 'create' command.
*
*
* @author Jesse Prescott (BleedObsidian)
*/
public final class CreateCommand implements Command {
@Override
public void execute(CommandSender sender, String label,
String[] args) {
String[] args) {
// If sender is not a player.
if(!(sender instanceof Player)) {
if (!(sender instanceof Player player)) {
// Send message.
ItemCaseCore.instance.getGenericLogger().message(
sender, "command.not-player");
// Exit.
return;
}
// Cast sender to player.
Player player = (Player) sender;
// Check if player is asking for help.
if(this.isAskingForHelp(player, label, args)) {
if (this.isAskingForHelp(player, label, args)) {
// Exit.
return;
}
// Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// Check if player has permission.
if(!player.hasPermission("itemcase.create")) {
if (!player.hasPermission("itemcase.create")) {
// Send message.
chatLogger.message(player, "command.permission");
// Exit.
return;
}
// List of materials that can be used as itemcases.
ArrayList<Material> materials =
ItemCaseCore.instance.getConfigFile().getMaterials();
// The target location.
Location target = null;
Location target;
// ItemStack to use.
ItemStack itemStack = null;
ItemStack itemStack;
// Get the players target block.
target = player.getTargetBlock(null, 5).getLocation();
// Check if itemcase already exists here.
if(ItemCaseCore.instance.getItemcaseManager().isItemcase(target)) {
if (ItemCaseCore.instance.getItemcaseManager().isItemcase(target)) {
// Show message.
chatLogger.message(player, "command.create.invalid-location");
// Exit.
return;
}
// If target block is not on the list of accepted materials.
if(!materials.contains(target.getBlock().getType())) {
if (!materials.contains(target.getBlock().getType())) {
chatLogger.message(player, String.valueOf(materials));
chatLogger.message(player, String.valueOf(target.getBlock()));
// Show message.
chatLogger.message(player, "command.create.invalid-type");
@ -103,29 +106,21 @@ public final class CreateCommand implements Command {
// Exit.
return;
}
// If this server has WorldGuard.
if(ItemCaseCore.instance.hasWorldGuard()) {
// Get world guard.
WorldGuardPlugin worldGuard = ItemCaseCore.instance.getWorldGuard();
// If player cannot build here.
if(!worldGuard.canBuild(player, target)) {
// Show message.
chatLogger.message(player, "command.create.no-build");
// Exit.
return;
}
}
// Get item in players main hand to use as the Itemcase item.
itemStack = player.getInventory().getItemInMainHand();
//Allow any protection plugins to protect
BlockPlaceEvent event = new BlockPlaceEvent(target.getBlock(), target.getBlock().getState(),
target.getBlock(), itemStack, player, true, EquipmentSlot.HAND);
ItemCaseCore.instance.getServer().getPluginManager().callEvent(event);
if (event.isCancelled() || !event.canBuild()) {
chatLogger.message(player, "command.create.no-build");
return;
}
// If the player is not holding anything...
if(itemStack == null || itemStack.getType() == Material.AIR) {
if (itemStack.getType() == Material.AIR) {
// Show message.
chatLogger.message(player, "command.create.main-hand");
@ -133,51 +128,51 @@ public final class CreateCommand implements Command {
// Exit.
return;
}
// Create itemcase.
ItemCaseCore.instance.getItemcaseManager().createItemcase(
itemStack, target, player);
// Show message.
chatLogger.message(player, "command.create.success");
}
/**
* @return If the command sender is asking for help about this command.
*/
public boolean isAskingForHelp(Player player, String label, String[] args) {
// If args length equals 2.
if(args.length != 2) {
if (args.length != 2) {
// False.
return false;
}
// Get argument.
String argument = args[1];
// If not equal to help.
if(!argument.equalsIgnoreCase("help")) {
if (!argument.equalsIgnoreCase("help")) {
return false;
}
// Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// Get translator.
LanguageTranslator translator = ItemCaseCore.instance.getTranslator();
// Set placeholder.
translator.setPlaceholder("%COMMAND%", "/" + label + " create");
// Show command help.
chatLogger.message(player, "command.itemcase-help");
// Show specific help.
chatLogger.message(player, "command.create.help");
// Return.
return true;
}

View File

@ -15,10 +15,10 @@
package com.gmail.bleedobsidian.itemcase.commands;
import com.gmail.bleedobsidian.itemcase.Command;
import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import com.gmail.bleedobsidian.itemcase.ItemCaseCore;
import com.gmail.bleedobsidian.itemcase.Itemcase;
import com.gmail.bleedobsidian.itemcase.LanguageTranslator;
import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import com.gmail.bleedobsidian.itemcase.managers.ItemcaseManager;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
@ -27,131 +27,130 @@ import org.bukkit.entity.Player;
/**
* A command handler for the 'destroy' command.
*
*
* @author Jesse Prescott (BleedObsidian)
*/
public final class DestroyCommand implements Command {
@Override
public void execute(CommandSender sender, String label,
String[] args) {
String[] args) {
// If sender is not a player.
if(!(sender instanceof Player)) {
if (!(sender instanceof Player player)) {
// Send message.
ItemCaseCore.instance.getGenericLogger().message(
sender, "command.not-player");
// Exit.
return;
}
// Cast sender to player.
Player player = (Player) sender;
// Check if player is asking for help.
if(this.isAskingForHelp(player, label, args)) {
if (this.isAskingForHelp(player, label, args)) {
// Exit.
return;
}
// Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// Check if player has permission (Uses create permission).
if(!player.hasPermission("itemcase.create")) {
if (!player.hasPermission("itemcase.create")) {
// Send message.
chatLogger.message(player, "command.permission");
// Exit.
return;
}
// The target location.
Location target = null;
Location target;
// Get ItemcaseManager.
ItemcaseManager manager = ItemCaseCore.instance.getItemcaseManager();
// Get the players target block.
target = player.getTargetBlock(null, 5).getLocation();
// Check this target is an itemcase.
if(!manager.isItemcase(target)) {
if (!manager.isItemcase(target)) {
// Show message.
chatLogger.message(player, "command.invalid-location");
// Exit.
return;
}
// Get itemcase.
Itemcase itemcase = manager.getItemcase(target);
// Get owner.
OfflinePlayer owner = itemcase.getOwner();
// Check if this player owns this itemcase.
if(!owner.equals(player)) {
if (!owner.equals(player)) {
// Check if player is allowed to destroy other peoples itemcases.
if(!player.hasPermission("itemcase.destroy.other")) {
if (!player.hasPermission("itemcase.destroy.other")) {
// Show message.
chatLogger.message(player, "command.not-owner");
// Exit.
return;
}
}
// Destroy itemcase.
manager.destroyItemcase(itemcase);
// Show message.
chatLogger.message(player, "command.destroy.success");
}
/**
* @return If the command sender is asking for help about this command.
*/
public boolean isAskingForHelp(Player player, String label, String[] args) {
// If args length equals 2.
if(args.length != 2) {
if (args.length != 2) {
// False.
return false;
}
// Get argument.
String argument = args[1];
// If not equal to help.
if(!argument.equalsIgnoreCase("help")) {
if (!argument.equalsIgnoreCase("help")) {
return false;
}
// Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// Get translator.
LanguageTranslator translator = ItemCaseCore.instance.getTranslator();
// Set placeholder.
translator.setPlaceholder("%COMMAND%", "/" + label + " destroy");
// Show command help.
chatLogger.message(player, "command.itemcase-help");
// Show specific help.
chatLogger.message(player, "command.destroy.help");
return true;
}
}

View File

@ -15,12 +15,12 @@
package com.gmail.bleedobsidian.itemcase.commands;
import com.gmail.bleedobsidian.itemcase.Command;
import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import com.gmail.bleedobsidian.itemcase.ItemCaseCore;
import com.gmail.bleedobsidian.itemcase.Itemcase;
import com.gmail.bleedobsidian.itemcase.Itemcase.StorageType;
import com.gmail.bleedobsidian.itemcase.Itemcase.Type;
import com.gmail.bleedobsidian.itemcase.LanguageTranslator;
import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
@ -29,104 +29,103 @@ import org.bukkit.entity.Player;
/**
* A command handler for the 'modify' command.
*
*
* @author Jesse Prescott (BleedObsidian)
*/
public final class ModifyCommand implements Command {
@Override
public void execute(CommandSender sender, String label,
String[] args) {
String[] args) {
// If sender is not a player.
if(!(sender instanceof Player)) {
if (!(sender instanceof Player player)) {
// Send message.
ItemCaseCore.instance.getGenericLogger().message(
sender, "command.not-player");
// Exit.
return;
}
// Cast sender to player.
Player player = (Player) sender;
// Check if player is asking for help.
if(this.isAskingForHelp(player, label, args)) {
if (this.isAskingForHelp(player, label, args)) {
// Exit.
return;
}
// If incorrect number of args.
if(args.length != 3) {
if (args.length != 3) {
// Show help.
this.showHelp(player, label);
// Exit.
return;
}
// Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// Check if player has permission (Uses create permission).
if(!player.hasPermission("itemcase.create")) {
if (!player.hasPermission("itemcase.create")) {
// Send message.
chatLogger.message(player, "command.permission");
// Exit.
return;
}
// The target location.
Location target = null;
Location target;
// Get the players target block.
target = player.getTargetBlock(null, 5).getLocation();
// Check if itemcase exists here.
if(!ItemCaseCore.instance.getItemcaseManager().isItemcase(target)) {
if (!ItemCaseCore.instance.getItemcaseManager().isItemcase(target)) {
// Show message.
chatLogger.message(player, "command.invalid-location");
// Exit.
return;
}
// Get itemcase.
Itemcase itemcase =
Itemcase itemcase =
ItemCaseCore.instance.getItemcaseManager().getItemcase(target);
// Get owner.
OfflinePlayer owner = itemcase.getOwner();
// Check if this player owns this itemcase.
if(!owner.equals(player)) {
if (!owner.equals(player)) {
// Check if player is allowed to modify other peoples itemcases.
if(!player.hasPermission("itemcase.modify.other")) {
if (!player.hasPermission("itemcase.modify.other")) {
// Show message.
chatLogger.message(player, "command.not-owner");
// Exit.
return;
}
}
// Get flag.
String flag = args[1];
// Get value.
String value = args[2];
// Switch flag.
switch(flag.toLowerCase()) {
switch (flag.toLowerCase()) {
case "type":
this.typeFlag(label, player, itemcase, value);
break;
@ -143,55 +142,48 @@ public final class ModifyCommand implements Command {
this.showHelp(player, label);
break;
}
// Exit.
return;
}
/**
* Type flag.
*
* @param label label.
* @param player Player.
*
* @param label label.
* @param player Player.
* @param itemcase Itemcase.
* @param value Flag value.
* @param value Flag value.
*/
private void typeFlag(String label, Player player, Itemcase itemcase,
String value) {
String value) {
// Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// If the itemcase was a shop.
boolean wasShop = false;
// If the itemcase was a shop.
if(itemcase.getType() != Type.SHOWCASE) {
// Set boolean.
wasShop = true;
}
boolean wasShop = itemcase.getType() != Type.SHOWCASE;
// If the itemcase is now a shop.
boolean isNowShop = false;
// Switch value.
switch(value.toLowerCase()) {
switch (value.toLowerCase()) {
// Showcase.
case "showcase":
// Set type.
itemcase.setType(Type.SHOWCASE);
// Break.
break;
// Shop buy.
case "shop_buy":
// Check if player has permission.
if(!player.hasPermission("itemcase.create.shop.buy")) {
if (!player.hasPermission("itemcase.create.shop.buy")) {
// Send message.
chatLogger.message(player, "command.permission");
@ -199,21 +191,21 @@ public final class ModifyCommand implements Command {
// Exit.
return;
}
// Set boolean
isNowShop = true;
// Set type.
itemcase.setType(Type.SHOP_BUY);
// Break.
break;
// Shop sell.
case "shop_sell":
// Check if player has permission.
if(!player.hasPermission("itemcase.create.shop.sell")) {
if (!player.hasPermission("itemcase.create.shop.sell")) {
// Send message.
chatLogger.message(player, "command.permission");
@ -221,21 +213,21 @@ public final class ModifyCommand implements Command {
// Exit.
return;
}
// Set boolean
isNowShop = true;
// Set type.
itemcase.setType(Type.SHOP_SELL);
// Break.
break;
// Shop multi.
case "shop_multi":
// Check if player has permission.
if(!player.hasPermission("itemcase.create.shop.buy") ||
if (!player.hasPermission("itemcase.create.shop.buy") ||
!player.hasPermission("itemcase.create.shop.sell")) {
// Send message.
@ -244,82 +236,82 @@ public final class ModifyCommand implements Command {
// Exit.
return;
}
// Set boolean
isNowShop = true;
// Set type.
itemcase.setType(Type.SHOP_MULTI);
// Break.
break;
// Default.
default:
// Show help.
this.showHelp(player, label);
// Exit.
return;
}
// If itemcase is now a shop but wasn't before.
if(isNowShop && !wasShop) {
if (isNowShop && !wasShop) {
// Set storage.
itemcase.setStorage(Bukkit.createInventory(
null, 54, Itemcase.INVENTORY_NAME));
}
// Save itemcase.
ItemCaseCore.instance.getItemcaseManager().saveItemcases(itemcase);
// Show message.
chatLogger.message(player, "command.modify.success");
}
/**
* Storage Type flag.
*
* @param label label.
* @param player Player.
*
* @param label label.
* @param player Player.
* @param itemcase Itemcase.
* @param value Flag value.
* @param value Flag value.
*/
private void storageTypeFlag(String label, Player player, Itemcase itemcase,
String value) {
String value) {
// Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// If itemcase is not a shop.
if(itemcase.getType() == Type.SHOWCASE) {
if (itemcase.getType() == Type.SHOWCASE) {
// Show message.
chatLogger.message(player, "command.not-shop");
// Exit.
return;
}
// Switch value.
switch(value.toLowerCase()) {
switch (value.toLowerCase()) {
// Finite.
case "finite":
// Set storage type.
itemcase.setStorageType(StorageType.FINITE);
// Break.
break;
// Infinite.
case "infinite":
// Check if player has permission.
if(!player.hasPermission("itemcase.create.shop.infinite")) {
if (!player.hasPermission("itemcase.create.shop.infinite")) {
// Send message.
chatLogger.message(player, "command.permission");
@ -327,46 +319,46 @@ public final class ModifyCommand implements Command {
// Exit.
return;
}
// Set storage type.
itemcase.setStorageType(StorageType.INFINITE);
// Break.
break;
// Default.
default:
// Show help.
this.showHelp(player, label);
// Exit.
return;
}
// Save itemcase.
ItemCaseCore.instance.getItemcaseManager().saveItemcases(itemcase);
// Show message.
chatLogger.message(player, "command.modify.success");
}
/**
* Buy Price flag.
*
* @param label label.
* @param player Player.
*
* @param label label.
* @param player Player.
* @param itemcase Itemcase.
* @param value Flag value.
* @param value Flag value.
*/
private void buyPriceFlag(String label, Player player, Itemcase itemcase,
String value) {
String value) {
// Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// Check if player has permission.
if(!player.hasPermission("itemcase.create.shop.buy")) {
if (!player.hasPermission("itemcase.create.shop.buy")) {
// Send message.
chatLogger.message(player, "command.permission");
@ -374,69 +366,69 @@ public final class ModifyCommand implements Command {
// Exit.
return;
}
// If itemcase is not a shop.
if(itemcase.getType() == Type.SHOWCASE) {
if (itemcase.getType() == Type.SHOWCASE) {
// Show message.
chatLogger.message(player, "command.not-shop");
// Exit.
return;
}
// If itemcase only sells items.
if(itemcase.getType() == Type.SHOP_SELL) {
if (itemcase.getType() == Type.SHOP_SELL) {
// Show message.
chatLogger.message(player, "command.modify.sell-only");
// Exit.
return;
}
// Attempt to cast value to double.
try {
// Cast to double.
double buyPrice = Double.parseDouble(value);
// Set price.
itemcase.setBuyPrice(buyPrice);
// Failed to parse value.
// Failed to parse value.
} catch (NumberFormatException e) {
// Show message.
chatLogger.message(player, "command.modify.invalid-price");
// Exit.
return;
}
// Save itemcase.
ItemCaseCore.instance.getItemcaseManager().saveItemcases(itemcase);
// Show message.
chatLogger.message(player, "command.modify.success");
}
/**
* Sell Price flag.
*
* @param label label.
* @param player Player.
*
* @param label label.
* @param player Player.
* @param itemcase Itemcase.
* @param value Flag value.
* @param value Flag value.
*/
private void sellPriceFlag(String label, Player player, Itemcase itemcase,
String value) {
String value) {
// Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// Check if player has permission.
if(!player.hasPermission("itemcase.create.shop.sell")) {
if (!player.hasPermission("itemcase.create.shop.sell")) {
// Send message.
chatLogger.message(player, "command.permission");
@ -444,95 +436,93 @@ public final class ModifyCommand implements Command {
// Exit.
return;
}
// If itemcase is not a shop.
if(itemcase.getType() == Type.SHOWCASE) {
if (itemcase.getType() == Type.SHOWCASE) {
// Show message.
chatLogger.message(player, "command.not-shop");
// Exit.
return;
}
// If itemcase only buys items.
if(itemcase.getType() == Type.SHOP_BUY) {
if (itemcase.getType() == Type.SHOP_BUY) {
// Show message.
chatLogger.message(player, "command.modify.buy-only");
// Exit.
return;
}
// Attempt to cast value to double.
try {
// Cast to double.
double sellPrice = Double.parseDouble(value);
// Set price.
itemcase.setSellPrice(sellPrice);
// Failed to parse value.
// Failed to parse value.
} catch (NumberFormatException e) {
// Show message.
chatLogger.message(player, "command.modify.invalid-price");
// Exit.
return;
}
// Save itemcase.
ItemCaseCore.instance.getItemcaseManager().saveItemcases(itemcase);
// Show message.
chatLogger.message(player, "command.modify.success");
}
/**
* @return If the command sender is asking for help about this command.
*/
public boolean isAskingForHelp(Player player, String label, String[] args) {
// If args length equals 2.
if(args.length != 2) {
if (args.length != 2) {
// False.
return false;
}
// Get argument.
String argument = args[1];
// If not equal to help.
if(!argument.equalsIgnoreCase("help")) {
if (!argument.equalsIgnoreCase("help")) {
return false;
}
// Show help.
this.showHelp(player, label);
// Return.
return true;
}
/**
* Show help for main command to given sender.
*
* @param sender CommandSender.
*/
private void showHelp(Player player, String label) {
// Get translator.
LanguageTranslator translator = ItemCaseCore.instance.getTranslator();
// Set placeholder.
translator.setPlaceholder("%COMMAND%",
translator.setPlaceholder("%COMMAND%",
"/" + label + " modify [flag] [value]");
// Get chat logger.
ChatLogger logger = ItemCaseCore.instance.getChatLogger();
@ -546,19 +536,19 @@ public final class ModifyCommand implements Command {
logger.message(player, "[flag] [value]:");
// Send flag help.
logger.message(player,
logger.message(player,
" type [showcase/shop_buy/shop_sell/shop_multi]");
// Send flag help.
logger.message(player,
logger.message(player,
" storage_type [finite/infinite]");
// Send flag help.
logger.message(player,
logger.message(player,
" buy_price [price]");
// Send flag help.
logger.message(player,
logger.message(player,
" sell_price [price]");
}
}

View File

@ -15,12 +15,12 @@
package com.gmail.bleedobsidian.itemcase.commands;
import com.gmail.bleedobsidian.itemcase.Command;
import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import com.gmail.bleedobsidian.itemcase.ItemCaseCore;
import com.gmail.bleedobsidian.itemcase.Itemcase;
import com.gmail.bleedobsidian.itemcase.Itemcase.StorageType;
import com.gmail.bleedobsidian.itemcase.Itemcase.Type;
import com.gmail.bleedobsidian.itemcase.LanguageTranslator;
import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import com.gmail.bleedobsidian.itemcase.managers.OrderManager.ItemcaseOrder;
import net.md_5.bungee.api.ChatColor;
import net.milkbowl.vault.economy.Economy;
@ -32,64 +32,63 @@ import org.bukkit.inventory.ItemStack;
/**
* A command handler for the 'order' command.
*
*
* @author Jesse Prescott (BleedObsidian)
*/
public final class OrderCommand implements Command {
@Override
public void execute(CommandSender sender, String label,
String[] args) {
String[] args) {
// If sender is not a player.
if(!(sender instanceof Player)) {
if (!(sender instanceof Player player)) {
// Send message.
ItemCaseCore.instance.getGenericLogger().message(
sender, "command.not-player");
// Exit.
return;
}
// Cast sender to player.
Player player = (Player) sender;
// Check if player is asking for help.
if(this.isAskingForHelp(player, label, args)) {
if (this.isAskingForHelp(player, label, args)) {
// Exit.
return;
}
// Get chat logger.
// Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// If not enough arguments.
if(args.length < 2) {
if (args.length < 2) {
// Show help.
this.showHelp(player, label);
// Exit.
return;
}
// Check if player has active order.
if(!ItemCaseCore.instance.getOrderManager().hasOrder(player)) {
if (!ItemCaseCore.instance.getOrderManager().hasOrder(player)) {
// Send message
chatLogger.message(player, "command.order.no-order");
// Exit.
return;
}
// Get sub command.
String subCommand = args[1];
// Switch sub command.
switch(subCommand) {
switch (subCommand) {
case "buy":
this.executeBuy(player);
break;
@ -103,179 +102,179 @@ public final class OrderCommand implements Command {
this.showHelp(player, label);
return;
}
// Exit.
return;
}
/**
* Show help to given player.
*
*
* @param player Player.
* @param label Label used.
* @param label Label used.
*/
public void showHelp(Player player, String label) {
// Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// Get translator.
LanguageTranslator translator = ItemCaseCore.instance.getTranslator();
// Set placeholder.
translator.setPlaceholder("%COMMAND%", "");
// Show command help.
chatLogger.message(player, "command.itemcase-help");
// Set placeholder.
translator.setPlaceholder("%LABEL%", label);
// Show specific help.
chatLogger.message(player, "command.order.help-amount");
// Show specific help.
chatLogger.message(player, "command.order.help-buy");
// Show specific help.
chatLogger.message(player, "command.order.help-sell");
}
/**
* @return If the command sender is asking for help about this command.
*/
public boolean isAskingForHelp(Player player, String label, String[] args) {
// If args length equals 2.
if(args.length != 2) {
if (args.length != 2) {
// False.
return false;
}
// Get argument.
String argument = args[1];
// If not equal to help.
if(!argument.equalsIgnoreCase("help")) {
if (!argument.equalsIgnoreCase("help")) {
return false;
}
// Show help.
this.showHelp(player, label);
// Return.
return true;
}
/**
* Execute buy command.
*
*
* @param player Player.
*/
private void executeBuy(Player player) {
// Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// Get translator.
LanguageTranslator translator = ItemCaseCore.instance.getTranslator();
// Check if player has permission.
if(!player.hasPermission("itemcase.buy")) {
if (!player.hasPermission("itemcase.buy")) {
// Send message.
chatLogger.message(player, "command.permission");
// Exit.
return;
}
// Get order.
ItemcaseOrder order =
ItemcaseOrder order =
ItemCaseCore.instance.getOrderManager().getOrder(player);
// Get itemcase.
Itemcase itemcase = order.getItemcase();
// If itemcase can not be bought from.
if(itemcase.getType() == Type.SHOP_SELL) {
if (itemcase.getType() == Type.SHOP_SELL) {
// Send message.
chatLogger.message(player, "command.order.no-buy");
// Exit.
return;
}
// Check if server has vault if items are not free.
if(!ItemCaseCore.instance.hasVault() &&
if (!ItemCaseCore.instance.hasVault() &&
order.getItemcase().getBuyPrice() > 0) {
// Show message.
chatLogger.message(player, "command.order.no-vault");
// Exit.
return;
}
// Get itemstack being bought.
ItemStack itemstack = itemcase.getItemStack().clone();
// If itemcase does not have enough items.
if(!itemcase.hasEnough(order.getAmount())) {
if (!itemcase.hasEnough(order.getAmount())) {
// If stock is 0.
if(itemcase.getStockLevel() == 0) {
if (itemcase.getStockLevel() == 0) {
// Send message.
chatLogger.message(player, "command.order.no-stock");
// Exit.
return;
}
// Set amount placeholder.
translator.setPlaceholder("%AMOUNT%",
translator.setPlaceholder("%AMOUNT%",
"" + ChatColor.GOLD + itemcase.getStockLevel() +
ChatColor.RESET);
// Send message.
chatLogger.message(player, "command.order.not-enough-stock");
// Exit.
return;
}
// Calculate total price.
double total = order.getItemcase().getBuyPrice() * order.getAmount();
// Get economy provider.
Economy economyProvider = ItemCaseCore.instance.getEconomyProvider();
// If total is greator than 0, vault must be used.
if(total == 0) {
if (total == 0) {
// Give player items.
itemstack.setAmount(order.getAmount());
player.getInventory().addItem(itemstack);
// Remove items from storage.
itemcase.takeStock(order.getAmount());
// Exit.
return;
}
// Format money.
String money = ChatColor.GOLD + economyProvider.format(total);
// If name exists.
if(!economyProvider.currencyNameSingular().equals("")) {
if (!economyProvider.currencyNameSingular().equals("")) {
// If greator than 1.
if(total > 1) {
if (total > 1) {
// Plural name.
money += " " + economyProvider.currencyNamePlural();
@ -288,12 +287,12 @@ public final class OrderCommand implements Command {
// Reset color.
money += ChatColor.RESET;
// Set placeholder.
translator.setPlaceholder("%MONEY%", money);
// If player does not have enough money.
if(economyProvider.getBalance(player,
if (economyProvider.getBalance(player,
player.getWorld().getName()) < total) {
// Send message.
@ -302,14 +301,14 @@ public final class OrderCommand implements Command {
// Exit.
return;
}
// Create blank response.
EconomyResponse response1 =
EconomyResponse response1 =
new EconomyResponse(0, 0, ResponseType.SUCCESS, null);
// If itemcase is not infinite.
if(itemcase.getStorageType() == StorageType.FINITE) {
if (itemcase.getStorageType() == StorageType.FINITE) {
// Deposit money to owner.
response1 = economyProvider.depositPlayer(
order.getItemcase().getOwner(),
@ -321,7 +320,7 @@ public final class OrderCommand implements Command {
player, player.getWorld().getName(), total);
// If successful.
if(response1.transactionSuccess() && response2.transactionSuccess()) {
if (response1.transactionSuccess() && response2.transactionSuccess()) {
// Give player items.
itemstack.setAmount(order.getAmount());
@ -329,44 +328,44 @@ public final class OrderCommand implements Command {
// Remove items from storage.
itemcase.takeStock(order.getAmount());
// Mark order as completed.
ItemCaseCore.instance.getOrderManager().completeOrder(player);
// Send message.
chatLogger.message(player, "command.order.withdrew");
// If owner is online and itemcase is not infinite.
if(itemcase.getStorageType() == StorageType.FINITE &&
if (itemcase.getStorageType() == StorageType.FINITE &&
order.getItemcase().getOwner().isOnline()) {
// Get owner.
Player owner = order.getItemcase().getOwner().getPlayer();
// Set placeholder.
translator.setPlaceholder("%PLAYER%", player.getDisplayName());
// If item has custom display name.
if(itemcase.getItemStack().getItemMeta().hasDisplayName()) {
if (itemcase.getItemStack().getItemMeta().hasDisplayName()) {
// Set placeholder.
translator.setPlaceholder("%ITEM_NAME%",
ChatColor.GOLD +
itemcase.getItemStack().getItemMeta()
.getDisplayName() + ChatColor.RESET);
translator.setPlaceholder("%ITEM_NAME%",
ChatColor.GOLD +
itemcase.getItemStack().getItemMeta()
.getDisplayName() + ChatColor.RESET);
} else {
// Set placeholder.
translator.setPlaceholder("%ITEM_NAME%",
ChatColor.GOLD +
itemcase.getItemStack().getType().name()
translator.setPlaceholder("%ITEM_NAME%",
ChatColor.GOLD +
itemcase.getItemStack().getType().name()
+ ChatColor.RESET);
}
// Set placeholder.
translator.setPlaceholder("%AMOUNT%", "" + ChatColor.GOLD +
translator.setPlaceholder("%AMOUNT%", "" + ChatColor.GOLD +
order.getAmount() + ChatColor.RESET);
// Send message.
chatLogger.message(owner, "command.order.bought-from");
}
@ -377,102 +376,100 @@ public final class OrderCommand implements Command {
}
}
/**
* Execute sell command.
*
*
* @param player Player.
* @param label Label.
* @param args Arguments.
*/
private void executeSell(Player player) {
// Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// Get translator.
LanguageTranslator translator = ItemCaseCore.instance.getTranslator();
// Check if player has permission.
if(!player.hasPermission("itemcase.sell")) {
if (!player.hasPermission("itemcase.sell")) {
// Send message.
chatLogger.message(player, "command.permission");
// Exit.
return;
}
// Get order.
ItemcaseOrder order =
ItemcaseOrder order =
ItemCaseCore.instance.getOrderManager().getOrder(player);
// Get itemcase.
Itemcase itemcase = order.getItemcase();
// If itemcase can not sell.
if(itemcase.getType() == Type.SHOP_BUY) {
if (itemcase.getType() == Type.SHOP_BUY) {
// Send message.
chatLogger.message(player, "command.order.no-sell");
// Exit.
return;
}
// Check if server has no vault and players get no money for items.
if(!ItemCaseCore.instance.hasVault() &&
if (!ItemCaseCore.instance.hasVault() &&
order.getItemcase().getSellPrice() > 0) {
// Show message.
chatLogger.message(player, "command.order.no-vault");
// Exit.
return;
}
// Get itemstack being bought.
ItemStack itemstack = itemcase.getItemStack().clone();
// If player does not have enough items.
if(!player.getInventory().containsAtLeast(itemstack,
if (!player.getInventory().containsAtLeast(itemstack,
order.getAmount())) {
// Send message.
chatLogger.message(player, "command.order.not-enough-items");
// Exit.
return;
}
// Calculate total price.
double total = order.getItemcase().getSellPrice() * order.getAmount();
// Get economy provider.
Economy economyProvider = ItemCaseCore.instance.getEconomyProvider();
// If total is greator than 0, vault must be used.
if(total == 0) {
if (total == 0) {
// Remove items from player.
itemstack.setAmount(order.getAmount());
player.getInventory().removeItem(itemstack);
// Add stock to storage.
itemcase.addStock(order.getAmount());
// Exit.
return;
}
// Format money.
String money = ChatColor.GOLD + economyProvider.format(total);
// If name exists.
if(!economyProvider.currencyNameSingular().equals("")) {
if (!economyProvider.currencyNameSingular().equals("")) {
// If greator than 1.
if(total > 1) {
if (total > 1) {
// Plural name.
money += " " + economyProvider.currencyNamePlural();
@ -485,14 +482,14 @@ public final class OrderCommand implements Command {
// Reset color.
money += ChatColor.RESET;
// Set placeholder.
translator.setPlaceholder("%MONEY%", money);
// If owner does not have enough money and storage is finite.
if(order.getItemcase().getStorageType() == StorageType.FINITE &&
if (order.getItemcase().getStorageType() == StorageType.FINITE &&
(economyProvider.getBalance(order.getItemcase().getOwner(),
player.getWorld().getName()) < total)) {
player.getWorld().getName()) < total)) {
// Send message.
chatLogger.message(player, "command.order.owner-not-enough-money");
@ -500,27 +497,27 @@ public final class OrderCommand implements Command {
// Exit.
return;
}
// Create blank response.
EconomyResponse response1 =
EconomyResponse response1 =
new EconomyResponse(0, 0, ResponseType.SUCCESS, null);
// If itemcase is not infinite.
if(itemcase.getStorageType() == StorageType.FINITE) {
if (itemcase.getStorageType() == StorageType.FINITE) {
// Withdraw money from owner.
response1 = economyProvider.withdrawPlayer(
order.getItemcase().getOwner(),
player.getWorld().getName(), total);
}
// Deposit money to player.
EconomyResponse response2 = economyProvider.depositPlayer(
player,
player.getWorld().getName(), total);
// If successful.
if(response1.transactionSuccess() && response2.transactionSuccess()) {
if (response1.transactionSuccess() && response2.transactionSuccess()) {
// Remove items from player.
itemstack.setAmount(order.getAmount());
@ -528,48 +525,48 @@ public final class OrderCommand implements Command {
// Add stock to storage.
itemcase.addStock(order.getAmount());
// Mark order as completed.
ItemCaseCore.instance.getOrderManager().completeOrder(player);
// Send message.
chatLogger.message(player, "command.order.deposit");
// If owner is online and itemcase is not infinite.
if(itemcase.getStorageType() == StorageType.FINITE &&
if (itemcase.getStorageType() == StorageType.FINITE &&
order.getItemcase().getOwner().isOnline()) {
// Get owner.
Player owner = order.getItemcase().getOwner().getPlayer();
// Set placeholder.
translator.setPlaceholder("%PLAYER%", player.getDisplayName());
// If item has custom display name.
if(itemcase.getItemStack().getItemMeta().hasDisplayName()) {
if (itemcase.getItemStack().getItemMeta().hasDisplayName()) {
// Set placeholder.
translator.setPlaceholder("%ITEM_NAME%",
ChatColor.GOLD +
itemcase.getItemStack().getItemMeta()
.getDisplayName() + ChatColor.RESET);
translator.setPlaceholder("%ITEM_NAME%",
ChatColor.GOLD +
itemcase.getItemStack().getItemMeta()
.getDisplayName() + ChatColor.RESET);
} else {
// Set placeholder.
translator.setPlaceholder("%ITEM_NAME%",
ChatColor.GOLD +
itemcase.getItemStack().getType().name()
translator.setPlaceholder("%ITEM_NAME%",
ChatColor.GOLD +
itemcase.getItemStack().getType().name()
+ ChatColor.RESET);
}
// Set placeholder.
translator.setPlaceholder("%AMOUNT%", "" + ChatColor.GOLD +
translator.setPlaceholder("%AMOUNT%", "" + ChatColor.GOLD +
order.getAmount() + ChatColor.RESET);
// Send message.
chatLogger.message(owner, "command.order.sold-to");
}
} else {
// Show message.
@ -577,73 +574,73 @@ public final class OrderCommand implements Command {
}
}
/**
* Execute amount command.
*
*
* @param player Player.
* @param label Label.
* @param args Arguments.
* @param label Label.
* @param args Arguments.
*/
private void executeAmount(Player player, String label, String[] args) {
// Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// Check if player has permission.
if(!player.hasPermission("itemcase.buy") &&
if (!player.hasPermission("itemcase.buy") &&
!player.hasPermission("itemcase.sell")) {
// Send message.
chatLogger.message(player, "command.permission");
// Exit.
return;
}
// Check argument length.
if(args.length != 3) {
if (args.length != 3) {
// Show help.
this.showHelp(player, label);
// Exit.
return;
}
// Define amount.
int amount = 0;
int amount;
// Attempt to parse amount.
try {
// Parse amount.
amount = Integer.parseInt(args[2]);
} catch(NumberFormatException e) {
} catch (NumberFormatException e) {
// Show message.
chatLogger.message(player, "command.order.invalid-amount");
// Exit.
return;
}
// Set amount.
ItemCaseCore.instance.getOrderManager().getOrder(player)
.setAmount(amount);
// Get translator.
LanguageTranslator translator =
LanguageTranslator translator =
ItemCaseCore.instance.getTranslator();
// Set placeholder.
translator.setPlaceholder("%AMOUNT%", "" + ChatColor.GOLD + amount +
ChatColor.RESET);
// Show message.
chatLogger.message(player, "command.order.amount-update");
// Exit.
return;
}

View File

@ -15,12 +15,12 @@
package com.gmail.bleedobsidian.itemcase.commands;
import com.gmail.bleedobsidian.itemcase.Command;
import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import com.gmail.bleedobsidian.itemcase.ItemCaseCore;
import com.gmail.bleedobsidian.itemcase.Itemcase;
import com.gmail.bleedobsidian.itemcase.Itemcase.StorageType;
import com.gmail.bleedobsidian.itemcase.Itemcase.Type;
import com.gmail.bleedobsidian.itemcase.LanguageTranslator;
import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
@ -28,146 +28,145 @@ import org.bukkit.entity.Player;
/**
* A command handler for the 'create' command.
*
*
* @author Jesse Prescott (BleedObsidian)
*/
public final class StorageCommand implements Command {
@Override
public void execute(CommandSender sender, String label,
String[] args) {
String[] args) {
// If sender is not a player.
if(!(sender instanceof Player)) {
if (!(sender instanceof Player player)) {
// Send message.
ItemCaseCore.instance.getGenericLogger().message(
sender, "command.not-player");
// Exit.
return;
}
// Cast sender to player.
Player player = (Player) sender;
// Check if player is asking for help.
if(this.isAskingForHelp(player, label, args)) {
if (this.isAskingForHelp(player, label, args)) {
// Exit.
return;
}
// Get chat logger.
// Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// Check if player has permission.
if(!player.hasPermission("itemcase.create")) {
if (!player.hasPermission("itemcase.create")) {
// Send message.
chatLogger.message(player, "command.permission");
// Exit.
return;
}
// The target location.
Location target = null;
Location target;
// Get the players target block.
target = player.getTargetBlock(null, 5).getLocation();
// Check if itemcase exists here.
if(!ItemCaseCore.instance.getItemcaseManager().isItemcase(target)) {
if (!ItemCaseCore.instance.getItemcaseManager().isItemcase(target)) {
// Show message.
chatLogger.message(player, "command.invalid-location");
// Exit.
return;
}
// Get itemcase.
Itemcase itemcase =
// Get itemcase.
Itemcase itemcase =
ItemCaseCore.instance.getItemcaseManager().getItemcase(target);
// Get owner.
OfflinePlayer owner = itemcase.getOwner();
// Check if this player owns this itemcase.
if(!owner.equals(player)) {
if (!owner.equals(player)) {
// Check if player is allowed to modify other peoples itemcases.
if(!player.hasPermission("itemcase.modify.other")) {
if (!player.hasPermission("itemcase.modify.other")) {
// Show message.
chatLogger.message(player, "command.not-owner");
// Exit.
return;
}
}
// Check if itemcase is a shop.
if(itemcase.getType() == Type.SHOWCASE) {
if (itemcase.getType() == Type.SHOWCASE) {
// Show message.
chatLogger.message(player, "command.not-shop");
// Exit.
return;
}
// If itemcase has infinite storage.
if(itemcase.getStorageType() == StorageType.INFINITE) {
if (itemcase.getStorageType() == StorageType.INFINITE) {
// Show message.
chatLogger.message(player, "command.storage.infinite");
// Exit.
return;
}
// Open itemcase storage to player.
player.openInventory(itemcase.getStorage());
}
/**
* @return If the command sender is asking for help about this command.
*/
public boolean isAskingForHelp(Player player, String label, String[] args) {
// If args length equals 2.
if(args.length != 2) {
if (args.length != 2) {
// False.
return false;
}
// Get argument.
String argument = args[1];
// If not equal to help.
if(!argument.equalsIgnoreCase("help")) {
if (!argument.equalsIgnoreCase("help")) {
return false;
}
// Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// Get translator.
LanguageTranslator translator = ItemCaseCore.instance.getTranslator();
// Set placeholder.
translator.setPlaceholder("%COMMAND%", "/" + label + " storage");
// Show command help.
chatLogger.message(player, "command.itemcase-help");
// Show specific help.
chatLogger.message(player, "command.storage.help");
// Return.
return true;
}

View File

@ -16,55 +16,59 @@ package com.gmail.bleedobsidian.itemcase.configurations;
import com.gmail.bleedobsidian.itemcase.ConfigurationFile;
import com.gmail.bleedobsidian.itemcase.LanguageTranslator.Language;
import java.util.ArrayList;
import org.bukkit.Material;
import java.util.ArrayList;
/**
* The main configuration file for ItemCase.
*
* The main configuration file for ItemCase.
*
* @author Jesse Prescott (BleedObsidian)
*/
public final class ConfigFile extends ConfigurationFile {
/**
* Constructor.
*/
public ConfigFile() {
// The name of this configuration file.
super("config.yml");
}
/**
* @return The chosen Language to use.
*/
public Language getLocale() {
// Get set locale string.
String locale = this.file.getString("Locale");
// Convert to uppercase just in case.
locale = locale.toUpperCase();
// Return equivalent language.
return Language.valueOf(locale);
}
/**
* @return An array list of materials that can be used as Itemcases.
*/
public ArrayList<Material> getMaterials() {
// Create array list.
ArrayList<Material> materials = new ArrayList<>();
// Loop through all material IDs in config.
this.file.getStringList("Materials").forEach((id) -> {
// Add material to list.
materials.add(Material.getMaterial(id));
Material material = Material.getMaterial(id);
if (material != null) {
materials.add(material);
}
});
// Return list.
return materials;
}

View File

@ -19,30 +19,30 @@ import com.gmail.bleedobsidian.itemcase.LanguageTranslator.Language;
/**
* A configuration file that holds the translations for a specific dialect.
*
*
* @author Jesse Prescott (BleedObsidian)
*/
public final class LanguageFile extends ConfigurationFile {
/**
* Constructor.
*
* @param Language The language this file is for.
*
* @param language The language this file is for.
*/
public LanguageFile(Language language) {
// Give config file name and prevent file being copied outside of jar.
super("languages/" + language.name() + ".yml", false);
}
/**
* Get the raw translation for the given message key.
*
*
* @param key Key.
* @return String.
*/
public String getRawTranslation(String key) {
return this.file.getString(key);
}
}

View File

@ -19,6 +19,17 @@ import com.gmail.bleedobsidian.itemcase.ItemCaseCore;
import com.gmail.bleedobsidian.itemcase.Itemcase;
import com.gmail.bleedobsidian.itemcase.Itemcase.StorageType;
import com.gmail.bleedobsidian.itemcase.Itemcase.Type;
import com.onarandombox.MultiverseCore.utils.FileUtils;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.configuration.MemorySection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
@ -27,335 +38,319 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import org.apache.commons.multiverse.io.FileUtils;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.configuration.MemorySection;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
/**
* A configuration file that holds all Itemcase saves for a specific world.
*
*
* @author Jesse Prescott (BleedObsidian)
*/
public final class WorldFile extends ConfigurationFile {
/**
* The world this configuration file is for.
*/
private final World world;
/**
* Constructor.
*
*
* @param world World.
*/
public WorldFile(World world) {
// Append world name to config file name.
super(world.getName() + "/itemcases.yml", "itemcases.yml");
// Set world.
this.world = world;
}
/**
* Saves the given Itemcase to config.
*
*
* @param itemcase Itemcase.
* @throws java.io.IOException
*/
public void saveItemcase(Itemcase itemcase) throws IOException {
// Get block coordinates of Itemcase.
int blockX = itemcase.getLocation().getBlockX();
int blockY = itemcase.getLocation().getBlockY();
int blockZ = itemcase.getLocation().getBlockZ();
// Create a unique key for this itemcase based on location.
String key = "itemcases." + blockX + "/" + blockY + "/" + blockZ + ".";
// Set this Itemcase's type.
this.file.set(key + "type", itemcase.getType().name());
// Set this Itemcase's Owner.
String uuid = itemcase.getOwner().getUniqueId().toString();
this.file.set(key + "owner", uuid);
// Set this Itemcase's ItemStack.
Map<String, Object> itemstack = itemcase.getItemStack().serialize();
this.file.set(key + "itemstack", itemstack);
// If itemcase is a shop.
if(itemcase.getType() != Type.SHOWCASE) {
if (itemcase.getType() != Type.SHOWCASE) {
// Set storage type.
this.file.set(key + "shop.storage-type",
itemcase.getStorageType().name());
// If shop has finite storage.
if(itemcase.getStorageType() == StorageType.FINITE) {
if (itemcase.getStorageType() == StorageType.FINITE) {
// Serialize inventory.
Map<String, Object> inventory =
Map<String, Object> inventory =
this.serializeInventory(itemcase.getStorage());
// Set inventory.
this.file.set(key + "shop.storage", inventory);
}
// If this itemcase buys.
if(itemcase.getType() == Type.SHOP_BUY ||
if (itemcase.getType() == Type.SHOP_BUY ||
itemcase.getType() == Type.SHOP_MULTI) {
// Set buy price.
this.file.set(key + "shop.buy-price", itemcase.getBuyPrice());
}
// If this itemcase sells.
if(itemcase.getType() == Type.SHOP_SELL ||
if (itemcase.getType() == Type.SHOP_SELL ||
itemcase.getType() == Type.SHOP_MULTI) {
// Set sell price.
this.file.set(key + "shop.sell-price", itemcase.getSellPrice());
}
} else {
// Set shop section to null.
this.file.set(key + "shop", null);
}
// Attempt to save to file.
this.save(ItemCaseCore.instance);
}
/**
* Deletes the given Itemcase from config.
*
*
* @param itemcase Itemcase.
* @throws IOException
*/
public void deleteItemcase(Itemcase itemcase) throws IOException {
// Get block coordinates of Itemcase.
int blockX = itemcase.getLocation().getBlockX();
int blockY = itemcase.getLocation().getBlockY();
int blockZ = itemcase.getLocation().getBlockZ();
// Create a unique key for this itemcase based on location.
String key = "itemcases." + blockX + "/" + blockY + "/" + blockZ;
// Delete itemcase.
this.file.set(key, null);
// Attempt to save to file.
this.save(ItemCaseCore.instance);
}
/**
* Attempts to load all itemcases from the config.
*
*
* @return Array list of loaded itemcases.
* @throws java.io.IOException
*/
public ArrayList<Itemcase> loadItemcases() throws IOException {
// Attempt to load raw config file.
this.load(ItemCaseCore.instance);
// Create new array list to store loaded itemcases.
ArrayList<Itemcase> itemcases = new ArrayList<>();
ArrayList<Itemcase> itemCases = new ArrayList<>();
// Get the list of keys (itemcase locations).
Set<String> keys =
Set<String> keys =
this.file.getConfigurationSection("itemcases").getKeys(false);
// For every key (itemcase).
for(String key : keys) {
for (String key : keys) {
// Split key by '/' to obtain individual coordinates.
String[] coordinates = key.split("/");
// Convert to block integer coordinates.
int blockX = Integer.parseInt(coordinates[0]);
int blockY = Integer.parseInt(coordinates[1]);
int blockZ = Integer.parseInt(coordinates[2]);
// Create fuller key for ease of use later.
key = "itemcases." + key + ".";
// Convert to location.
Location location = new Location(this.world, blockX, blockY,
blockZ);
// Get type.
Type type = Itemcase.Type.valueOf(
this.file.getString(key + ".type"));
// Get owner.
UUID uuid = UUID.fromString(this.file.getString(key + ".owner"));
OfflinePlayer owner = Bukkit.getOfflinePlayer(uuid);
// Get ItemStack.
Map<String, Object> itemstackMap =
this.file.getConfigurationSection(key + "itemstack")
.getValues(true);
Map<String, Object> itemstackMap =
this.file.getConfigurationSection(key + "itemstack").getValues(true);
ItemStack itemstack = ItemStack.deserialize(itemstackMap);
// Create itemcase object.
Itemcase itemcase = new Itemcase(type, itemstack, location, owner);
// Spawn item.
itemcase.spawnItem();
// If itemcase is a shop.
if(type != Type.SHOWCASE) {
if (type != Type.SHOWCASE) {
// Get storage type.
StorageType storageType = StorageType.valueOf(
this.file.getString(key + "shop.storage-type"));
// Set storage type.
itemcase.setStorageType(storageType);
// If itemcase has finite storage.
if(storageType == StorageType.FINITE) {
// Deserialse inventory.
if (storageType == StorageType.FINITE) {
// De-serialise inventory.
Inventory inventory = this.deserializeInventory(
this.file.getConfigurationSection(
key + "shop.storage").getValues(false));
// Set inventory.
itemcase.setStorage(inventory);
}
// If this itemcase buys.
if(type == Type.SHOP_BUY || type == Type.SHOP_MULTI) {
if (type == Type.SHOP_BUY || type == Type.SHOP_MULTI) {
// Get buy price.
double buyPrice =
double buyPrice =
this.file.getDouble(key + "shop.buy-price");
// Set buy price.
itemcase.setBuyPrice(buyPrice);
}
// If this itemcase sells.
if(type == Type.SHOP_SELL || type == Type.SHOP_MULTI) {
if (type == Type.SHOP_SELL || type == Type.SHOP_MULTI) {
// Get sell price.
double sellPrice =
double sellPrice =
this.file.getDouble(key + "shop.sell-price");
// Set sell price.
itemcase.setSellPrice(sellPrice);
}
}
// Add to list.
itemcases.add(itemcase);
itemCases.add(itemcase);
}
// Return list of loaded itemcases.
return itemcases;
return itemCases;
}
/**
* Delete directory and config.
*
* @throws IOException
*/
public void deleteDirectory() throws IOException {
public void deleteDirectory() {
// Create file reference.
File fileReference = new File(ItemCaseCore.instance.getDataFolder(),
this.world.getName());
// Nullify reference.
this.file = null;
// Delete directory.
FileUtils.deleteDirectory(fileReference);
FileUtils.deleteFolder(fileReference);
}
/**
* Serialize the given inventory.
*
*
* @param inventory Inventory.
* @return Map.
*/
private Map<String, Object> serializeInventory(Inventory inventory) {
// Create map.
Map<String, Object> map = new HashMap();
Map<String, Object> map = new HashMap<>();
// Set size.
map.put("size", inventory.getSize());
// Set name.
map.put("name", inventory.getName());
map.put("name", ((Entity) inventory).getName());
// Loop through all content slots.
for(int i = 0; i < inventory.getSize(); i++) {
for (int i = 0; i < inventory.getSize(); i++) {
// Check if content slot has any items.
if (inventory.getItem(i) != null) {
// Serialize itemstack in content slot.
map.put("" + i, inventory.getItem(i).serialize());
}
}
// Return map.
return map;
}
/**
* Deserialize inventory from given map.
*
*
* @param map Map.
* @return Inventory.
*/
private Inventory deserializeInventory(Map<String, Object> map) {
// Get size.
int size = (int) map.get("size");
// Get name.
String name = (String) map.get("name");
// Create inventory.
Inventory inventory = Bukkit.createInventory(null, size, name);
// For every map entry.
for(Entry<String, Object> entry : map.entrySet()) {
for (Entry<String, Object> entry : map.entrySet()) {
// Check entry is parameter.
if(entry.getKey().equals("size") ||
if (entry.getKey().equals("size") ||
entry.getKey().equals("name")) {
// Skip.
continue;
}
// Get slot.
int slot = Integer.parseInt(entry.getKey());
// Get memory section.
MemorySection section = (MemorySection) entry.getValue();
// Deserialize item.
ItemStack item = ItemStack.deserialize((Map<String, Object>)
section.getValues(true));
ItemStack item = ItemStack.deserialize(section.getValues(true));
// Set item in slot.
inventory.setItem(slot, item);
}
// Return inventory.
return inventory;
}

View File

@ -20,7 +20,7 @@ import org.bukkit.entity.Player;
/**
* Utility class used for communicating to players in game with a translator.
*
*
* @author Jesse Prescott (BleedObsidian).
*/
public final class ChatLogger {
@ -28,41 +28,41 @@ public final class ChatLogger {
/**
* The prefix placed before all messages.
*/
private final static String PREFIX =
private final static String PREFIX =
ChatColor.BLUE + "[ItemCase]: " + ChatColor.RESET;
/**
* Language translator.
*/
private final LanguageTranslator translator;
/**
* Constructor.
*
*
* @param translator language translator.
*/
public ChatLogger(LanguageTranslator translator) {
// Set translator.
this.translator = translator;
}
/**
* Send given Player a message.
*
*
* @param player Player to send message.
* @param string Message key or message.
*/
public void message(Player player, String string) {
// If string is a message key.
if(this.translator.isKey(string)) {
if (this.translator.isKey(string)) {
// Translate.
string = this.translator.getTranslation(string);
}
// Send message.
player.sendMessage(ChatLogger.PREFIX + string);
}

View File

@ -16,10 +16,11 @@
package com.gmail.bleedobsidian.itemcase.loggers;
import com.gmail.bleedobsidian.itemcase.LanguageTranslator;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import org.bukkit.plugin.java.JavaPlugin;
/**
* A custom logger used to add color to the console when using warnings and
@ -28,81 +29,81 @@ import org.bukkit.plugin.java.JavaPlugin;
* @author Jesse Prescott (BleedObsidian)
*/
public final class ConsoleLogger extends Logger {
/**
* The plugin prefix.
*/
private final String prefix;
/**
* Language translator.
*/
private final LanguageTranslator translator;
/**
* Constructor.
*
*
* @param plugin The B
*/
public ConsoleLogger(JavaPlugin plugin, LanguageTranslator translator) {
// Call parent constructor.
super(plugin.getName(), null);
// Set logger settings.
super.setParent(plugin.getServer().getLogger());
super.setLevel(Level.ALL);
// Set plugin prefix.
this.prefix = "[" + plugin.getName() + "] ";
// Set translator.
this.translator = translator;
}
@Override
public void log(LogRecord logRecord) {
// Message.
String message = logRecord.getMessage();
// If message is a message key.
if(translator.isKey(message)) {
if (translator.isKey(message)) {
// Translate.
message = translator.getTranslation(message);
}
// Default white text.
logRecord.setMessage(this.prefix + message);
// Parent.
super.log(logRecord);
}
@Override
public void warning(String message) {
// Log message.
this.log(Level.WARNING, message);
}
@Override
public void severe(String message) {
// Log message.
this.log(Level.SEVERE, message);
}
/**
* Severe message with throwable exception.
*
* @param message The message to display.
*
* @param message The message to display.
* @param throwable The exception to display.
*/
public void severe(String message, Throwable throwable) {
// Log message.
this.log(Level.SEVERE, message, throwable);
}

View File

@ -20,43 +20,43 @@ import org.bukkit.command.CommandSender;
/**
* Utility class used for communicating to command senders in different
* dialects.
*
*
* @author Jesse Prescott (BleedObsidian).
*/
public final class GenericLogger {
/**
* Language translator.
*/
private final LanguageTranslator translator;
/**
* Constructor.
*
*
* @param translator language translator.
*/
public GenericLogger(LanguageTranslator translator) {
// Set translator.
this.translator = translator;
}
/**
* Send given CommandSender a message.
*
*
* @param sender CommandSender.
* @param string Message key or message.
*/
public void message(CommandSender sender, String string) {
// If string is a message key.
if(this.translator.isKey(string)) {
if (this.translator.isKey(string)) {
// Translate.
string = this.translator.getTranslation(string);
}
// Send message.
sender.sendMessage(string);
}

View File

@ -20,10 +20,6 @@ import com.gmail.bleedobsidian.itemcase.Itemcase.StorageType;
import com.gmail.bleedobsidian.itemcase.Itemcase.Type;
import com.gmail.bleedobsidian.itemcase.configurations.WorldFile;
import com.onarandombox.MultiverseCore.event.MVWorldDeleteEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
@ -35,44 +31,49 @@ import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.inventory.ItemStack;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
/**
* A manager of all Itemcases in a server. This manager is also responsible
* A manager of all Itemcases in a server. This manager is also responsible
* for loading and saving Itemcases to a config.
*
*
* @author Jesse Prescott (BleedObsidian)
*/
public final class ItemcaseManager {
/**
* A HashMap of each world and its corresponding WorldFile.
*/
private final HashMap<World, WorldFile> worldFiles = new HashMap<>();
/**
* A list of all active Itemcase instances.
*/
private final ArrayList<Itemcase> itemcases = new ArrayList<>();
/**
* Initialize this class.
*/
public void initialize() {
// For every currently loaded world.
for(World world : Bukkit.getWorlds()) {
for (World world : Bukkit.getWorlds()) {
// Request itemcases to be loaded.
this.loadItemcases(world);
}
}
/**
* Loads itemcases for the given world.
*
*
* @param world World.
*/
private void loadItemcases(World world) {
// Create WorldFile object.
WorldFile file = new WorldFile(world);
@ -105,306 +106,299 @@ public final class ItemcaseManager {
ItemCaseCore.instance.getConsoleLogger().info(
"console.info.loaded");
}
/**
* Save given Itemcase.
*
*
* @param itemcase Itemcase.
*/
public void saveItemcases(Itemcase itemcase) {
// Get world file.
WorldFile file = this.worldFiles.get(itemcase.getLocation().getWorld());
// Attempt to save itemcase.
try {
// Save itemcase.
file.saveItemcase(itemcase);
} catch (IOException e) {
// Log error.
// Log error.
ItemCaseCore.instance.getConsoleLogger().severe(
"Failed to save itemcase to config.", e);
"Failed to save itemcase to config.", e);
}
}
/**
* Create a new Itemcase.
*
*
* @param itemStack The ItemStack to be displayed.
* @param location The location of the itemcase.
* @param owner The owner of this itemcase.
* @param location The location of the itemcase.
* @param owner The owner of this itemcase.
*/
public void createItemcase(ItemStack itemStack, Location location,
OfflinePlayer owner) {
OfflinePlayer owner) {
// Create new itemcase instance.
Itemcase itemcase = new Itemcase(Itemcase.Type.SHOWCASE, itemStack,
location, owner);
// Spawn item.
itemcase.spawnItem();
// Add itemcase to the list.
this.itemcases.add(itemcase);
// Get config file for itemcase's world.
WorldFile file = this.worldFiles.get(location.getWorld());
// Attempt to save itemcase.
try {
// Save itemcase.
file.saveItemcase(itemcase);
} catch (IOException e) {
// Log error.
// Log error.
ItemCaseCore.instance.getConsoleLogger().severe(
"Failed to save new itemcase to config.", e);
"Failed to save new itemcase to config.", e);
}
}
/**
* Destroy given Itemcase.
*
*
* @param itemcase Itemcase.
*/
public void destroyItemcase(Itemcase itemcase) {
// Despawn Itemcase's item.
itemcase.despawnItem();
// Remove itemcase from list.
this.itemcases.remove(itemcase);
// Get config file for itemcase's world.
WorldFile file = this.worldFiles.get(itemcase.getLocation().getWorld());
// Attempt to delete itemcase.
// Attempt to delete itemcase.
try {
// Delete itemcase.
file.deleteItemcase(itemcase);
} catch (IOException e) {
// Log error.
// Log error.
ItemCaseCore.instance.getConsoleLogger().severe(
"Failed to delete itemcase from config.", e);
"Failed to delete itemcase from config.", e);
}
}
/**
* Unload all currently loaded Itemcases.
*/
public void unloadItemcases() {
// For every loaded itemcase.
for(Itemcase itemcase : this.itemcases) {
for (Itemcase itemcase : this.itemcases) {
// Despawn the item.
itemcase.despawnItem();
}
// Clear list.
this.itemcases.clear();
}
/**
* Register the event listener for this class.
*/
public void registerListener() {
// Register listener with bukkit.
Bukkit.getPluginManager().registerEvents(
new ItemcaseManagerListener(), ItemCaseCore.instance);
}
/**
* If the given location is an itemcase or not.
*
*
* @param location Location.
* @return Boolean.
*/
public boolean isItemcase(Location location) {
// For every itemcase.
for(Itemcase itemcase : this.itemcases) {
for (Itemcase itemcase : this.itemcases) {
// Check if location matches.
if(itemcase.getLocation().equals(location)) {
if (itemcase.getLocation().equals(location)) {
// Return true.
return true;
}
}
// Otherwise return false.
return false;
}
/**
* Attempt to get the itemcase at the given location.
*
*
* @param location Location.
* @return ItemCase.
*/
public Itemcase getItemcase(Location location) {
// For every itemcase.
for(Itemcase itemcase : this.itemcases) {
for (Itemcase itemcase : this.itemcases) {
// Check if location matches.
if(itemcase.getLocation().equals(location)) {
if (itemcase.getLocation().equals(location)) {
// Return itemcase.
return itemcase;
}
}
// No itemcase found.
return null;
}
/**
* @return A list of all active Itemcase instances.
*/
public ArrayList<Itemcase> getItemcases() {
// List of Itemcases.
return this.itemcases;
}
/**
* A bukkit listener for the ItemcaseManager. Used to load Itemcases upon
* world loading.
*/
private final class ItemcaseManagerListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR)
public void onWorldLoadEvent(WorldLoadEvent event) {
// Get world.
World world = event.getWorld();
// Request itemcases to be loaded.
ItemcaseManager.this.loadItemcases(world);
}
@EventHandler(priority = EventPriority.MONITOR)
public void onWorldDeleteEvent(MVWorldDeleteEvent event) {
// Get world name.
String worldName = event.getWorld().getName();
// WorldFile.
WorldFile worldFile = null;
// For every entry.
for(Entry<World, WorldFile> entry :
ItemcaseManager.this.worldFiles.entrySet()) {
for (Entry<World, WorldFile> entry :
ItemcaseManager.this.worldFiles.entrySet()) {
// Check if world name matches.
if(entry.getKey().getName() == worldName) {
if (entry.getKey().getName().equals(worldName)) {
// Attempt to delete config.
try {
// Set world file.
worldFile = entry.getValue();
// Delete config.
entry.getValue().deleteDirectory();
} catch (IOException e) {
// Log error.
ItemCaseCore.instance.getConsoleLogger().severe(
"Failed to delete itemcase config for world:"
+ worldName, e);
}
// Set world file.
worldFile = entry.getValue();
// Delete config.
entry.getValue().deleteDirectory();
}
}
// Remove world file.
ItemcaseManager.this.worldFiles.values().remove(worldFile);
// List to store itemcases of this world.
ArrayList<Itemcase> itemcases = new ArrayList();
ArrayList<Itemcase> itemcases = new ArrayList<>();
// For every itemcase.
for(Itemcase itemcase : ItemcaseManager.this.itemcases) {
for (Itemcase itemcase : ItemcaseManager.this.itemcases) {
// Check if itemcase was in deleted world.
if(itemcase.getLocation().getWorld().getName() == worldName) {
if (itemcase.getLocation().getWorld().getName().equals(worldName)) {
// Despawn item.
itemcase.despawnItem();
// Add to list.
itemcases.add(itemcase);
}
}
// Remove all itemcases that were in this world from list.
ItemcaseManager.this.itemcases.removeAll(itemcases);
}
@EventHandler(priority = EventPriority.MONITOR)
public void onInventoryCloseEvent(InventoryCloseEvent event) {
// Get inventory name.
String name = event.getInventory().getName();
String name = event.getView().getTitle();
// If inventory is Itemcase inventory.
if(!name.equals(Itemcase.INVENTORY_NAME)) {
if (!name.equals(Itemcase.INVENTORY_NAME)) {
// Exit.
return;
}
// For every Itemcase.
for(Itemcase itemcase : ItemcaseManager.this.itemcases) {
for (Itemcase itemcase : ItemcaseManager.this.itemcases) {
// If itemcase is not a shop it wont have storage.
if(itemcase.getType() == Type.SHOWCASE) {
if (itemcase.getType() == Type.SHOWCASE) {
// Skip.
continue;
}
// If itemcase is inifinite, it wont have storage.
if(itemcase.getStorageType() == StorageType.INFINITE) {
if (itemcase.getStorageType() == StorageType.INFINITE) {
// Skip.
continue;
}
// If inventory belongs to this itemcase.
if(itemcase.getStorage().equals(event.getInventory())) {
if (itemcase.getStorage().equals(event.getInventory())) {
// Get world file.
WorldFile file = ItemcaseManager.this.worldFiles.get(
itemcase.getLocation().getWorld());
// Attempt to save itemcase.
try {
// Save itemcase.
file.saveItemcase(itemcase);
} catch (IOException e) {
// Log error.
// Log error.
ItemCaseCore.instance.getConsoleLogger().severe(
"Failed to save itemcase after storage change.", e);
"Failed to save itemcase after storage change.", e);
}
}
}
}
}
}

View File

@ -14,45 +14,46 @@
*/
package com.gmail.bleedobsidian.itemcase.managers;
import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import com.gmail.bleedobsidian.itemcase.ItemCaseCore;
import com.gmail.bleedobsidian.itemcase.Itemcase;
import com.gmail.bleedobsidian.itemcase.Itemcase.Type;
import com.gmail.bleedobsidian.itemcase.LanguageTranslator;
import java.util.HashMap;
import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.util.HashMap;
/**
* Manages all active Itemcase orders.
*
*
* @author Jesse Prescott (BleedObsidian)
*/
public final class OrderManager {
/**
* HashMap of players and their active orders.
*/
private final HashMap<Player, ItemcaseOrder> orders = new HashMap();
private final HashMap<Player, ItemcaseOrder> orders = new HashMap<>();
/**
* Create new order.
*
*
* @param itemcase Itemcase.
* @param player Player.
* @param player Player.
*/
public void createOrder(Itemcase itemcase, Player player) {
// Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// Get translator.
LanguageTranslator translator =
LanguageTranslator translator =
ItemCaseCore.instance.getTranslator();
// Create new order for amount 1.
ItemcaseOrder order = new ItemcaseOrder(itemcase, 1);
// Add to list.
this.orders.put(player, order);
@ -60,128 +61,128 @@ public final class OrderManager {
chatLogger.message(player, "---------- Order ----------");
// If item has custom display name.
if(itemcase.getItemStack().getItemMeta().hasDisplayName()) {
if (itemcase.getItemStack().getItemMeta().hasDisplayName()) {
// Set placeholder.
translator.setPlaceholder("%ITEM_NAME%",
translator.setPlaceholder("%ITEM_NAME%",
ChatColor.GOLD + itemcase.getItemStack().getItemMeta()
.getDisplayName());
} else {
// Set placeholder.
translator.setPlaceholder("%ITEM_NAME%",
translator.setPlaceholder("%ITEM_NAME%",
ChatColor.GOLD + itemcase.getItemStack().getType().name());
}
// Send message.
chatLogger.message(player, "order.item");
// Set amount placeholder.
translator.setPlaceholder("%AMOUNT%", ChatColor.GOLD +
translator.setPlaceholder("%AMOUNT%", ChatColor.GOLD +
String.valueOf(1));
// Send message.
chatLogger.message(player, "order.amount");
// If shop buys products.
if(itemcase.getType() == Type.SHOP_BUY ||
if (itemcase.getType() == Type.SHOP_BUY ||
itemcase.getType() == Type.SHOP_MULTI) {
// Set placeholder.
translator.setPlaceholder("%BUY_PRICE%", "" + ChatColor.GOLD +
itemcase.getBuyPrice());
// Send message.
chatLogger.message(player, "order.buy-price");
}
// If shop sells products.
if(itemcase.getType() == Type.SHOP_SELL ||
if (itemcase.getType() == Type.SHOP_SELL ||
itemcase.getType() == Type.SHOP_MULTI) {
// Set placeholder.
translator.setPlaceholder("%SELL_PRICE%", "" + ChatColor.GOLD +
itemcase.getSellPrice());
// Send message.
chatLogger.message(player, "order.sell-price");
}
// Send message.
chatLogger.message(player, "---------------------------");
// Send message.
chatLogger.message(player, "order.help");
// Send message.
chatLogger.message(player, "---------------------------");
}
/**
* Mark order as completed.
*
*
* @param player Player.
*/
public void completeOrder(Player player) {
// Remove oder.
this.orders.remove(player);
}
/**
* @param player Player.
* @return If order exists for given player.
*/
public boolean hasOrder(Player player) {
// Return if order exists for given player.
return this.orders.containsKey(player);
}
/**
* @param player Player.
* @return The order linked with this player.
*/
public ItemcaseOrder getOrder(Player player) {
// Return order linked to player.
return this.orders.get(player);
}
/**
* An order for a specific itemcase of some amount.
*/
public final class ItemcaseOrder {
public static final class ItemcaseOrder {
/**
* The itemcase this order is for.
*/
private final Itemcase itemcase;
/**
* The amount.
*/
private int amount;
/**
* Constructor.
*
*
* @param itemcase Itemcase.
* @param amount Amount.
* @param amount Amount.
*/
public ItemcaseOrder(Itemcase itemcase, int amount) {
// Set attributes.
this.itemcase = itemcase;
this.amount = amount;
}
/**
* @return Itemcase.
*/
public Itemcase getItemcase() {
// Return itemcase.
return itemcase;
}
@ -190,16 +191,16 @@ public final class OrderManager {
* @return Amount.
*/
public int getAmount() {
// Amount.
return amount;
}
/**
* @param amount Amount.
*/
public void setAmount(int amount) {
// Set amount.
this.amount = amount;
}

View File

@ -1,16 +1,64 @@
#-------------------- ItemCase Configuration File --------------------#
# This file contains all of the ItemCase configuration settings that #
# can be altered. #
#---------------------------------------------------------------------#
#-------------------- ItemCase Configuration File -----------------#
# This file contains all the ItemCase configuration settings that #
# can be altered. #
#------------------------------------------------------------------#
# Locale:
# - EN
Locale: EN
# Materials that can be used for ItemCases.
# https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/Material.html
Materials:
- 'STEP' # Slabs.
- 'STONE_SLAB2' # Red Sandstone Slabs.
- 'WOOD_STEP' # Wooden Slabs.
- 'PURPUR_SLAB' # Purpur Slabs.
- 'ACACIA_SLAB'
- 'ANDESITE_SLAB'
- 'BIRCH_SLAB'
- 'BLACKSTONE_SLAB'
- 'BRICK_SLAB'
- 'COBBLED_DEEPSLATE_SLAB'
- 'COBBLESTONE_SLAB'
- 'CRIMSON_SLAB'
- 'CUT_COPPER_SLAB'
- 'CUT_RED_SANDSTONE_SLAB'
- 'CUT_SANDSTONE_SLAB'
- 'DARK_OAK_SLAB'
- 'DARK_PRISMARINE_SLAB'
- 'DEEPSLATE_BRICK_SLAB'
- 'DEEPSLATE_TILE_SLAB'
- 'DIORITE_SLAB'
- 'END_STONE_BRICK_SLAB'
- 'EXPOSED_CUT_COPPER_SLAB'
- 'GRANITE_SLAB'
- 'JUNGLE_SLAB'
- 'MOSSY_COBBLESTONE_SLAB'
- 'MOSSY_STONE_BRICK_SLAB'
- 'NETHER_BRICK_SLAB'
- 'OAK_SLAB'
- 'OXIDIZED_CUT_COPPER_SLAB'
- 'PETRIFIED_OAK_SLAB'
- 'POLISHED_ANDESITE_SLAB'
- 'POLISHED_BLACKSTONE_BRICK_SLAB'
- 'POLISHED_BLACKSTONE_SLAB'
- 'POLISHED_DEEPSLATE_SLAB'
- 'POLISHED_DIORITE_SLAB'
- 'POLISHED_GRANITE_SLAB'
- 'PRISMARINE_BRICK_SLAB'
- 'PRISMARINE_SLAB'
- 'PURPUR_SLAB'
- 'QUARTZ_SLAB'
- 'RED_NETHER_BRICK_SLAB'
- 'RED_SANDSTONE_SLAB'
- 'SANDSTONE_SLAB'
- 'SMOOTH_QUARTZ_SLAB'
- 'SMOOTH_RED_SANDSTONE_SLAB'
- 'SMOOTH_SANDSTONE_SLAB'
- 'SMOOTH_STONE_SLAB'
- 'SPRUCE_SLAB'
- 'STONE_BRICK_SLAB'
- 'STONE_SLAB'
- 'WARPED_SLAB'
- 'WAXED_CUT_COPPER_SLAB'
- 'WAXED_EXPOSED_CUT_COPPER_SLAB'
- 'WAXED_OXIDIZED_CUT_COPPER_SLAB'
- 'WAXED_WEATHERED_CUT_COPPER_SLAB'
- 'WEATHERED_CUT_COPPER_SLAB'

View File

@ -2,4 +2,4 @@
# Server must be stopped while changes are made to this file #
# otherwise they will be overwritten. #
itemcases: {}
itemcases: { }

View File

@ -4,207 +4,207 @@
# Console based messages.
console:
# Non erroneous messages.
info:
# Shown during plugin loading.
#
# %LANGUAGE% = The language as set in the main config.
# %VERSION% = The version of ItemCase in use.
# %WORLD_NAME% = The name of the world.
locale: "Using locale: %LANGUAGE%"
config-loaded: "Successfully loaded main configuration file."
enabled: "ItemCase v%VERSION% enabled."
unloaded: "Itemcases unloaded successfully."
loaded: "Loaded itemcases for world: %WORLD_NAME%"
vault-hooked: "Vault successfully hooked."
worldguard-hooked: "WorldGuard successfully hooked."
# Non erroneous messages.
info:
# Shown during plugin loading.
#
# %LANGUAGE% = The language as set in the main config.
# %VERSION% = The version of ItemCase in use.
# %WORLD_NAME% = The name of the world.
locale: "Using locale: %LANGUAGE%"
config-loaded: "Successfully loaded main configuration file."
enabled: "ItemCase v%VERSION% enabled."
unloaded: "Itemcases unloaded successfully."
loaded: "Loaded itemcases for world: %WORLD_NAME%"
vault-hooked: "Vault successfully hooked."
worldguard-hooked: "WorldGuard successfully hooked."
# Messages shown when using commands.
command:
# Shown when a user incorrectly uses the main itemcase command.
# %COMMAND% = The command usage syntax.
itemcase-help: "Usage: %COMMAND%"
# Shown when a user incorrectly uses the main itemcase command.
# %LABEL% = The label that was used.
command-help: "To view more: /%LABEL% [command] help"
# Shown when a user tries to execute a command and they are not an in game
# player.
not-player: "You must be a player to use this command."
# Shown when a player tries to destroy another persons itemcase when
# they do not have permission itemcase.destroy.other.
not-owner: "You do not own this ItemCase."
# Shown when a user tries to execute a command and they do not have the
# required permission.
permission: "You do not have permission to use this command."
# Shown when a player uses a command but is not looking at an itemcase.
invalid-location: "This block is not an ItemCase."
# Shown to the player when trying to set storage type on an itemcase
# that is not a shop or access the storage of an itemcase that is not a
# shop.
not-shop: "This ItemCase is not a shop."
# Messages shown when using the 'create' command.
create:
# Shown to the player when asking for help.
help: "Creates a new itemcase with the item in your main hand, at the block you are looking at."
# Shown to the player when they try to make an itemcase out of an
# invalid block type.
invalid-type: "This block cannot be used for an ItemCase."
# Shown to the player when they try to make an itemcase where one
# already exists.
invalid-location: "An ItemCase already exists here."
# Shown to the player when they use the create command but they are not
# holding any item in their main hand.
main-hand: "You must be holding something in your main hand."
# Shown when a player tries to make an itemcase in a WorldGuard restricted location.
no-build: "You do not have building permission here."
# Shown to the player upon successful creation.
success: "ItemCase created."
# Messages shown when using the 'destroy' command.
destroy:
# Shown to the player when asking for help.
help: "Destroy the itemcase you are looking at permanently."
# Shown to the player upon successful deletion.
success: "ItemCase destroyed."
# Messages shwon when using the 'modify' command.
modify:
# Shown to the player when asking for help.
help: "Modify a flag of the itemcase you are looking at."
# Shown to the player when trying to set the sell price of an ItemCase
# that only buys items.
sell-only: "This ItemCase only sells items."
# Shown to the player when trying to set the buy price of an ItemCase
# that only sells items.
buy-only: "This ItemCase only buys items."
# Shown to the player when setting a buy/sell price that is invalid.
invalid-price: "Invalid price."
# Shown to the player upon successful modification.
success: "ItemCase flag modified."
# Messages shown when using the 'storage' command.
storage:
# Shown to the player when asking for help.
help: "View the storage of the itemcase you are looking at."
# Shown to the player when trying to access the storage of an infinite
# itemcase shop.
infinite: "This ItemCase has infinite items to buy/sell, therefore has no storage."
# Messages shown when using the 'order' command.
order:
# Shown to the player when asking for help.
# %LABEL% = The label used.
help-amount: "/%LABEL% order amount [amount]: Change amount."
# Shown to the player when asking for help.
# %LABEL% = The label used.
help-buy: "/%LABEL% order buy: Buy the current order."
# Shown to the player when asking for help.
# %LABEL% = The label used.
help-sell: "/%LABEL% order sell: Sell the current order."
# Shown when the player uses this command but don't have an active order.
no-order: "You do not have an active order."
# Shown when a player uses an order command but no vault hook is present.
no-vault: "Sorry, this server does not have Vault or an economy plugin."
# Shown when the player enters an invalid amount.
invalid-amount: "Invalid amount."
# Shown when the player uses the amount command,
# %AMOUNT% = The amount the player entered.
amount-update: "Amount updated to %AMOUNT%."
# Shown when the player does not have enough money for an order.
# %MONEY% = The formatted money and name.
not-enough-money: "You need atleast %MONEY% to complete this order."
# Shown when the owner does not have enough money for an order.
owner-not-enough-money: "Sorry, the owner of this ItemCase does not have the funds to buy these items from you."
# Shown when the player sets an amount higher than the amount an itemcase has.
# %AMOUNT% = The amount left.
not-enough-stock: "Sorry, this itemcase only has %AMOUNT% left."
# Shown when a player tries to sell more than they have.
not-enough-items: "You do not have enough of the item to sell."
# Shown when an itemcase has zero stock.
no-stock: "Sorry, this itemcase has no stock."
# Shown when a transaction failes for some reason.
failed: "Transaction failed"
# Shown when a player tries to buy items form an itemcase that only players can sell to.
no-buy: "You cannot buy items from this itemcase."
# Shown when a player tries to sell items to an itemcase that only players can buy from.
no-sell: "You cannot sell items to this itemcase."
# Shown to an owner if they are online when a player buys from one of their itemcases.
bought-from: "%PLAYER% bought %AMOUNT% x %ITEM_NAME% from you for %MONEY%."
# Shown to an owner if they are online when a player sells to one of their itemcases.
# %AMOUNT% = The amount left.
# %MONEY% = The formatted money and name.
# %ITEM_NAME% = The item being sold.
# %PLAYER% = The player's name.
sold-to: "%PLAYER% sold %AMOUNT% x %ITEM_NAME% to you for %MONEY%."
# Shown when the player buys from a shop.
# %MONEY% = The formatted money and name.
withdrew: "Withdrew %MONEY% from your account."
# Shown when the player sell to a shop.
# %MONEY% = The formatted money and name.
deposit: "Deposited %MONEY% to your account."
# Shown when a user incorrectly uses the main itemcase command.
# %COMMAND% = The command usage syntax.
itemcase-help: "Usage: %COMMAND%"
# Shown when a user incorrectly uses the main itemcase command.
# %LABEL% = The label that was used.
command-help: "To view more: /%LABEL% [command] help"
# Shown when a user tries to execute a command and they are not an in game
# player.
not-player: "You must be a player to use this command."
# Shown when a player tries to destroy another persons itemcase when
# they do not have permission itemcase.destroy.other.
not-owner: "You do not own this ItemCase."
# Shown when a user tries to execute a command and they do not have the
# required permission.
permission: "You do not have permission to use this command."
# Shown when a player uses a command but is not looking at an itemcase.
invalid-location: "This block is not an ItemCase."
# Shown to the player when trying to set storage type on an itemcase
# that is not a shop or access the storage of an itemcase that is not a
# shop.
not-shop: "This ItemCase is not a shop."
# Messages shown when using the 'create' command.
create:
# Shown to the player when asking for help.
help: "Creates a new itemcase with the item in your main hand, at the block you are looking at."
# Shown to the player when they try to make an itemcase out of an
# invalid block type.
invalid-type: "This block cannot be used for an ItemCase."
# Shown to the player when they try to make an itemcase where one
# already exists.
invalid-location: "An ItemCase already exists here."
# Shown to the player when they use the create command but they are not
# holding any item in their main hand.
main-hand: "You must be holding something in your main hand."
# Shown when a player tries to make an itemcase in a WorldGuard restricted location.
no-build: "You do not have building permission here."
# Shown to the player upon successful creation.
success: "ItemCase created."
# Messages shown when using the 'destroy' command.
destroy:
# Shown to the player when asking for help.
help: "Destroy the itemcase you are looking at permanently."
# Shown to the player upon successful deletion.
success: "ItemCase destroyed."
# Messages shwon when using the 'modify' command.
modify:
# Shown to the player when asking for help.
help: "Modify a flag of the itemcase you are looking at."
# Shown to the player when trying to set the sell price of an ItemCase
# that only buys items.
sell-only: "This ItemCase only sells items."
# Shown to the player when trying to set the buy price of an ItemCase
# that only sells items.
buy-only: "This ItemCase only buys items."
# Shown to the player when setting a buy/sell price that is invalid.
invalid-price: "Invalid price."
# Shown to the player upon successful modification.
success: "ItemCase flag modified."
# Messages shown when using the 'storage' command.
storage:
# Shown to the player when asking for help.
help: "View the storage of the itemcase you are looking at."
# Shown to the player when trying to access the storage of an infinite
# itemcase shop.
infinite: "This ItemCase has infinite items to buy/sell, therefore has no storage."
# Messages shown when using the 'order' command.
order:
# Shown to the player when asking for help.
# %LABEL% = The label used.
help-amount: "/%LABEL% order amount [amount]: Change amount."
# Shown to the player when asking for help.
# %LABEL% = The label used.
help-buy: "/%LABEL% order buy: Buy the current order."
# Shown to the player when asking for help.
# %LABEL% = The label used.
help-sell: "/%LABEL% order sell: Sell the current order."
# Shown when the player uses this command but don't have an active order.
no-order: "You do not have an active order."
# Shown when a player uses an order command but no vault hook is present.
no-vault: "Sorry, this server does not have Vault or an economy plugin."
# Shown when the player enters an invalid amount.
invalid-amount: "Invalid amount."
# Shown when the player uses the amount command,
# %AMOUNT% = The amount the player entered.
amount-update: "Amount updated to %AMOUNT%."
# Shown when the player does not have enough money for an order.
# %MONEY% = The formatted money and name.
not-enough-money: "You need atleast %MONEY% to complete this order."
# Shown when the owner does not have enough money for an order.
owner-not-enough-money: "Sorry, the owner of this ItemCase does not have the funds to buy these items from you."
# Shown when the player sets an amount higher than the amount an itemcase has.
# %AMOUNT% = The amount left.
not-enough-stock: "Sorry, this itemcase only has %AMOUNT% left."
# Shown when a player tries to sell more than they have.
not-enough-items: "You do not have enough of the item to sell."
# Shown when an itemcase has zero stock.
no-stock: "Sorry, this itemcase has no stock."
# Shown when a transaction failes for some reason.
failed: "Transaction failed"
# Shown when a player tries to buy items form an itemcase that only players can sell to.
no-buy: "You cannot buy items from this itemcase."
# Shown when a player tries to sell items to an itemcase that only players can buy from.
no-sell: "You cannot sell items to this itemcase."
# Shown to an owner if they are online when a player buys from one of their itemcases.
bought-from: "%PLAYER% bought %AMOUNT% x %ITEM_NAME% from you for %MONEY%."
# Shown to an owner if they are online when a player sells to one of their itemcases.
# %AMOUNT% = The amount left.
# %MONEY% = The formatted money and name.
# %ITEM_NAME% = The item being sold.
# %PLAYER% = The player's name.
sold-to: "%PLAYER% sold %AMOUNT% x %ITEM_NAME% to you for %MONEY%."
# Shown when the player buys from a shop.
# %MONEY% = The formatted money and name.
withdrew: "Withdrew %MONEY% from your account."
# Shown when the player sell to a shop.
# %MONEY% = The formatted money and name.
deposit: "Deposited %MONEY% to your account."
# Messages shown when ordering.
order:
# Shown when ordering.
# %ITEM_NAME% = The item being sold.
item: "Item: %ITEM_NAME%"
# Shown when ordering.
# %BUY_PRICE% = The buy price.
buy-price: "Buy price: %BUY_PRICE%"
# Shown when ordering.
# %SELL_PRICE% = The sell price.
sell-price: "Sell price: %SELL_PRICE%"
# Shown when ordering.
# %AMOUNT% = The amount.
amount: "Amount: %AMOUNT%"
# Shown when ordering.
help: "Help: /itemc order help"
# Shown when ordering.
# %ITEM_NAME% = The item being sold.
item: "Item: %ITEM_NAME%"
# Shown when ordering.
# %BUY_PRICE% = The buy price.
buy-price: "Buy price: %BUY_PRICE%"
# Shown when ordering.
# %SELL_PRICE% = The sell price.
sell-price: "Sell price: %SELL_PRICE%"
# Shown when ordering.
# %AMOUNT% = The amount.
amount: "Amount: %AMOUNT%"
# Shown when ordering.
help: "Help: /itemc order help"

View File

@ -1,30 +1,32 @@
name: ItemCase
version: 2.0.1
version: 3.0.0
description: ItemCase is a Bukkit plugin allowing you to showcase items on slabs, that can also be used as shops.
load: POSTWORLD
softdepend: [WorldGuard, Vault]
author: BleedObsidian
website: http://dev.bukkit.org/bukkit-plugins/itemcase/
softdepend: [ WorldGuard, Vault, Multiverse-Core ]
author: EpicKnarvik97
authors: [ BleedObsidian, EpicKnarvik97 ]
website: https://git.knarcraft.net
api-version: 1.17
database: false
prefix: ItemCase
main: com.gmail.bleedobsidian.itemcase.ItemCaseCore
commands:
itemcase:
aliases: [itemc, ic]
description: "Showcase items on slabs, that can also be used as shops."
itemcase:
aliases: [ itemc, ic ]
description: "Showcase items on slabs, that can also be used as shops."
permissions:
itemcase.create:
description: Create and destroy showcase itemcases.
itemcase.create.shop.buy:
description: Create itemcases that can sell things to players.
itemcase.create.shop.sell:
description: Create itemcases that can buy things from players.
itemcase.create.shop.infinite:
description: Create an itemcase shop that has infinite items to buy/sell.
itemcase.modify.other:
description: Modify flags and access storage of itemcases you don't own.
itemcase.destroy.other:
description: Destroy an itemcase you don't own.
itemcase.create:
description: Create and destroy showcase itemcases.
itemcase.create.shop.buy:
description: Create itemcases that can sell things to players.
itemcase.create.shop.sell:
description: Create itemcases that can buy things from players.
itemcase.create.shop.infinite:
description: Create an itemcase shop that has infinite items to buy/sell.
itemcase.modify.other:
description: Modify flags and access storage of itemcases you don't own.
itemcase.destroy.other:
description: Destroy an itemcase you don't own.

View File

@ -1,245 +0,0 @@
/*
* ItemCase is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/gpl.html>.
*/
package com.gmail.bleedobsidian.itemcase;
import com.gmail.bleedobsidian.itemcase.Itemcase.ItemcaseTask;
import com.gmail.bleedobsidian.itemcase.Itemcase.Type;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.powermock.api.mockito.PowerMockito;
import static org.powermock.api.mockito.PowerMockito.whenNew;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
/**
* Unit test for {@link com.gmail.bleedobsidian.itemcase.Itemcase}
*
* @author Jesse Prescott (BleedObsidian).
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest(Itemcase.class)
public class ItemcaseTest {
/**
* The material of the itemcase
*/
private Material itemcaseMaterial;
/**
* Creates a valid itemcase.
*
* @return Itemcase.
*/
private Itemcase createValidItemcase() throws Exception {
// Itemcase type.
Type type = Type.SHOP_MULTI;
// Mock ItemMeta.
ItemMeta meta = PowerMockito.mock(ItemMeta.class);
// Mock itemstack.
ItemStack itemstack = PowerMockito.mock(ItemStack.class);
// When clone method is called, return mock itemstack.
when(itemstack.clone()).thenReturn(itemstack);
// Return mock item meta.
when(itemstack.getItemMeta()).thenReturn(meta);
// Mock world.
World world = PowerMockito.mock(World.class);
// Mock block.
Block block = PowerMockito.mock(Block.class);
// Return material.
when(block.getType()).thenReturn(this.itemcaseMaterial);
// Mock location.
Location location = PowerMockito.mock(Location.class);
// Return mock world when asked for.
when(location.getWorld()).thenReturn(world);
// Return mock block.
when(location.getBlock()).thenReturn(block);
// Mock chunk.
Chunk chunk = PowerMockito.mock(Chunk.class);
// When asking for the chunk from location, return mock.
when(location.getChunk()).thenReturn(chunk);
// Mock player.
OfflinePlayer player = PowerMockito.mock(OfflinePlayer.class);
// Create new itemcase to test.
Itemcase itemcase = new Itemcase(type, itemstack, location, player);
// Test type is correct.
assertEquals(itemcase.getType(), type);
// Test itemstack is correct.
assertEquals(itemcase.getItemStack(), itemstack);
// Verify itemstack amount was set to 1.
verify(itemstack).setAmount(1);
// Test owner is correct.
assertEquals(itemcase.getOwner(), player);
// Return itemcase.
return itemcase;
}
@Test
public void constructor_valid_pass() throws Exception {
// Create itemcase.
Itemcase itemcase = this.createValidItemcase();
}
@Test(expected = IllegalArgumentException.class)
public void constructor_nullType_exception() {
// Mock itemstack.
ItemStack itemstack = PowerMockito.mock(ItemStack.class);
// When clone method is called, return mock itemstack.
when(itemstack.clone()).thenReturn(itemstack);
// Mock location.
Location location = PowerMockito.mock(Location.class);
// Mock chunk.
Chunk chunk = PowerMockito.mock(Chunk.class);
// When asking for the chunk from location, return mock.
when(location.getChunk()).thenReturn(chunk);
// Mock player.
OfflinePlayer player = PowerMockito.mock(OfflinePlayer.class);
// Create object.
new Itemcase(null, itemstack, location, player);
}
@Test(expected = IllegalArgumentException.class)
public void constructor_nullItemStack_exception() {
// Itemcase type.
Type type = Type.SHOP_MULTI;
// Mock location.
Location location = PowerMockito.mock(Location.class);
// Mock chunk.
Chunk chunk = PowerMockito.mock(Chunk.class);
// When asking for the chunk from location, return mock.
when(location.getChunk()).thenReturn(chunk);
// Mock player.
OfflinePlayer player = PowerMockito.mock(OfflinePlayer.class);
// Create itemcase.
new Itemcase(type, null, location, player);
}
@Test(expected = IllegalArgumentException.class)
public void constructor_nullLocation_exception() {
// Itemcase type.
Type type = Type.SHOP_MULTI;
// Mock itemstack.
ItemStack itemstack = PowerMockito.mock(ItemStack.class);
// When clone method is called, return mock itemstack.
when(itemstack.clone()).thenReturn(itemstack);
// Mock player.
OfflinePlayer player = PowerMockito.mock(OfflinePlayer.class);
// Create itemcase.
new Itemcase(type, itemstack, null, player);
}
@Test(expected = IllegalArgumentException.class)
public void constructor_nullOwner_exception() {
// Itemcase type.
Type type = Type.SHOP_MULTI;
// Mock itemstack.
ItemStack itemstack = PowerMockito.mock(ItemStack.class);
// When clone method is called, return mock itemstack.
when(itemstack.clone()).thenReturn(itemstack);
// Mock location.
Location location = PowerMockito.mock(Location.class);
// Mock chunk.
Chunk chunk = PowerMockito.mock(Chunk.class);
// When asking for the chunk from location, return mock.
when(location.getChunk()).thenReturn(chunk);
// Create itemcase.
new Itemcase(type, itemstack, location, null);
}
public void spawnItem_taskStarted_pass() throws Exception {
// Create valid itemcase.
Itemcase itemcase = this.createValidItemcase();
// Create mock bukkit runnable.
ItemcaseTask runnable = PowerMockito.mock(ItemcaseTask.class);
// When creating a new bukkit runnable (as done so inside of spawnItem
// return a mock.
whenNew(ItemcaseTask.class).withAnyArguments().thenReturn(runnable);
// Pretend chunk is loaded.
when(itemcase.getLocation().getWorld().isChunkLoaded(
any(Chunk.class))).thenReturn(true);
// Spawn item.
itemcase.spawnItem();
// verify task was started.
verify(runnable)
.runTaskTimer(any(JavaPlugin.class), anyInt(), anyInt());
}
}