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. 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` * Checkout this repo and run: `mvn clean`
Coding and Pull Request Formatting Coding and Pull Request Formatting
---------------------------------- ----------------------------------
* Generally follow the Oracle coding standards. * Generally follow the Oracle coding standards.
* Use spaces not tabs. * Use spaces not tabs.
* No trailing whitespaces. * 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.** **Please try to follow the above conventions if you want your pull request(s) accepted.**
[License]: http://www.gnu.org/licenses/gpl.html [License]: http://www.gnu.org/licenses/gpl.html
[GitHub]: http://github.com/BleedObsidian/ItemCase/ [GitHub]: http://github.com/BleedObsidian/ItemCase/
[Bukkit]: http://dev.bukkit.org/bukkit-plugins/itemcase/ [Bukkit]: http://dev.bukkit.org/bukkit-plugins/itemcase/
[Javadoc]: http://bleedobsidian.github.io/ItemCase/ [Javadoc]: http://bleedobsidian.github.io/ItemCase/

114
pom.xml
View File

@ -1,85 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?> <?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> <modelVersion>4.0.0</modelVersion>
<groupId>com.gmail.bleedobsidian</groupId> <groupId>com.gmail.bleedobsidian</groupId>
<artifactId>ItemCase</artifactId> <artifactId>ItemCase</artifactId>
<name>ItemCase</name> <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> <version>2.0.0</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.source>16</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.target>16</maven.compiler.target>
</properties> </properties>
<repositories> <repositories>
<repository> <repository>
<id>spigot-repo</id> <id>sk89q-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url> <url>https://maven.enginehub.org/repo/</url>
</repository> </repository>
<repository> <repository>
<id>bstats-repo</id> <id>spigot-repo</id>
<url>http://repo.bstats.org/content/repositories/releases/</url> <url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
</repository> </repository>
<repository> <repository>
<id>vault-repo</id> <id>vault-repo</id>
<url>http://nexus.hc.to/content/repositories/pub_releases</url> <url>http://nexus.hc.to/content/repositories/pub_releases</url>
</repository> </repository>
<repository> <repository>
<id>sk89q-repo</id> <id>OnARandomBox</id>
<url>http://maven.sk89q.com/repo/</url> <url>https://repo.onarandombox.com/content/groups/public/</url>
</repository> </repository>
</repositories> </repositories>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.spigotmc</groupId> <groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId> <artifactId>spigot-api</artifactId>
<version>1.12.2-R0.1-SNAPSHOT</version> <version>1.17.1-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>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.onarandombox.multiversecore</groupId> <groupId>com.onarandombox.multiversecore</groupId>
<artifactId>Multiverse-Core</artifactId> <artifactId>Multiverse-Core</artifactId>
<version>2.5.0</version> <version>4.3.1</version>
<scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>net.milkbowl.vault</groupId> <groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId> <artifactId>VaultAPI</artifactId>
<version>1.6</version> <version>1.7</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.sk89q.worldguard</groupId> <groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard</artifactId> <artifactId>worldguard-bukkit</artifactId>
<version>6.2.1</version> <version>7.0.7-SNAPSHOT</version>
</dependency> <scope>provided</scope>
<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>
</dependency> </dependency>
</dependencies> </dependencies>
@ -108,52 +87,19 @@
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version> <version>3.8.1</version>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<version>2.4</version> <version>3.2.0</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>
<configuration> <configuration>
<finalName>${artifactId}</finalName> <archive>
<artifactSet> <addMavenDescriptor>false</addMavenDescriptor>
<excludes> </archive>
<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>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -15,117 +15,118 @@
package com.gmail.bleedobsidian.itemcase; package com.gmail.bleedobsidian.itemcase;
import com.gmail.bleedobsidian.itemcase.configurations.LanguageFile; import com.gmail.bleedobsidian.itemcase.configurations.LanguageFile;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map.Entry; import java.util.Map.Entry;
import org.bukkit.plugin.java.JavaPlugin;
/** /**
* Utility class used for communicating in different dialects. * Utility class used for communicating in different dialects.
* *
* @author Jesse Prescott (BleedObsidian). * @author Jesse Prescott (BleedObsidian).
*/ */
public final class LanguageTranslator { public final class LanguageTranslator {
/** /**
* Supported languages. * Supported languages.
*/ */
public static enum Language { public enum Language {
EN EN
}; }
/** /**
* The language file for the chosen language. * The language file for the chosen language.
*/ */
private LanguageFile file; private LanguageFile file;
/** /**
* A hash map of placeholders. * A hash map of placeholders.
*/ */
private HashMap<String, String> placeholders = new HashMap<>(); private final HashMap<String, String> placeholders = new HashMap<>();
/** /**
* Load corresponding language file. * Load corresponding language file.
* *
* @param plugin JavaPlugin. * @param plugin JavaPlugin.
* @param language Language to communicate in. * @param language Language to communicate in.
* @return If loading was successful. * @return If loading was successful.
*/ */
public boolean load(JavaPlugin plugin, Language language) { public boolean load(JavaPlugin plugin, Language language) {
// Create language file. // Create language file.
this.file = new LanguageFile(language); this.file = new LanguageFile(language);
// Attempt to load language file. // Attempt to load language file.
try { try {
// Load language file. // Load language file.
this.file.load(plugin); this.file.load(plugin);
} catch (IOException e) { } catch (IOException e) {
// Display error. // Display error.
ItemCaseCore.instance.getConsoleLogger().severe( ItemCaseCore.instance.getConsoleLogger().severe(
"Failed to load configuration file.", e); "Failed to load configuration file.", e);
// Failed to load. // Failed to load.
return false; return false;
} }
// Successfully loaded. // Successfully loaded.
return true; return true;
} }
/** /**
* Get translation. * Get translation.
* *
* @param key Message key. * @param key Message key.
* @return String. * @return String.
*/ */
public String getTranslation(String key) { public String getTranslation(String key) {
// Get raw translation. // Get raw translation.
String translation = this.file.getRawTranslation(key); String translation = this.file.getRawTranslation(key);
// For every placeholder. // 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 // Replace the placeholder with given value if placeholder is
// present in string. // present in string.
translation = translation.replace(entry.getKey(), entry.getValue()); translation = translation.replace(entry.getKey(), entry.getValue());
} }
// Return translation. // Return translation.
return translation; return translation;
} }
/** /**
* Set the value of a given placeholder. * Set the value of a given placeholder.
* *
* @param placeholder Placeholder. * @param placeholder Placeholder.
* @param value Value. * @param value Value.
*/ */
public void setPlaceholder(String placeholder, String value) { public void setPlaceholder(String placeholder, String value) {
// Update HashMap. // Update HashMap.
this.placeholders.put(placeholder, value); this.placeholders.put(placeholder, value);
} }
/** /**
* If given string is a valid message key. * If given string is a valid message key.
* *
* @param string String. * @param string String.
* @return Boolean. * @return Boolean.
*/ */
public boolean isKey(String string) { public boolean isKey(String string) {
// If the file is not loaded yet. // 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 as we cant do translations yet.
return false; return false;
} }
// Check if key exists and return result. // Check if key exists and return result.
return this.file.hasKey(string); 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; package com.gmail.bleedobsidian.itemcase.commands;
import com.gmail.bleedobsidian.itemcase.Command; import com.gmail.bleedobsidian.itemcase.Command;
import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import com.gmail.bleedobsidian.itemcase.ItemCaseCore; import com.gmail.bleedobsidian.itemcase.ItemCaseCore;
import com.gmail.bleedobsidian.itemcase.LanguageTranslator; import com.gmail.bleedobsidian.itemcase.LanguageTranslator;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import java.util.ArrayList;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
/** /**
* A command handler for the 'create' command. * A command handler for the 'create' command.
* *
* @author Jesse Prescott (BleedObsidian) * @author Jesse Prescott (BleedObsidian)
*/ */
public final class CreateCommand implements Command { public final class CreateCommand implements Command {
@Override @Override
public void execute(CommandSender sender, String label, public void execute(CommandSender sender, String label,
String[] args) { String[] args) {
// If sender is not a player. // If sender is not a player.
if(!(sender instanceof Player)) { if (!(sender instanceof Player player)) {
// Send message. // Send message.
ItemCaseCore.instance.getGenericLogger().message( ItemCaseCore.instance.getGenericLogger().message(
sender, "command.not-player"); sender, "command.not-player");
// Exit. // Exit.
return; return;
} }
// Cast sender to player. // Cast sender to player.
Player player = (Player) sender;
// Check if player is asking for help. // Check if player is asking for help.
if(this.isAskingForHelp(player, label, args)) { if (this.isAskingForHelp(player, label, args)) {
// Exit. // Exit.
return; return;
} }
// Get chat logger. // Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger(); ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// Check if player has permission. // Check if player has permission.
if(!player.hasPermission("itemcase.create")) { if (!player.hasPermission("itemcase.create")) {
// Send message. // Send message.
chatLogger.message(player, "command.permission"); chatLogger.message(player, "command.permission");
// Exit. // Exit.
return; return;
} }
// List of materials that can be used as itemcases. // List of materials that can be used as itemcases.
ArrayList<Material> materials = ArrayList<Material> materials =
ItemCaseCore.instance.getConfigFile().getMaterials(); ItemCaseCore.instance.getConfigFile().getMaterials();
// The target location. // The target location.
Location target = null; Location target;
// ItemStack to use. // ItemStack to use.
ItemStack itemStack = null; ItemStack itemStack;
// Get the players target block. // Get the players target block.
target = player.getTargetBlock(null, 5).getLocation(); target = player.getTargetBlock(null, 5).getLocation();
// Check if itemcase already exists here. // Check if itemcase already exists here.
if(ItemCaseCore.instance.getItemcaseManager().isItemcase(target)) { if (ItemCaseCore.instance.getItemcaseManager().isItemcase(target)) {
// Show message. // Show message.
chatLogger.message(player, "command.create.invalid-location"); chatLogger.message(player, "command.create.invalid-location");
// Exit. // Exit.
return; return;
} }
// If target block is not on the list of accepted materials. // 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. // Show message.
chatLogger.message(player, "command.create.invalid-type"); chatLogger.message(player, "command.create.invalid-type");
@ -103,29 +106,21 @@ public final class CreateCommand implements Command {
// Exit. // Exit.
return; 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. // Get item in players main hand to use as the Itemcase item.
itemStack = player.getInventory().getItemInMainHand(); 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 the player is not holding anything...
if(itemStack == null || itemStack.getType() == Material.AIR) { if (itemStack.getType() == Material.AIR) {
// Show message. // Show message.
chatLogger.message(player, "command.create.main-hand"); chatLogger.message(player, "command.create.main-hand");
@ -133,51 +128,51 @@ public final class CreateCommand implements Command {
// Exit. // Exit.
return; return;
} }
// Create itemcase. // Create itemcase.
ItemCaseCore.instance.getItemcaseManager().createItemcase( ItemCaseCore.instance.getItemcaseManager().createItemcase(
itemStack, target, player); itemStack, target, player);
// Show message. // Show message.
chatLogger.message(player, "command.create.success"); chatLogger.message(player, "command.create.success");
} }
/** /**
* @return If the command sender is asking for help about this command. * @return If the command sender is asking for help about this command.
*/ */
public boolean isAskingForHelp(Player player, String label, String[] args) { public boolean isAskingForHelp(Player player, String label, String[] args) {
// If args length equals 2. // If args length equals 2.
if(args.length != 2) { if (args.length != 2) {
// False. // False.
return false; return false;
} }
// Get argument. // Get argument.
String argument = args[1]; String argument = args[1];
// If not equal to help. // If not equal to help.
if(!argument.equalsIgnoreCase("help")) { if (!argument.equalsIgnoreCase("help")) {
return false; return false;
} }
// Get chat logger. // Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger(); ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// Get translator. // Get translator.
LanguageTranslator translator = ItemCaseCore.instance.getTranslator(); LanguageTranslator translator = ItemCaseCore.instance.getTranslator();
// Set placeholder. // Set placeholder.
translator.setPlaceholder("%COMMAND%", "/" + label + " create"); translator.setPlaceholder("%COMMAND%", "/" + label + " create");
// Show command help. // Show command help.
chatLogger.message(player, "command.itemcase-help"); chatLogger.message(player, "command.itemcase-help");
// Show specific help. // Show specific help.
chatLogger.message(player, "command.create.help"); chatLogger.message(player, "command.create.help");
// Return. // Return.
return true; return true;
} }

View File

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

View File

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

View File

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

View File

@ -15,12 +15,12 @@
package com.gmail.bleedobsidian.itemcase.commands; package com.gmail.bleedobsidian.itemcase.commands;
import com.gmail.bleedobsidian.itemcase.Command; import com.gmail.bleedobsidian.itemcase.Command;
import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import com.gmail.bleedobsidian.itemcase.ItemCaseCore; import com.gmail.bleedobsidian.itemcase.ItemCaseCore;
import com.gmail.bleedobsidian.itemcase.Itemcase; import com.gmail.bleedobsidian.itemcase.Itemcase;
import com.gmail.bleedobsidian.itemcase.Itemcase.StorageType; import com.gmail.bleedobsidian.itemcase.Itemcase.StorageType;
import com.gmail.bleedobsidian.itemcase.Itemcase.Type; import com.gmail.bleedobsidian.itemcase.Itemcase.Type;
import com.gmail.bleedobsidian.itemcase.LanguageTranslator; import com.gmail.bleedobsidian.itemcase.LanguageTranslator;
import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -28,146 +28,145 @@ import org.bukkit.entity.Player;
/** /**
* A command handler for the 'create' command. * A command handler for the 'create' command.
* *
* @author Jesse Prescott (BleedObsidian) * @author Jesse Prescott (BleedObsidian)
*/ */
public final class StorageCommand implements Command { public final class StorageCommand implements Command {
@Override @Override
public void execute(CommandSender sender, String label, public void execute(CommandSender sender, String label,
String[] args) { String[] args) {
// If sender is not a player. // If sender is not a player.
if(!(sender instanceof Player)) { if (!(sender instanceof Player player)) {
// Send message. // Send message.
ItemCaseCore.instance.getGenericLogger().message( ItemCaseCore.instance.getGenericLogger().message(
sender, "command.not-player"); sender, "command.not-player");
// Exit. // Exit.
return; return;
} }
// Cast sender to player. // Cast sender to player.
Player player = (Player) sender;
// Check if player is asking for help. // Check if player is asking for help.
if(this.isAskingForHelp(player, label, args)) { if (this.isAskingForHelp(player, label, args)) {
// Exit. // Exit.
return; return;
} }
// Get chat logger. // Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger(); ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// Check if player has permission. // Check if player has permission.
if(!player.hasPermission("itemcase.create")) { if (!player.hasPermission("itemcase.create")) {
// Send message. // Send message.
chatLogger.message(player, "command.permission"); chatLogger.message(player, "command.permission");
// Exit. // Exit.
return; return;
} }
// The target location. // The target location.
Location target = null; Location target;
// Get the players target block. // Get the players target block.
target = player.getTargetBlock(null, 5).getLocation(); target = player.getTargetBlock(null, 5).getLocation();
// Check if itemcase exists here. // Check if itemcase exists here.
if(!ItemCaseCore.instance.getItemcaseManager().isItemcase(target)) { if (!ItemCaseCore.instance.getItemcaseManager().isItemcase(target)) {
// Show message. // Show message.
chatLogger.message(player, "command.invalid-location"); chatLogger.message(player, "command.invalid-location");
// Exit. // Exit.
return; return;
} }
// Get itemcase. // Get itemcase.
Itemcase itemcase = Itemcase itemcase =
ItemCaseCore.instance.getItemcaseManager().getItemcase(target); ItemCaseCore.instance.getItemcaseManager().getItemcase(target);
// Get owner. // Get owner.
OfflinePlayer owner = itemcase.getOwner(); OfflinePlayer owner = itemcase.getOwner();
// Check if this player owns this itemcase. // 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. // Check if player is allowed to modify other peoples itemcases.
if(!player.hasPermission("itemcase.modify.other")) { if (!player.hasPermission("itemcase.modify.other")) {
// Show message. // Show message.
chatLogger.message(player, "command.not-owner"); chatLogger.message(player, "command.not-owner");
// Exit. // Exit.
return; return;
} }
} }
// Check if itemcase is a shop. // Check if itemcase is a shop.
if(itemcase.getType() == Type.SHOWCASE) { if (itemcase.getType() == Type.SHOWCASE) {
// Show message. // Show message.
chatLogger.message(player, "command.not-shop"); chatLogger.message(player, "command.not-shop");
// Exit. // Exit.
return; return;
} }
// If itemcase has infinite storage. // If itemcase has infinite storage.
if(itemcase.getStorageType() == StorageType.INFINITE) { if (itemcase.getStorageType() == StorageType.INFINITE) {
// Show message. // Show message.
chatLogger.message(player, "command.storage.infinite"); chatLogger.message(player, "command.storage.infinite");
// Exit. // Exit.
return; return;
} }
// Open itemcase storage to player. // Open itemcase storage to player.
player.openInventory(itemcase.getStorage()); player.openInventory(itemcase.getStorage());
} }
/** /**
* @return If the command sender is asking for help about this command. * @return If the command sender is asking for help about this command.
*/ */
public boolean isAskingForHelp(Player player, String label, String[] args) { public boolean isAskingForHelp(Player player, String label, String[] args) {
// If args length equals 2. // If args length equals 2.
if(args.length != 2) { if (args.length != 2) {
// False. // False.
return false; return false;
} }
// Get argument. // Get argument.
String argument = args[1]; String argument = args[1];
// If not equal to help. // If not equal to help.
if(!argument.equalsIgnoreCase("help")) { if (!argument.equalsIgnoreCase("help")) {
return false; return false;
} }
// Get chat logger. // Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger(); ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// Get translator. // Get translator.
LanguageTranslator translator = ItemCaseCore.instance.getTranslator(); LanguageTranslator translator = ItemCaseCore.instance.getTranslator();
// Set placeholder. // Set placeholder.
translator.setPlaceholder("%COMMAND%", "/" + label + " storage"); translator.setPlaceholder("%COMMAND%", "/" + label + " storage");
// Show command help. // Show command help.
chatLogger.message(player, "command.itemcase-help"); chatLogger.message(player, "command.itemcase-help");
// Show specific help. // Show specific help.
chatLogger.message(player, "command.storage.help"); chatLogger.message(player, "command.storage.help");
// Return. // Return.
return true; 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.ConfigurationFile;
import com.gmail.bleedobsidian.itemcase.LanguageTranslator.Language; import com.gmail.bleedobsidian.itemcase.LanguageTranslator.Language;
import java.util.ArrayList;
import org.bukkit.Material; import org.bukkit.Material;
import java.util.ArrayList;
/** /**
* The main configuration file for ItemCase. * The main configuration file for ItemCase.
* *
* @author Jesse Prescott (BleedObsidian) * @author Jesse Prescott (BleedObsidian)
*/ */
public final class ConfigFile extends ConfigurationFile { public final class ConfigFile extends ConfigurationFile {
/** /**
* Constructor. * Constructor.
*/ */
public ConfigFile() { public ConfigFile() {
// The name of this configuration file. // The name of this configuration file.
super("config.yml"); super("config.yml");
} }
/** /**
* @return The chosen Language to use. * @return The chosen Language to use.
*/ */
public Language getLocale() { public Language getLocale() {
// Get set locale string. // Get set locale string.
String locale = this.file.getString("Locale"); String locale = this.file.getString("Locale");
// Convert to uppercase just in case. // Convert to uppercase just in case.
locale = locale.toUpperCase(); locale = locale.toUpperCase();
// Return equivalent language. // Return equivalent language.
return Language.valueOf(locale); return Language.valueOf(locale);
} }
/** /**
* @return An array list of materials that can be used as Itemcases. * @return An array list of materials that can be used as Itemcases.
*/ */
public ArrayList<Material> getMaterials() { public ArrayList<Material> getMaterials() {
// Create array list. // Create array list.
ArrayList<Material> materials = new ArrayList<>(); ArrayList<Material> materials = new ArrayList<>();
// Loop through all material IDs in config. // Loop through all material IDs in config.
this.file.getStringList("Materials").forEach((id) -> { this.file.getStringList("Materials").forEach((id) -> {
// Add material to list. // Add material to list.
materials.add(Material.getMaterial(id)); Material material = Material.getMaterial(id);
if (material != null) {
materials.add(material);
}
}); });
// Return list. // Return list.
return materials; 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. * A configuration file that holds the translations for a specific dialect.
* *
* @author Jesse Prescott (BleedObsidian) * @author Jesse Prescott (BleedObsidian)
*/ */
public final class LanguageFile extends ConfigurationFile { public final class LanguageFile extends ConfigurationFile {
/** /**
* Constructor. * Constructor.
* *
* @param Language The language this file is for. * @param language The language this file is for.
*/ */
public LanguageFile(Language language) { public LanguageFile(Language language) {
// Give config file name and prevent file being copied outside of jar. // Give config file name and prevent file being copied outside of jar.
super("languages/" + language.name() + ".yml", false); super("languages/" + language.name() + ".yml", false);
} }
/** /**
* Get the raw translation for the given message key. * Get the raw translation for the given message key.
* *
* @param key Key. * @param key Key.
* @return String. * @return String.
*/ */
public String getRawTranslation(String key) { public String getRawTranslation(String key) {
return this.file.getString(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;
import com.gmail.bleedobsidian.itemcase.Itemcase.StorageType; import com.gmail.bleedobsidian.itemcase.Itemcase.StorageType;
import com.gmail.bleedobsidian.itemcase.Itemcase.Type; 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.File;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
@ -27,335 +38,319 @@ import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import java.util.UUID; 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. * A configuration file that holds all Itemcase saves for a specific world.
* *
* @author Jesse Prescott (BleedObsidian) * @author Jesse Prescott (BleedObsidian)
*/ */
public final class WorldFile extends ConfigurationFile { public final class WorldFile extends ConfigurationFile {
/** /**
* The world this configuration file is for. * The world this configuration file is for.
*/ */
private final World world; private final World world;
/** /**
* Constructor. * Constructor.
* *
* @param world World. * @param world World.
*/ */
public WorldFile(World world) { public WorldFile(World world) {
// Append world name to config file name. // Append world name to config file name.
super(world.getName() + "/itemcases.yml", "itemcases.yml"); super(world.getName() + "/itemcases.yml", "itemcases.yml");
// Set world. // Set world.
this.world = world; this.world = world;
} }
/** /**
* Saves the given Itemcase to config. * Saves the given Itemcase to config.
* *
* @param itemcase Itemcase. * @param itemcase Itemcase.
* @throws java.io.IOException
*/ */
public void saveItemcase(Itemcase itemcase) throws IOException { public void saveItemcase(Itemcase itemcase) throws IOException {
// Get block coordinates of Itemcase. // Get block coordinates of Itemcase.
int blockX = itemcase.getLocation().getBlockX(); int blockX = itemcase.getLocation().getBlockX();
int blockY = itemcase.getLocation().getBlockY(); int blockY = itemcase.getLocation().getBlockY();
int blockZ = itemcase.getLocation().getBlockZ(); int blockZ = itemcase.getLocation().getBlockZ();
// Create a unique key for this itemcase based on location. // Create a unique key for this itemcase based on location.
String key = "itemcases." + blockX + "/" + blockY + "/" + blockZ + "."; String key = "itemcases." + blockX + "/" + blockY + "/" + blockZ + ".";
// Set this Itemcase's type. // Set this Itemcase's type.
this.file.set(key + "type", itemcase.getType().name()); this.file.set(key + "type", itemcase.getType().name());
// Set this Itemcase's Owner. // Set this Itemcase's Owner.
String uuid = itemcase.getOwner().getUniqueId().toString(); String uuid = itemcase.getOwner().getUniqueId().toString();
this.file.set(key + "owner", uuid); this.file.set(key + "owner", uuid);
// Set this Itemcase's ItemStack. // Set this Itemcase's ItemStack.
Map<String, Object> itemstack = itemcase.getItemStack().serialize(); Map<String, Object> itemstack = itemcase.getItemStack().serialize();
this.file.set(key + "itemstack", itemstack); this.file.set(key + "itemstack", itemstack);
// If itemcase is a shop. // If itemcase is a shop.
if(itemcase.getType() != Type.SHOWCASE) { if (itemcase.getType() != Type.SHOWCASE) {
// Set storage type. // Set storage type.
this.file.set(key + "shop.storage-type", this.file.set(key + "shop.storage-type",
itemcase.getStorageType().name()); itemcase.getStorageType().name());
// If shop has finite storage. // If shop has finite storage.
if(itemcase.getStorageType() == StorageType.FINITE) { if (itemcase.getStorageType() == StorageType.FINITE) {
// Serialize inventory. // Serialize inventory.
Map<String, Object> inventory = Map<String, Object> inventory =
this.serializeInventory(itemcase.getStorage()); this.serializeInventory(itemcase.getStorage());
// Set inventory. // Set inventory.
this.file.set(key + "shop.storage", inventory); this.file.set(key + "shop.storage", inventory);
} }
// If this itemcase buys. // If this itemcase buys.
if(itemcase.getType() == Type.SHOP_BUY || if (itemcase.getType() == Type.SHOP_BUY ||
itemcase.getType() == Type.SHOP_MULTI) { itemcase.getType() == Type.SHOP_MULTI) {
// Set buy price. // Set buy price.
this.file.set(key + "shop.buy-price", itemcase.getBuyPrice()); this.file.set(key + "shop.buy-price", itemcase.getBuyPrice());
} }
// If this itemcase sells. // If this itemcase sells.
if(itemcase.getType() == Type.SHOP_SELL || if (itemcase.getType() == Type.SHOP_SELL ||
itemcase.getType() == Type.SHOP_MULTI) { itemcase.getType() == Type.SHOP_MULTI) {
// Set sell price. // Set sell price.
this.file.set(key + "shop.sell-price", itemcase.getSellPrice()); this.file.set(key + "shop.sell-price", itemcase.getSellPrice());
} }
} else { } else {
// Set shop section to null. // Set shop section to null.
this.file.set(key + "shop", null); this.file.set(key + "shop", null);
} }
// Attempt to save to file. // Attempt to save to file.
this.save(ItemCaseCore.instance); this.save(ItemCaseCore.instance);
} }
/** /**
* Deletes the given Itemcase from config. * Deletes the given Itemcase from config.
* *
* @param itemcase Itemcase. * @param itemcase Itemcase.
* @throws IOException
*/ */
public void deleteItemcase(Itemcase itemcase) throws IOException { public void deleteItemcase(Itemcase itemcase) throws IOException {
// Get block coordinates of Itemcase. // Get block coordinates of Itemcase.
int blockX = itemcase.getLocation().getBlockX(); int blockX = itemcase.getLocation().getBlockX();
int blockY = itemcase.getLocation().getBlockY(); int blockY = itemcase.getLocation().getBlockY();
int blockZ = itemcase.getLocation().getBlockZ(); int blockZ = itemcase.getLocation().getBlockZ();
// Create a unique key for this itemcase based on location. // Create a unique key for this itemcase based on location.
String key = "itemcases." + blockX + "/" + blockY + "/" + blockZ; String key = "itemcases." + blockX + "/" + blockY + "/" + blockZ;
// Delete itemcase. // Delete itemcase.
this.file.set(key, null); this.file.set(key, null);
// Attempt to save to file. // Attempt to save to file.
this.save(ItemCaseCore.instance); this.save(ItemCaseCore.instance);
} }
/** /**
* Attempts to load all itemcases from the config. * Attempts to load all itemcases from the config.
* *
* @return Array list of loaded itemcases. * @return Array list of loaded itemcases.
* @throws java.io.IOException
*/ */
public ArrayList<Itemcase> loadItemcases() throws IOException { public ArrayList<Itemcase> loadItemcases() throws IOException {
// Attempt to load raw config file. // Attempt to load raw config file.
this.load(ItemCaseCore.instance); this.load(ItemCaseCore.instance);
// Create new array list to store loaded itemcases. // 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). // Get the list of keys (itemcase locations).
Set<String> keys = Set<String> keys =
this.file.getConfigurationSection("itemcases").getKeys(false); this.file.getConfigurationSection("itemcases").getKeys(false);
// For every key (itemcase). // For every key (itemcase).
for(String key : keys) { for (String key : keys) {
// Split key by '/' to obtain individual coordinates. // Split key by '/' to obtain individual coordinates.
String[] coordinates = key.split("/"); String[] coordinates = key.split("/");
// Convert to block integer coordinates. // Convert to block integer coordinates.
int blockX = Integer.parseInt(coordinates[0]); int blockX = Integer.parseInt(coordinates[0]);
int blockY = Integer.parseInt(coordinates[1]); int blockY = Integer.parseInt(coordinates[1]);
int blockZ = Integer.parseInt(coordinates[2]); int blockZ = Integer.parseInt(coordinates[2]);
// Create fuller key for ease of use later. // Create fuller key for ease of use later.
key = "itemcases." + key + "."; key = "itemcases." + key + ".";
// Convert to location. // Convert to location.
Location location = new Location(this.world, blockX, blockY, Location location = new Location(this.world, blockX, blockY,
blockZ); blockZ);
// Get type. // Get type.
Type type = Itemcase.Type.valueOf( Type type = Itemcase.Type.valueOf(
this.file.getString(key + ".type")); this.file.getString(key + ".type"));
// Get owner. // Get owner.
UUID uuid = UUID.fromString(this.file.getString(key + ".owner")); UUID uuid = UUID.fromString(this.file.getString(key + ".owner"));
OfflinePlayer owner = Bukkit.getOfflinePlayer(uuid); OfflinePlayer owner = Bukkit.getOfflinePlayer(uuid);
// Get ItemStack. // Get ItemStack.
Map<String, Object> itemstackMap = Map<String, Object> itemstackMap =
this.file.getConfigurationSection(key + "itemstack") this.file.getConfigurationSection(key + "itemstack").getValues(true);
.getValues(true);
ItemStack itemstack = ItemStack.deserialize(itemstackMap); ItemStack itemstack = ItemStack.deserialize(itemstackMap);
// Create itemcase object. // Create itemcase object.
Itemcase itemcase = new Itemcase(type, itemstack, location, owner); Itemcase itemcase = new Itemcase(type, itemstack, location, owner);
// Spawn item. // Spawn item.
itemcase.spawnItem(); itemcase.spawnItem();
// If itemcase is a shop. // If itemcase is a shop.
if(type != Type.SHOWCASE) { if (type != Type.SHOWCASE) {
// Get storage type. // Get storage type.
StorageType storageType = StorageType.valueOf( StorageType storageType = StorageType.valueOf(
this.file.getString(key + "shop.storage-type")); this.file.getString(key + "shop.storage-type"));
// Set storage type. // Set storage type.
itemcase.setStorageType(storageType); itemcase.setStorageType(storageType);
// If itemcase has finite storage. // If itemcase has finite storage.
if(storageType == StorageType.FINITE) { if (storageType == StorageType.FINITE) {
// Deserialse inventory. // De-serialise inventory.
Inventory inventory = this.deserializeInventory( Inventory inventory = this.deserializeInventory(
this.file.getConfigurationSection( this.file.getConfigurationSection(
key + "shop.storage").getValues(false)); key + "shop.storage").getValues(false));
// Set inventory. // Set inventory.
itemcase.setStorage(inventory); itemcase.setStorage(inventory);
} }
// If this itemcase buys. // 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. // Get buy price.
double buyPrice = double buyPrice =
this.file.getDouble(key + "shop.buy-price"); this.file.getDouble(key + "shop.buy-price");
// Set buy price. // Set buy price.
itemcase.setBuyPrice(buyPrice); itemcase.setBuyPrice(buyPrice);
} }
// If this itemcase sells. // 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. // Get sell price.
double sellPrice = double sellPrice =
this.file.getDouble(key + "shop.sell-price"); this.file.getDouble(key + "shop.sell-price");
// Set sell price. // Set sell price.
itemcase.setSellPrice(sellPrice); itemcase.setSellPrice(sellPrice);
} }
} }
// Add to list. // Add to list.
itemcases.add(itemcase); itemCases.add(itemcase);
} }
// Return list of loaded itemcases. // Return list of loaded itemcases.
return itemcases; return itemCases;
} }
/** /**
* Delete directory and config. * Delete directory and config.
*
* @throws IOException
*/ */
public void deleteDirectory() throws IOException { public void deleteDirectory() {
// Create file reference. // Create file reference.
File fileReference = new File(ItemCaseCore.instance.getDataFolder(), File fileReference = new File(ItemCaseCore.instance.getDataFolder(),
this.world.getName()); this.world.getName());
// Nullify reference. // Nullify reference.
this.file = null; this.file = null;
// Delete directory. // Delete directory.
FileUtils.deleteDirectory(fileReference); FileUtils.deleteFolder(fileReference);
} }
/** /**
* Serialize the given inventory. * Serialize the given inventory.
* *
* @param inventory Inventory. * @param inventory Inventory.
* @return Map. * @return Map.
*/ */
private Map<String, Object> serializeInventory(Inventory inventory) { private Map<String, Object> serializeInventory(Inventory inventory) {
// Create map. // Create map.
Map<String, Object> map = new HashMap(); Map<String, Object> map = new HashMap<>();
// Set size. // Set size.
map.put("size", inventory.getSize()); map.put("size", inventory.getSize());
// Set name. // Set name.
map.put("name", inventory.getName()); map.put("name", ((Entity) inventory).getName());
// Loop through all content slots. // 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. // Check if content slot has any items.
if (inventory.getItem(i) != null) { if (inventory.getItem(i) != null) {
// Serialize itemstack in content slot. // Serialize itemstack in content slot.
map.put("" + i, inventory.getItem(i).serialize()); map.put("" + i, inventory.getItem(i).serialize());
} }
} }
// Return map. // Return map.
return map; return map;
} }
/** /**
* Deserialize inventory from given map. * Deserialize inventory from given map.
* *
* @param map Map. * @param map Map.
* @return Inventory. * @return Inventory.
*/ */
private Inventory deserializeInventory(Map<String, Object> map) { private Inventory deserializeInventory(Map<String, Object> map) {
// Get size. // Get size.
int size = (int) map.get("size"); int size = (int) map.get("size");
// Get name. // Get name.
String name = (String) map.get("name"); String name = (String) map.get("name");
// Create inventory. // Create inventory.
Inventory inventory = Bukkit.createInventory(null, size, name); Inventory inventory = Bukkit.createInventory(null, size, name);
// For every map entry. // For every map entry.
for(Entry<String, Object> entry : map.entrySet()) { for (Entry<String, Object> entry : map.entrySet()) {
// Check entry is parameter. // Check entry is parameter.
if(entry.getKey().equals("size") || if (entry.getKey().equals("size") ||
entry.getKey().equals("name")) { entry.getKey().equals("name")) {
// Skip. // Skip.
continue; continue;
} }
// Get slot. // Get slot.
int slot = Integer.parseInt(entry.getKey()); int slot = Integer.parseInt(entry.getKey());
// Get memory section. // Get memory section.
MemorySection section = (MemorySection) entry.getValue(); MemorySection section = (MemorySection) entry.getValue();
// Deserialize item. // Deserialize item.
ItemStack item = ItemStack.deserialize((Map<String, Object>) ItemStack item = ItemStack.deserialize(section.getValues(true));
section.getValues(true));
// Set item in slot. // Set item in slot.
inventory.setItem(slot, item); inventory.setItem(slot, item);
} }
// Return inventory. // Return inventory.
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. * Utility class used for communicating to players in game with a translator.
* *
* @author Jesse Prescott (BleedObsidian). * @author Jesse Prescott (BleedObsidian).
*/ */
public final class ChatLogger { public final class ChatLogger {
@ -28,41 +28,41 @@ public final class ChatLogger {
/** /**
* The prefix placed before all messages. * The prefix placed before all messages.
*/ */
private final static String PREFIX = private final static String PREFIX =
ChatColor.BLUE + "[ItemCase]: " + ChatColor.RESET; ChatColor.BLUE + "[ItemCase]: " + ChatColor.RESET;
/** /**
* Language translator. * Language translator.
*/ */
private final LanguageTranslator translator; private final LanguageTranslator translator;
/** /**
* Constructor. * Constructor.
* *
* @param translator language translator. * @param translator language translator.
*/ */
public ChatLogger(LanguageTranslator translator) { public ChatLogger(LanguageTranslator translator) {
// Set translator. // Set translator.
this.translator = translator; this.translator = translator;
} }
/** /**
* Send given Player a message. * Send given Player a message.
* *
* @param player Player to send message. * @param player Player to send message.
* @param string Message key or message. * @param string Message key or message.
*/ */
public void message(Player player, String string) { public void message(Player player, String string) {
// If string is a message key. // If string is a message key.
if(this.translator.isKey(string)) { if (this.translator.isKey(string)) {
// Translate. // Translate.
string = this.translator.getTranslation(string); string = this.translator.getTranslation(string);
} }
// Send message. // Send message.
player.sendMessage(ChatLogger.PREFIX + string); player.sendMessage(ChatLogger.PREFIX + string);
} }

View File

@ -16,10 +16,11 @@
package com.gmail.bleedobsidian.itemcase.loggers; package com.gmail.bleedobsidian.itemcase.loggers;
import com.gmail.bleedobsidian.itemcase.LanguageTranslator; import com.gmail.bleedobsidian.itemcase.LanguageTranslator;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.LogRecord; import java.util.logging.LogRecord;
import java.util.logging.Logger; 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 * 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) * @author Jesse Prescott (BleedObsidian)
*/ */
public final class ConsoleLogger extends Logger { public final class ConsoleLogger extends Logger {
/** /**
* The plugin prefix. * The plugin prefix.
*/ */
private final String prefix; private final String prefix;
/** /**
* Language translator. * Language translator.
*/ */
private final LanguageTranslator translator; private final LanguageTranslator translator;
/** /**
* Constructor. * Constructor.
* *
* @param plugin The B * @param plugin The B
*/ */
public ConsoleLogger(JavaPlugin plugin, LanguageTranslator translator) { public ConsoleLogger(JavaPlugin plugin, LanguageTranslator translator) {
// Call parent constructor. // Call parent constructor.
super(plugin.getName(), null); super(plugin.getName(), null);
// Set logger settings. // Set logger settings.
super.setParent(plugin.getServer().getLogger()); super.setParent(plugin.getServer().getLogger());
super.setLevel(Level.ALL); super.setLevel(Level.ALL);
// Set plugin prefix. // Set plugin prefix.
this.prefix = "[" + plugin.getName() + "] "; this.prefix = "[" + plugin.getName() + "] ";
// Set translator. // Set translator.
this.translator = translator; this.translator = translator;
} }
@Override @Override
public void log(LogRecord logRecord) { public void log(LogRecord logRecord) {
// Message. // Message.
String message = logRecord.getMessage(); String message = logRecord.getMessage();
// If message is a message key. // If message is a message key.
if(translator.isKey(message)) { if (translator.isKey(message)) {
// Translate. // Translate.
message = translator.getTranslation(message); message = translator.getTranslation(message);
} }
// Default white text. // Default white text.
logRecord.setMessage(this.prefix + message); logRecord.setMessage(this.prefix + message);
// Parent. // Parent.
super.log(logRecord); super.log(logRecord);
} }
@Override @Override
public void warning(String message) { public void warning(String message) {
// Log message. // Log message.
this.log(Level.WARNING, message); this.log(Level.WARNING, message);
} }
@Override @Override
public void severe(String message) { public void severe(String message) {
// Log message. // Log message.
this.log(Level.SEVERE, message); this.log(Level.SEVERE, message);
} }
/** /**
* Severe message with throwable exception. * Severe message with throwable exception.
* *
* @param message The message to display. * @param message The message to display.
* @param throwable The exception to display. * @param throwable The exception to display.
*/ */
public void severe(String message, Throwable throwable) { public void severe(String message, Throwable throwable) {
// Log message. // Log message.
this.log(Level.SEVERE, message, throwable); 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 * Utility class used for communicating to command senders in different
* dialects. * dialects.
* *
* @author Jesse Prescott (BleedObsidian). * @author Jesse Prescott (BleedObsidian).
*/ */
public final class GenericLogger { public final class GenericLogger {
/** /**
* Language translator. * Language translator.
*/ */
private final LanguageTranslator translator; private final LanguageTranslator translator;
/** /**
* Constructor. * Constructor.
* *
* @param translator language translator. * @param translator language translator.
*/ */
public GenericLogger(LanguageTranslator translator) { public GenericLogger(LanguageTranslator translator) {
// Set translator. // Set translator.
this.translator = translator; this.translator = translator;
} }
/** /**
* Send given CommandSender a message. * Send given CommandSender a message.
* *
* @param sender CommandSender. * @param sender CommandSender.
* @param string Message key or message. * @param string Message key or message.
*/ */
public void message(CommandSender sender, String string) { public void message(CommandSender sender, String string) {
// If string is a message key. // If string is a message key.
if(this.translator.isKey(string)) { if (this.translator.isKey(string)) {
// Translate. // Translate.
string = this.translator.getTranslation(string); string = this.translator.getTranslation(string);
} }
// Send message. // Send message.
sender.sendMessage(string); 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.Itemcase.Type;
import com.gmail.bleedobsidian.itemcase.configurations.WorldFile; import com.gmail.bleedobsidian.itemcase.configurations.WorldFile;
import com.onarandombox.MultiverseCore.event.MVWorldDeleteEvent; 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.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
@ -35,44 +31,49 @@ import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.world.WorldLoadEvent; import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.inventory.ItemStack; 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. * for loading and saving Itemcases to a config.
* *
* @author Jesse Prescott (BleedObsidian) * @author Jesse Prescott (BleedObsidian)
*/ */
public final class ItemcaseManager { public final class ItemcaseManager {
/** /**
* A HashMap of each world and its corresponding WorldFile. * A HashMap of each world and its corresponding WorldFile.
*/ */
private final HashMap<World, WorldFile> worldFiles = new HashMap<>(); private final HashMap<World, WorldFile> worldFiles = new HashMap<>();
/** /**
* A list of all active Itemcase instances. * A list of all active Itemcase instances.
*/ */
private final ArrayList<Itemcase> itemcases = new ArrayList<>(); private final ArrayList<Itemcase> itemcases = new ArrayList<>();
/** /**
* Initialize this class. * Initialize this class.
*/ */
public void initialize() { public void initialize() {
// For every currently loaded world. // For every currently loaded world.
for(World world : Bukkit.getWorlds()) { for (World world : Bukkit.getWorlds()) {
// Request itemcases to be loaded. // Request itemcases to be loaded.
this.loadItemcases(world); this.loadItemcases(world);
} }
} }
/** /**
* Loads itemcases for the given world. * Loads itemcases for the given world.
* *
* @param world World. * @param world World.
*/ */
private void loadItemcases(World world) { private void loadItemcases(World world) {
// Create WorldFile object. // Create WorldFile object.
WorldFile file = new WorldFile(world); WorldFile file = new WorldFile(world);
@ -105,306 +106,299 @@ public final class ItemcaseManager {
ItemCaseCore.instance.getConsoleLogger().info( ItemCaseCore.instance.getConsoleLogger().info(
"console.info.loaded"); "console.info.loaded");
} }
/** /**
* Save given Itemcase. * Save given Itemcase.
* *
* @param itemcase Itemcase. * @param itemcase Itemcase.
*/ */
public void saveItemcases(Itemcase itemcase) { public void saveItemcases(Itemcase itemcase) {
// Get world file. // Get world file.
WorldFile file = this.worldFiles.get(itemcase.getLocation().getWorld()); WorldFile file = this.worldFiles.get(itemcase.getLocation().getWorld());
// Attempt to save itemcase. // Attempt to save itemcase.
try { try {
// Save itemcase. // Save itemcase.
file.saveItemcase(itemcase); file.saveItemcase(itemcase);
} catch (IOException e) { } catch (IOException e) {
// Log error. // Log error.
ItemCaseCore.instance.getConsoleLogger().severe( ItemCaseCore.instance.getConsoleLogger().severe(
"Failed to save itemcase to config.", e); "Failed to save itemcase to config.", e);
} }
} }
/** /**
* Create a new Itemcase. * Create a new Itemcase.
* *
* @param itemStack The ItemStack to be displayed. * @param itemStack The ItemStack to be displayed.
* @param location The location of the itemcase. * @param location The location of the itemcase.
* @param owner The owner of this itemcase. * @param owner The owner of this itemcase.
*/ */
public void createItemcase(ItemStack itemStack, Location location, public void createItemcase(ItemStack itemStack, Location location,
OfflinePlayer owner) { OfflinePlayer owner) {
// Create new itemcase instance. // Create new itemcase instance.
Itemcase itemcase = new Itemcase(Itemcase.Type.SHOWCASE, itemStack, Itemcase itemcase = new Itemcase(Itemcase.Type.SHOWCASE, itemStack,
location, owner); location, owner);
// Spawn item. // Spawn item.
itemcase.spawnItem(); itemcase.spawnItem();
// Add itemcase to the list. // Add itemcase to the list.
this.itemcases.add(itemcase); this.itemcases.add(itemcase);
// Get config file for itemcase's world. // Get config file for itemcase's world.
WorldFile file = this.worldFiles.get(location.getWorld()); WorldFile file = this.worldFiles.get(location.getWorld());
// Attempt to save itemcase. // Attempt to save itemcase.
try { try {
// Save itemcase. // Save itemcase.
file.saveItemcase(itemcase); file.saveItemcase(itemcase);
} catch (IOException e) { } catch (IOException e) {
// Log error. // Log error.
ItemCaseCore.instance.getConsoleLogger().severe( ItemCaseCore.instance.getConsoleLogger().severe(
"Failed to save new itemcase to config.", e); "Failed to save new itemcase to config.", e);
} }
} }
/** /**
* Destroy given Itemcase. * Destroy given Itemcase.
* *
* @param itemcase Itemcase. * @param itemcase Itemcase.
*/ */
public void destroyItemcase(Itemcase itemcase) { public void destroyItemcase(Itemcase itemcase) {
// Despawn Itemcase's item. // Despawn Itemcase's item.
itemcase.despawnItem(); itemcase.despawnItem();
// Remove itemcase from list. // Remove itemcase from list.
this.itemcases.remove(itemcase); this.itemcases.remove(itemcase);
// Get config file for itemcase's world. // Get config file for itemcase's world.
WorldFile file = this.worldFiles.get(itemcase.getLocation().getWorld()); WorldFile file = this.worldFiles.get(itemcase.getLocation().getWorld());
// Attempt to delete itemcase. // Attempt to delete itemcase.
try { try {
// Delete itemcase. // Delete itemcase.
file.deleteItemcase(itemcase); file.deleteItemcase(itemcase);
} catch (IOException e) { } catch (IOException e) {
// Log error. // Log error.
ItemCaseCore.instance.getConsoleLogger().severe( ItemCaseCore.instance.getConsoleLogger().severe(
"Failed to delete itemcase from config.", e); "Failed to delete itemcase from config.", e);
} }
} }
/** /**
* Unload all currently loaded Itemcases. * Unload all currently loaded Itemcases.
*/ */
public void unloadItemcases() { public void unloadItemcases() {
// For every loaded itemcase. // For every loaded itemcase.
for(Itemcase itemcase : this.itemcases) { for (Itemcase itemcase : this.itemcases) {
// Despawn the item. // Despawn the item.
itemcase.despawnItem(); itemcase.despawnItem();
} }
// Clear list. // Clear list.
this.itemcases.clear(); this.itemcases.clear();
} }
/** /**
* Register the event listener for this class. * Register the event listener for this class.
*/ */
public void registerListener() { public void registerListener() {
// Register listener with bukkit. // Register listener with bukkit.
Bukkit.getPluginManager().registerEvents( Bukkit.getPluginManager().registerEvents(
new ItemcaseManagerListener(), ItemCaseCore.instance); new ItemcaseManagerListener(), ItemCaseCore.instance);
} }
/** /**
* If the given location is an itemcase or not. * If the given location is an itemcase or not.
* *
* @param location Location. * @param location Location.
* @return Boolean. * @return Boolean.
*/ */
public boolean isItemcase(Location location) { public boolean isItemcase(Location location) {
// For every itemcase. // For every itemcase.
for(Itemcase itemcase : this.itemcases) { for (Itemcase itemcase : this.itemcases) {
// Check if location matches. // Check if location matches.
if(itemcase.getLocation().equals(location)) { if (itemcase.getLocation().equals(location)) {
// Return true. // Return true.
return true; return true;
} }
} }
// Otherwise return false. // Otherwise return false.
return false; return false;
} }
/** /**
* Attempt to get the itemcase at the given location. * Attempt to get the itemcase at the given location.
* *
* @param location Location. * @param location Location.
* @return ItemCase. * @return ItemCase.
*/ */
public Itemcase getItemcase(Location location) { public Itemcase getItemcase(Location location) {
// For every itemcase. // For every itemcase.
for(Itemcase itemcase : this.itemcases) { for (Itemcase itemcase : this.itemcases) {
// Check if location matches. // Check if location matches.
if(itemcase.getLocation().equals(location)) { if (itemcase.getLocation().equals(location)) {
// Return itemcase. // Return itemcase.
return itemcase; return itemcase;
} }
} }
// No itemcase found. // No itemcase found.
return null; return null;
} }
/** /**
* @return A list of all active Itemcase instances. * @return A list of all active Itemcase instances.
*/ */
public ArrayList<Itemcase> getItemcases() { public ArrayList<Itemcase> getItemcases() {
// List of Itemcases. // List of Itemcases.
return this.itemcases; return this.itemcases;
} }
/** /**
* A bukkit listener for the ItemcaseManager. Used to load Itemcases upon * A bukkit listener for the ItemcaseManager. Used to load Itemcases upon
* world loading. * world loading.
*/ */
private final class ItemcaseManagerListener implements Listener { private final class ItemcaseManagerListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onWorldLoadEvent(WorldLoadEvent event) { public void onWorldLoadEvent(WorldLoadEvent event) {
// Get world. // Get world.
World world = event.getWorld(); World world = event.getWorld();
// Request itemcases to be loaded. // Request itemcases to be loaded.
ItemcaseManager.this.loadItemcases(world); ItemcaseManager.this.loadItemcases(world);
} }
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onWorldDeleteEvent(MVWorldDeleteEvent event) { public void onWorldDeleteEvent(MVWorldDeleteEvent event) {
// Get world name. // Get world name.
String worldName = event.getWorld().getName(); String worldName = event.getWorld().getName();
// WorldFile. // WorldFile.
WorldFile worldFile = null; WorldFile worldFile = null;
// For every entry. // For every entry.
for(Entry<World, WorldFile> entry : for (Entry<World, WorldFile> entry :
ItemcaseManager.this.worldFiles.entrySet()) { ItemcaseManager.this.worldFiles.entrySet()) {
// Check if world name matches. // Check if world name matches.
if(entry.getKey().getName() == worldName) { if (entry.getKey().getName().equals(worldName)) {
// Attempt to delete config. // Attempt to delete config.
try {
// Set world file.
// Set world file. worldFile = entry.getValue();
worldFile = entry.getValue();
// Delete config.
// Delete config. entry.getValue().deleteDirectory();
entry.getValue().deleteDirectory();
} catch (IOException e) {
// Log error.
ItemCaseCore.instance.getConsoleLogger().severe(
"Failed to delete itemcase config for world:"
+ worldName, e);
}
} }
} }
// Remove world file. // Remove world file.
ItemcaseManager.this.worldFiles.values().remove(worldFile); ItemcaseManager.this.worldFiles.values().remove(worldFile);
// List to store itemcases of this world. // List to store itemcases of this world.
ArrayList<Itemcase> itemcases = new ArrayList(); ArrayList<Itemcase> itemcases = new ArrayList<>();
// For every itemcase. // For every itemcase.
for(Itemcase itemcase : ItemcaseManager.this.itemcases) { for (Itemcase itemcase : ItemcaseManager.this.itemcases) {
// Check if itemcase was in deleted world. // Check if itemcase was in deleted world.
if(itemcase.getLocation().getWorld().getName() == worldName) { if (itemcase.getLocation().getWorld().getName().equals(worldName)) {
// Despawn item. // Despawn item.
itemcase.despawnItem(); itemcase.despawnItem();
// Add to list. // Add to list.
itemcases.add(itemcase); itemcases.add(itemcase);
} }
} }
// Remove all itemcases that were in this world from list. // Remove all itemcases that were in this world from list.
ItemcaseManager.this.itemcases.removeAll(itemcases); ItemcaseManager.this.itemcases.removeAll(itemcases);
} }
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onInventoryCloseEvent(InventoryCloseEvent event) { public void onInventoryCloseEvent(InventoryCloseEvent event) {
// Get inventory name. // Get inventory name.
String name = event.getInventory().getName(); String name = event.getView().getTitle();
// If inventory is Itemcase inventory. // If inventory is Itemcase inventory.
if(!name.equals(Itemcase.INVENTORY_NAME)) { if (!name.equals(Itemcase.INVENTORY_NAME)) {
// Exit. // Exit.
return; return;
} }
// For every Itemcase. // 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 is not a shop it wont have storage.
if(itemcase.getType() == Type.SHOWCASE) { if (itemcase.getType() == Type.SHOWCASE) {
// Skip. // Skip.
continue; continue;
} }
// If itemcase is inifinite, it wont have storage. // If itemcase is inifinite, it wont have storage.
if(itemcase.getStorageType() == StorageType.INFINITE) { if (itemcase.getStorageType() == StorageType.INFINITE) {
// Skip. // Skip.
continue; continue;
} }
// If inventory belongs to this itemcase. // If inventory belongs to this itemcase.
if(itemcase.getStorage().equals(event.getInventory())) { if (itemcase.getStorage().equals(event.getInventory())) {
// Get world file. // Get world file.
WorldFile file = ItemcaseManager.this.worldFiles.get( WorldFile file = ItemcaseManager.this.worldFiles.get(
itemcase.getLocation().getWorld()); itemcase.getLocation().getWorld());
// Attempt to save itemcase. // Attempt to save itemcase.
try { try {
// Save itemcase. // Save itemcase.
file.saveItemcase(itemcase); file.saveItemcase(itemcase);
} catch (IOException e) { } catch (IOException e) {
// Log error. // Log error.
ItemCaseCore.instance.getConsoleLogger().severe( 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; package com.gmail.bleedobsidian.itemcase.managers;
import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import com.gmail.bleedobsidian.itemcase.ItemCaseCore; import com.gmail.bleedobsidian.itemcase.ItemCaseCore;
import com.gmail.bleedobsidian.itemcase.Itemcase; import com.gmail.bleedobsidian.itemcase.Itemcase;
import com.gmail.bleedobsidian.itemcase.Itemcase.Type; import com.gmail.bleedobsidian.itemcase.Itemcase.Type;
import com.gmail.bleedobsidian.itemcase.LanguageTranslator; import com.gmail.bleedobsidian.itemcase.LanguageTranslator;
import java.util.HashMap; import com.gmail.bleedobsidian.itemcase.loggers.ChatLogger;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.HashMap;
/** /**
* Manages all active Itemcase orders. * Manages all active Itemcase orders.
* *
* @author Jesse Prescott (BleedObsidian) * @author Jesse Prescott (BleedObsidian)
*/ */
public final class OrderManager { public final class OrderManager {
/** /**
* HashMap of players and their active orders. * 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. * Create new order.
* *
* @param itemcase Itemcase. * @param itemcase Itemcase.
* @param player Player. * @param player Player.
*/ */
public void createOrder(Itemcase itemcase, Player player) { public void createOrder(Itemcase itemcase, Player player) {
// Get chat logger. // Get chat logger.
ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger(); ChatLogger chatLogger = ItemCaseCore.instance.getChatLogger();
// Get translator. // Get translator.
LanguageTranslator translator = LanguageTranslator translator =
ItemCaseCore.instance.getTranslator(); ItemCaseCore.instance.getTranslator();
// Create new order for amount 1. // Create new order for amount 1.
ItemcaseOrder order = new ItemcaseOrder(itemcase, 1); ItemcaseOrder order = new ItemcaseOrder(itemcase, 1);
// Add to list. // Add to list.
this.orders.put(player, order); this.orders.put(player, order);
@ -60,128 +61,128 @@ public final class OrderManager {
chatLogger.message(player, "---------- Order ----------"); chatLogger.message(player, "---------- Order ----------");
// If item has custom display name. // If item has custom display name.
if(itemcase.getItemStack().getItemMeta().hasDisplayName()) { if (itemcase.getItemStack().getItemMeta().hasDisplayName()) {
// Set placeholder. // Set placeholder.
translator.setPlaceholder("%ITEM_NAME%", translator.setPlaceholder("%ITEM_NAME%",
ChatColor.GOLD + itemcase.getItemStack().getItemMeta() ChatColor.GOLD + itemcase.getItemStack().getItemMeta()
.getDisplayName()); .getDisplayName());
} else { } else {
// Set placeholder. // Set placeholder.
translator.setPlaceholder("%ITEM_NAME%", translator.setPlaceholder("%ITEM_NAME%",
ChatColor.GOLD + itemcase.getItemStack().getType().name()); ChatColor.GOLD + itemcase.getItemStack().getType().name());
} }
// Send message. // Send message.
chatLogger.message(player, "order.item"); chatLogger.message(player, "order.item");
// Set amount placeholder. // Set amount placeholder.
translator.setPlaceholder("%AMOUNT%", ChatColor.GOLD + translator.setPlaceholder("%AMOUNT%", ChatColor.GOLD +
String.valueOf(1)); String.valueOf(1));
// Send message. // Send message.
chatLogger.message(player, "order.amount"); chatLogger.message(player, "order.amount");
// If shop buys products. // If shop buys products.
if(itemcase.getType() == Type.SHOP_BUY || if (itemcase.getType() == Type.SHOP_BUY ||
itemcase.getType() == Type.SHOP_MULTI) { itemcase.getType() == Type.SHOP_MULTI) {
// Set placeholder. // Set placeholder.
translator.setPlaceholder("%BUY_PRICE%", "" + ChatColor.GOLD + translator.setPlaceholder("%BUY_PRICE%", "" + ChatColor.GOLD +
itemcase.getBuyPrice()); itemcase.getBuyPrice());
// Send message. // Send message.
chatLogger.message(player, "order.buy-price"); chatLogger.message(player, "order.buy-price");
} }
// If shop sells products. // If shop sells products.
if(itemcase.getType() == Type.SHOP_SELL || if (itemcase.getType() == Type.SHOP_SELL ||
itemcase.getType() == Type.SHOP_MULTI) { itemcase.getType() == Type.SHOP_MULTI) {
// Set placeholder. // Set placeholder.
translator.setPlaceholder("%SELL_PRICE%", "" + ChatColor.GOLD + translator.setPlaceholder("%SELL_PRICE%", "" + ChatColor.GOLD +
itemcase.getSellPrice()); itemcase.getSellPrice());
// Send message. // Send message.
chatLogger.message(player, "order.sell-price"); chatLogger.message(player, "order.sell-price");
} }
// Send message. // Send message.
chatLogger.message(player, "---------------------------"); chatLogger.message(player, "---------------------------");
// Send message. // Send message.
chatLogger.message(player, "order.help"); chatLogger.message(player, "order.help");
// Send message. // Send message.
chatLogger.message(player, "---------------------------"); chatLogger.message(player, "---------------------------");
} }
/** /**
* Mark order as completed. * Mark order as completed.
* *
* @param player Player. * @param player Player.
*/ */
public void completeOrder(Player player) { public void completeOrder(Player player) {
// Remove oder. // Remove oder.
this.orders.remove(player); this.orders.remove(player);
} }
/** /**
* @param player Player. * @param player Player.
* @return If order exists for given player. * @return If order exists for given player.
*/ */
public boolean hasOrder(Player player) { public boolean hasOrder(Player player) {
// Return if order exists for given player. // Return if order exists for given player.
return this.orders.containsKey(player); return this.orders.containsKey(player);
} }
/** /**
* @param player Player. * @param player Player.
* @return The order linked with this player. * @return The order linked with this player.
*/ */
public ItemcaseOrder getOrder(Player player) { public ItemcaseOrder getOrder(Player player) {
// Return order linked to player. // Return order linked to player.
return this.orders.get(player); return this.orders.get(player);
} }
/** /**
* An order for a specific itemcase of some amount. * An order for a specific itemcase of some amount.
*/ */
public final class ItemcaseOrder { public static final class ItemcaseOrder {
/** /**
* The itemcase this order is for. * The itemcase this order is for.
*/ */
private final Itemcase itemcase; private final Itemcase itemcase;
/** /**
* The amount. * The amount.
*/ */
private int amount; private int amount;
/** /**
* Constructor. * Constructor.
* *
* @param itemcase Itemcase. * @param itemcase Itemcase.
* @param amount Amount. * @param amount Amount.
*/ */
public ItemcaseOrder(Itemcase itemcase, int amount) { public ItemcaseOrder(Itemcase itemcase, int amount) {
// Set attributes. // Set attributes.
this.itemcase = itemcase; this.itemcase = itemcase;
this.amount = amount; this.amount = amount;
} }
/** /**
* @return Itemcase. * @return Itemcase.
*/ */
public Itemcase getItemcase() { public Itemcase getItemcase() {
// Return itemcase. // Return itemcase.
return itemcase; return itemcase;
} }
@ -190,16 +191,16 @@ public final class OrderManager {
* @return Amount. * @return Amount.
*/ */
public int getAmount() { public int getAmount() {
// Amount. // Amount.
return amount; return amount;
} }
/** /**
* @param amount Amount. * @param amount Amount.
*/ */
public void setAmount(int amount) { public void setAmount(int amount) {
// Set amount. // Set amount.
this.amount = amount; this.amount = amount;
} }

View File

@ -1,16 +1,64 @@
#-------------------- ItemCase Configuration File --------------------# #-------------------- ItemCase Configuration File -----------------#
# This file contains all of the ItemCase configuration settings that # # This file contains all the ItemCase configuration settings that #
# can be altered. # # can be altered. #
#---------------------------------------------------------------------# #------------------------------------------------------------------#
# Locale: # Locale:
# - EN # - EN
Locale: EN Locale: EN
# Materials that can be used for ItemCases. # Materials that can be used for ItemCases.
# https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/Material.html # https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/Material.html
Materials: Materials:
- 'STEP' # Slabs. - 'ACACIA_SLAB'
- 'STONE_SLAB2' # Red Sandstone Slabs. - 'ANDESITE_SLAB'
- 'WOOD_STEP' # Wooden Slabs. - 'BIRCH_SLAB'
- 'PURPUR_SLAB' # Purpur Slabs. - '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 # # Server must be stopped while changes are made to this file #
# otherwise they will be overwritten. # # otherwise they will be overwritten. #
itemcases: {} itemcases: { }

View File

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

View File

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