Convert tabs to spaces

This commit is contained in:
filoghost 2020-08-23 15:00:44 +02:00
parent 68d5ff891d
commit 4a4097e447
150 changed files with 6083 additions and 6128 deletions

View File

@ -1,28 +1,28 @@
<?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">
<modelVersion>4.0.0</modelVersion>
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>
<parent>
<groupId>me.filoghost.chestcommands</groupId>
<artifactId>chestcommands-parent</artifactId>
<version>4.0.0-SNAPSHOT</version>
</parent>
<parent>
<groupId>me.filoghost.chestcommands</groupId>
<artifactId>chestcommands-parent</artifactId>
<version>4.0.0-SNAPSHOT</version>
</parent>
<artifactId>chestcommands-api</artifactId>
<name>ChestCommands API</name>
<artifactId>chestcommands-api</artifactId>
<name>ChestCommands API</name>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
</dependency>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
</dependency>
<dependency>
<groupId>me.filoghost.fcommons</groupId>
<artifactId>fcommons</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<dependency>
<groupId>me.filoghost.fcommons</groupId>
<artifactId>fcommons</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -10,47 +10,47 @@ import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class ChestCommandsAPI {
private ChestCommandsAPI() {}
/**
* The API version is increased every time the API is modified.
* You can use it to require a minimum version, as features may
* be added (rarely removed) in future versions.
*
* @return the API version
*/
public static int getAPIVersion() {
return 1;
}
public static void registerPlaceholder(Plugin plugin, String identifier, PlaceholderReplacer placeholderReplacer) {
BackendAPI.getImplementation().registerPlaceholder(plugin, identifier, placeholderReplacer);
}
private ChestCommandsAPI() {}
/**
* Checks if a menu with a given file name was loaded by the plugin.
*
* @return if the menu was found
*/
public static boolean pluginMenuExists(String menuFileName) {
return BackendAPI.getImplementation().pluginMenuExists(menuFileName);
}
/**
* Opens a menu loaded by ChestCommands to a player.
* NOTE: this method ignores permissions.
*
* @param player the player that will see the menu
* @param menuFileName the file name of the menu to open (with the .yml extension)
* @return if the menu was found and opened
*/
public static boolean openPluginMenu(Player player, String menuFileName) {
return BackendAPI.getImplementation().openPluginMenu(player, menuFileName);
}
/**
* The API version is increased every time the API is modified.
* You can use it to require a minimum version, as features may
* be added (rarely removed) in future versions.
*
* @return the API version
*/
public static int getAPIVersion() {
return 1;
}
public static void registerPlaceholder(Plugin plugin, String identifier, PlaceholderReplacer placeholderReplacer) {
BackendAPI.getImplementation().registerPlaceholder(plugin, identifier, placeholderReplacer);
}
/**
* Checks if a menu with a given file name was loaded by the plugin.
*
* @return if the menu was found
*/
public static boolean pluginMenuExists(String menuFileName) {
return BackendAPI.getImplementation().pluginMenuExists(menuFileName);
}
/**
* Opens a menu loaded by ChestCommands to a player.
* NOTE: this method ignores permissions.
*
* @param player the player that will see the menu
* @param menuFileName the file name of the menu to open (with the .yml extension)
* @return if the menu was found and opened
*/
public static boolean openPluginMenu(Player player, String menuFileName) {
return BackendAPI.getImplementation().openPluginMenu(player, menuFileName);
}
}

View File

@ -10,10 +10,10 @@ import org.bukkit.entity.Player;
@FunctionalInterface
public interface ClickHandler {
/**
* @param player the player that clicked on the inventory
* @return true if the inventory should be closed, false otherwise
*/
ClickResult onClick(MenuView menuView, Player player);
/**
* @param player the player that clicked on the inventory
* @return true if the inventory should be closed, false otherwise
*/
ClickResult onClick(MenuView menuView, Player player);
}

View File

@ -7,7 +7,7 @@ package me.filoghost.chestcommands.api;
public enum ClickResult {
KEEP_OPEN,
CLOSE
KEEP_OPEN,
CLOSE
}

View File

@ -9,17 +9,17 @@ import org.bukkit.entity.Player;
public interface ClickableIcon extends Icon {
void setClickHandler(ClickHandler clickHandler);
void setClickHandler(ClickHandler clickHandler);
ClickHandler getClickHandler();
ClickHandler getClickHandler();
@Override
default ClickResult onClick(MenuView menuView, Player clicker) {
if (getClickHandler() != null) {
return getClickHandler().onClick(menuView, clicker);
} else {
return ClickResult.KEEP_OPEN;
}
}
@Override
default ClickResult onClick(MenuView menuView, Player clicker) {
if (getClickHandler() != null) {
return getClickHandler().onClick(menuView, clicker);
} else {
return ClickResult.KEEP_OPEN;
}
}
}

View File

@ -5,6 +5,8 @@
*/
package me.filoghost.chestcommands.api;
import java.util.List;
import java.util.Map;
import me.filoghost.chestcommands.api.internal.BackendAPI;
import org.bukkit.Color;
import org.bukkit.DyeColor;
@ -12,67 +14,64 @@ import org.bukkit.Material;
import org.bukkit.block.banner.Pattern;
import org.bukkit.enchantments.Enchantment;
import java.util.List;
import java.util.Map;
public interface ConfigurableIcon extends ClickableIcon {
static ConfigurableIcon create(Material material) {
return BackendAPI.getImplementation().createConfigurableIcon(material);
}
void setMaterial(Material material);
static ConfigurableIcon create(Material material) {
return BackendAPI.getImplementation().createConfigurableIcon(material);
}
void setMaterial(Material material);
Material getMaterial();
Material getMaterial();
void setAmount(int amount);
void setAmount(int amount);
int getAmount();
int getAmount();
void setDurability(short durability);
void setDurability(short durability);
short getDurability();
short getDurability();
void setNBTData(String nbtData);
void setNBTData(String nbtData);
String getNBTData();
String getNBTData();
void setName(String name);
String getName();
void setName(String name);
String getName();
void setLore(String... lore);
void setLore(String... lore);
void setLore(List<String> lore);
void setLore(List<String> lore);
List<String> getLore();
List<String> getLore();
void setEnchantments(Map<Enchantment, Integer> enchantments);
void setEnchantments(Map<Enchantment, Integer> enchantments);
Map<Enchantment, Integer> getEnchantments();
Map<Enchantment, Integer> getEnchantments();
void addEnchantment(Enchantment enchantment);
void addEnchantment(Enchantment enchantment);
void addEnchantment(Enchantment enchantment, Integer level);
void addEnchantment(Enchantment enchantment, Integer level);
void removeEnchantment(Enchantment enchantment);
void removeEnchantment(Enchantment enchantment);
Color getLeatherColor();
Color getLeatherColor();
void setLeatherColor(Color leatherColor);
void setLeatherColor(Color leatherColor);
String getSkullOwner();
String getSkullOwner();
void setSkullOwner(String skullOwner);
void setSkullOwner(String skullOwner);
DyeColor getBannerColor();
DyeColor getBannerColor();
void setBannerColor(DyeColor bannerColor);
void setBannerColor(DyeColor bannerColor);
List<Pattern> getBannerPatterns();
List<Pattern> getBannerPatterns();
void setBannerPatterns(List<Pattern> bannerPatterns);
void setBannerPatterns(List<Pattern> bannerPatterns);
void setPlaceholdersEnabled(boolean enabled);
void setPlaceholdersEnabled(boolean enabled);
}

View File

@ -10,8 +10,8 @@ import org.bukkit.inventory.ItemStack;
public interface Icon {
ItemStack render(Player viewer);
ItemStack render(Player viewer);
ClickResult onClick(MenuView menuView, Player clicker);
ClickResult onClick(MenuView menuView, Player clicker);
}

View File

@ -10,29 +10,29 @@ import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public interface Menu {
static Menu create(Plugin owner, String title, int rowCount) {
return BackendAPI.getImplementation().createMenu(owner, title, rowCount);
}
void setIcon(int row, int column, Icon icon);
static Menu create(Plugin owner, String title, int rowCount) {
return BackendAPI.getImplementation().createMenu(owner, title, rowCount);
}
Icon getIcon(int row, int column);
void setIcon(int row, int column, Icon icon);
String getTitle();
int getRowCount();
int getColumnCount();
Icon getIcon(int row, int column);
/**
* Opens a view of the current menu configuration.
* Updating the menu doesn't automatically update all the views.
*
* @param player the player to which the menu will be displayed
*/
MenuView open(Player player);
String getTitle();
void refreshMenuViews();
int getRowCount();
int getColumnCount();
/**
* Opens a view of the current menu configuration.
* Updating the menu doesn't automatically update all the views.
*
* @param player the player to which the menu will be displayed
*/
MenuView open(Player player);
void refreshMenuViews();
}

View File

@ -9,10 +9,10 @@ import org.bukkit.entity.Player;
public interface MenuView {
void refresh();
void refresh();
Player getViewer();
Player getViewer();
Menu getMenu();
Menu getMenu();
}

View File

@ -9,6 +9,6 @@ import org.bukkit.entity.Player;
public interface PlaceholderReplacer {
String getReplacement(Player player, String argument);
String getReplacement(Player player, String argument);
}

View File

@ -9,13 +9,13 @@ import me.filoghost.chestcommands.api.internal.BackendAPI;
import org.bukkit.inventory.ItemStack;
public interface StaticIcon extends ClickableIcon {
static StaticIcon create(ItemStack itemStack) {
return BackendAPI.getImplementation().createStaticIcon(itemStack);
}
static StaticIcon create(ItemStack itemStack) {
return BackendAPI.getImplementation().createStaticIcon(itemStack);
}
ItemStack getItemStack();
ItemStack getItemStack();
void setItemStack(ItemStack itemStack);
void setItemStack(ItemStack itemStack);
}

View File

@ -16,32 +16,32 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
public abstract class BackendAPI {
private static BackendAPI implementation;
public static void setImplementation(BackendAPI implementation) {
Preconditions.notNull(implementation, "implementation");
Preconditions.checkState(BackendAPI.implementation == null, "implementation already set");
private static BackendAPI implementation;
public static void setImplementation(BackendAPI implementation) {
Preconditions.notNull(implementation, "implementation");
Preconditions.checkState(BackendAPI.implementation == null, "implementation already set");
BackendAPI.implementation = implementation;
}
public static BackendAPI getImplementation() {
Preconditions.checkState(implementation != null, "no implementation set");
return implementation;
}
public abstract boolean pluginMenuExists(String menuFileName);
BackendAPI.implementation = implementation;
}
public static BackendAPI getImplementation() {
Preconditions.checkState(implementation != null, "no implementation set");
return implementation;
}
public abstract boolean pluginMenuExists(String menuFileName);
public abstract boolean openPluginMenu(Player player, String menuFileName);
public abstract boolean openPluginMenu(Player player, String menuFileName);
public abstract Menu createMenu(Plugin owner, String title, int rows);
public abstract ConfigurableIcon createConfigurableIcon(Material material);
public abstract Menu createMenu(Plugin owner, String title, int rows);
public abstract ConfigurableIcon createConfigurableIcon(Material material);
public abstract StaticIcon createStaticIcon(ItemStack itemStack);
public abstract StaticIcon createStaticIcon(ItemStack itemStack);
public abstract void registerPlaceholder(Plugin plugin, String identifier, PlaceholderReplacer placeholderReplacer);
public abstract void registerPlaceholder(Plugin plugin, String identifier, PlaceholderReplacer placeholderReplacer);
}

View File

@ -1,165 +1,165 @@
<?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">
<modelVersion>4.0.0</modelVersion>
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>
<parent>
<groupId>me.filoghost.chestcommands</groupId>
<artifactId>chestcommands-parent</artifactId>
<version>4.0.0-SNAPSHOT</version>
</parent>
<parent>
<groupId>me.filoghost.chestcommands</groupId>
<artifactId>chestcommands-parent</artifactId>
<version>4.0.0-SNAPSHOT</version>
</parent>
<artifactId>chestcommands-plugin</artifactId>
<name>ChestCommands Plugin</name>
<artifactId>chestcommands-plugin</artifactId>
<name>ChestCommands Plugin</name>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
</dependency>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
</dependency>
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId>
</dependency>
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId>
</dependency>
<dependency>
<groupId>me.confuser</groupId>
<artifactId>BarAPI</artifactId>
</dependency>
<dependency>
<groupId>me.confuser</groupId>
<artifactId>BarAPI</artifactId>
</dependency>
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
</dependency>
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
</dependency>
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit-lite</artifactId>
</dependency>
<dependency>
<groupId>me.filoghost.updatechecker</groupId>
<artifactId>updatechecker</artifactId>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>chestcommands-api</artifactId>
</dependency>
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit-lite</artifactId>
</dependency>
<dependency>
<groupId>me.filoghost.fcommons</groupId>
<artifactId>fcommons</artifactId>
</dependency>
</dependencies>
<dependency>
<groupId>me.filoghost.updatechecker</groupId>
<artifactId>updatechecker</artifactId>
</dependency>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
<resource>
<directory>..</directory>
<includes>
<include>LICENSE.txt</include>
<include>THIRD-PARTY.txt</include>
<include>licenses/*</include>
</includes>
</resource>
</resources>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>chestcommands-api</artifactId>
</dependency>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<!-- Appends build number to plugin version on SNAPSHOT builds. -->
<execution>
<id>set-plugin-version</id>
<phase>validate</phase>
<goals>
<goal>bsh-property</goal>
</goals>
<configuration>
<properties>
<property>pluginVersion</property>
</properties>
<source>
projectVersion = project.version;
buildNumber = System.getenv("BUILD_NUMBER");
<dependency>
<groupId>me.filoghost.fcommons</groupId>
<artifactId>fcommons</artifactId>
</dependency>
</dependencies>
String pluginVersion;
if (buildNumber != null @and projectVersion.contains("SNAPSHOT")) {
pluginVersion = projectVersion + "-b" + buildNumber;
} else {
pluginVersion = projectVersion;
}
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
<resource>
<directory>..</directory>
<includes>
<include>LICENSE.txt</include>
<include>THIRD-PARTY.txt</include>
<include>licenses/*</include>
</includes>
</resource>
</resources>
print("Project version: " + projectVersion);
print("Build number: " + buildNumber);
print("Computed plugin version: " + pluginVersion);
</source>
</configuration>
</execution>
</executions>
</plugin>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<!-- Appends build number to plugin version on SNAPSHOT builds. -->
<execution>
<id>set-plugin-version</id>
<phase>validate</phase>
<goals>
<goal>bsh-property</goal>
</goals>
<configuration>
<properties>
<property>pluginVersion</property>
</properties>
<source>
projectVersion = project.version;
buildNumber = System.getenv("BUILD_NUMBER");
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
<manifestEntries>
<Implementation-Version>${pluginVersion}</Implementation-Version>
</manifestEntries>
</archive>
</configuration>
</plugin>
String pluginVersion;
if (buildNumber != null @and projectVersion.contains("SNAPSHOT")) {
pluginVersion = projectVersion + "-b" + buildNumber;
} else {
pluginVersion = projectVersion;
}
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<shadedArtifactAttached>false</shadedArtifactAttached>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/maven/</exclude>
</excludes>
</filter>
</filters>
<relocations>
<relocation>
<pattern>org.bstats.bukkit</pattern>
<shadedPattern>me.filoghost.chestcommands.metrics</shadedPattern>
</relocation>
<relocation>
<pattern>me.filoghost.updatechecker</pattern>
<shadedPattern>me.filoghost.chestcommands.updater</shadedPattern>
</relocation>
<relocation>
<pattern>me.filoghost.fcommons</pattern>
<shadedPattern>me.filoghost.chestcommands.fcommons</shadedPattern>
</relocation>
</relocations>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
print("Project version: " + projectVersion);
print("Build number: " + buildNumber);
print("Computed plugin version: " + pluginVersion);
</source>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
<manifestEntries>
<Implementation-Version>${pluginVersion}</Implementation-Version>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<shadedArtifactAttached>false</shadedArtifactAttached>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/maven/</exclude>
</excludes>
</filter>
</filters>
<relocations>
<relocation>
<pattern>org.bstats.bukkit</pattern>
<shadedPattern>me.filoghost.chestcommands.metrics</shadedPattern>
</relocation>
<relocation>
<pattern>me.filoghost.updatechecker</pattern>
<shadedPattern>me.filoghost.chestcommands.updater</shadedPattern>
</relocation>
<relocation>
<pattern>me.filoghost.fcommons</pattern>
<shadedPattern>me.filoghost.chestcommands.fcommons</shadedPattern>
</relocation>
</relocations>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -5,6 +5,10 @@
*/
package me.filoghost.chestcommands;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import me.filoghost.chestcommands.api.internal.BackendAPI;
import me.filoghost.chestcommands.command.CommandHandler;
import me.filoghost.chestcommands.config.ConfigManager;
@ -39,185 +43,180 @@ import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class ChestCommands extends BaseJavaPlugin {
public static final String CHAT_PREFIX = ChatColor.DARK_GREEN + "[" + ChatColor.GREEN + "ChestCommands" + ChatColor.DARK_GREEN + "] " + ChatColor.GREEN;
public static final String CHAT_PREFIX = ChatColor.DARK_GREEN + "[" + ChatColor.GREEN + "ChestCommands" + ChatColor.DARK_GREEN + "] " + ChatColor.GREEN;
private static Plugin pluginInstance;
private static Path dataFolderPath;
private static Plugin pluginInstance;
private static Path dataFolderPath;
private static ConfigManager configManager;
private static MenuManager menuManager;
private static CustomPlaceholders placeholders;
private static ConfigManager configManager;
private static MenuManager menuManager;
private static CustomPlaceholders placeholders;
private static ErrorCollector lastLoadErrors;
private static String newVersion;
private static ErrorCollector lastLoadErrors;
private static String newVersion;
@Override
protected void onCheckedEnable() throws PluginEnableException {
if (!CommonsUtil.isClassLoaded("org.bukkit.inventory.ItemFlag")) { // ItemFlag was added in 1.8
if (Bukkit.getVersion().contains("(MC: 1.8)")) {
throw new PluginEnableException("ChestCommands requires a more recent version of Bukkit 1.8 to run.");
} else {
throw new PluginEnableException("ChestCommands requires at least Bukkit 1.8 to run.");
}
}
@Override
protected void onCheckedEnable() throws PluginEnableException {
if (!CommonsUtil.isClassLoaded("org.bukkit.inventory.ItemFlag")) { // ItemFlag was added in 1.8
if (Bukkit.getVersion().contains("(MC: 1.8)")) {
throw new PluginEnableException("ChestCommands requires a more recent version of Bukkit 1.8 to run.");
} else {
throw new PluginEnableException("ChestCommands requires at least Bukkit 1.8 to run.");
}
}
if (pluginInstance != null || System.getProperty("ChestCommandsLoaded") != null) {
Log.warning("Please do not use /reload or plugin reloaders. Use the command \"/cc reload\" instead.");
return;
}
if (pluginInstance != null || System.getProperty("ChestCommandsLoaded") != null) {
Log.warning("Please do not use /reload or plugin reloaders. Use the command \"/cc reload\" instead.");
return;
}
System.setProperty("ChestCommandsLoaded", "true");
System.setProperty("ChestCommandsLoaded", "true");
pluginInstance = this;
dataFolderPath = getDataFolder().toPath();
Log.setLogger(getLogger());
configManager = new ConfigManager(getDataFolderPath());
menuManager = new MenuManager();
placeholders = new CustomPlaceholders();
pluginInstance = this;
dataFolderPath = getDataFolder().toPath();
Log.setLogger(getLogger());
configManager = new ConfigManager(getDataFolderPath());
menuManager = new MenuManager();
placeholders = new CustomPlaceholders();
BackendAPI.setImplementation(new DefaultBackendAPI());
BackendAPI.setImplementation(new DefaultBackendAPI());
VaultEconomyHook.INSTANCE.setup();
BarAPIHook.INSTANCE.setup();
PlaceholderAPIHook.INSTANCE.setup();
BungeeCordHook.INSTANCE.setup();
VaultEconomyHook.INSTANCE.setup();
BarAPIHook.INSTANCE.setup();
PlaceholderAPIHook.INSTANCE.setup();
BungeeCordHook.INSTANCE.setup();
if (VaultEconomyHook.INSTANCE.isEnabled()) {
Log.info("Hooked Vault");
} else {
Log.warning("Couldn't find Vault and a compatible economy plugin! Money-related features will not work.");
}
if (VaultEconomyHook.INSTANCE.isEnabled()) {
Log.info("Hooked Vault");
} else {
Log.warning("Couldn't find Vault and a compatible economy plugin! Money-related features will not work.");
}
if (BarAPIHook.INSTANCE.isEnabled()) {
Log.info("Hooked BarAPI");
}
if (BarAPIHook.INSTANCE.isEnabled()) {
Log.info("Hooked BarAPI");
}
if (PlaceholderAPIHook.INSTANCE.isEnabled()) {
Log.info("Hooked PlaceholderAPI");
}
if (PlaceholderAPIHook.INSTANCE.isEnabled()) {
Log.info("Hooked PlaceholderAPI");
}
if (Settings.update_notifications) {
UpdateChecker.run(this, 56919, (String newVersion) -> {
ChestCommands.newVersion = newVersion;
if (Settings.update_notifications) {
UpdateChecker.run(this, 56919, (String newVersion) -> {
ChestCommands.newVersion = newVersion;
Log.info("Found a new version: " + newVersion + " (yours: v" + getDescription().getVersion() + ")");
Log.info("Download the update on Bukkit Dev:");
Log.info("https://dev.bukkit.org/projects/chest-commands");
});
}
Log.info("Found a new version: " + newVersion + " (yours: v" + getDescription().getVersion() + ")");
Log.info("Download the update on Bukkit Dev:");
Log.info("https://dev.bukkit.org/projects/chest-commands");
});
}
// Start bStats metrics
int pluginID = 3658;
new MetricsLite(this, pluginID);
// Start bStats metrics
int pluginID = 3658;
new MetricsLite(this, pluginID);
Bukkit.getPluginManager().registerEvents(new CommandListener(menuManager), this);
Bukkit.getPluginManager().registerEvents(new InventoryListener(menuManager), this);
Bukkit.getPluginManager().registerEvents(new JoinListener(), this);
Bukkit.getPluginManager().registerEvents(new SignListener(menuManager), this);
Bukkit.getPluginManager().registerEvents(new CommandListener(menuManager), this);
Bukkit.getPluginManager().registerEvents(new InventoryListener(menuManager), this);
Bukkit.getPluginManager().registerEvents(new JoinListener(), this);
Bukkit.getPluginManager().registerEvents(new SignListener(menuManager), this);
CommandFramework.register(this, new CommandHandler(menuManager, "chestcommands"));
CommandFramework.register(this, new CommandHandler(menuManager, "chestcommands"));
ErrorCollector errorCollector = load();
ErrorCollector errorCollector = load();
if (errorCollector.hasErrors()) {
errorCollector.logToConsole();
Bukkit.getScheduler().runTaskLater(this, () -> {
Bukkit.getConsoleSender().sendMessage(
ChestCommands.CHAT_PREFIX + ChatColor.RED + "Encountered " + errorCollector.getErrorsCount() + " error(s) on load. "
+ "Check previous console logs or run \"/chestcommands errors\" to see them again.");
}, 10L);
}
if (errorCollector.hasErrors()) {
errorCollector.logToConsole();
Bukkit.getScheduler().runTaskLater(this, () -> {
Bukkit.getConsoleSender().sendMessage(
ChestCommands.CHAT_PREFIX + ChatColor.RED + "Encountered " + errorCollector.getErrorsCount() + " error(s) on load. "
+ "Check previous console logs or run \"/chestcommands errors\" to see them again.");
}, 10L);
}
Bukkit.getScheduler().runTaskTimer(this, new TickingTask(), 1L, 1L);
}
Bukkit.getScheduler().runTaskTimer(this, new TickingTask(), 1L, 1L);
}
@Override
public void onDisable() {
closeAllMenus();
}
@Override
public void onDisable() {
closeAllMenus();
}
public static ErrorCollector load() {
ErrorCollector errorCollector = new PrintableErrorCollector();
menuManager.clear();
boolean isFreshInstall = !Files.isDirectory(configManager.getRootDataFolder());
try {
Files.createDirectories(configManager.getRootDataFolder());
} catch (IOException e) {
errorCollector.add(e, Errors.Config.createDataFolderIOException);
return errorCollector;
}
public static ErrorCollector load() {
ErrorCollector errorCollector = new PrintableErrorCollector();
menuManager.clear();
boolean isFreshInstall = !Files.isDirectory(configManager.getRootDataFolder());
try {
Files.createDirectories(configManager.getRootDataFolder());
} catch (IOException e) {
errorCollector.add(e, Errors.Config.createDataFolderIOException);
return errorCollector;
}
UpgradesExecutor upgradeExecutor = new UpgradesExecutor(configManager);
UpgradesExecutor upgradeExecutor = new UpgradesExecutor(configManager);
try {
boolean allUpgradesSuccessful = upgradeExecutor.run(isFreshInstall, errorCollector);
if (!allUpgradesSuccessful) {
errorCollector.add(Errors.Upgrade.failedSomeUpgrades);
}
} catch (UpgradeExecutorException e) {
errorCollector.add(e, Errors.Upgrade.genericExecutorError);
errorCollector.add(Errors.Upgrade.failedSomeUpgrades);
}
try {
boolean allUpgradesSuccessful = upgradeExecutor.run(isFreshInstall, errorCollector);
if (!allUpgradesSuccessful) {
errorCollector.add(Errors.Upgrade.failedSomeUpgrades);
}
} catch (UpgradeExecutorException e) {
errorCollector.add(e, Errors.Upgrade.genericExecutorError);
errorCollector.add(Errors.Upgrade.failedSomeUpgrades);
}
configManager.tryLoadSettings(errorCollector);
configManager.tryLoadLang(errorCollector);
placeholders = configManager.tryLoadCustomPlaceholders(errorCollector);
PlaceholderManager.setStaticPlaceholders(placeholders.getPlaceholders());
configManager.tryLoadSettings(errorCollector);
configManager.tryLoadLang(errorCollector);
placeholders = configManager.tryLoadCustomPlaceholders(errorCollector);
PlaceholderManager.setStaticPlaceholders(placeholders.getPlaceholders());
// Create the menu folder with the example menu
if (!Files.isDirectory(configManager.getMenusFolder())) {
ConfigLoader exampleMenuLoader = configManager.getConfigLoader(configManager.getMenusFolder().resolve("example.yml"));
configManager.tryCreateDefault(errorCollector, exampleMenuLoader);
}
// Create the menu folder with the example menu
if (!Files.isDirectory(configManager.getMenusFolder())) {
ConfigLoader exampleMenuLoader = configManager.getConfigLoader(configManager.getMenusFolder().resolve("example.yml"));
configManager.tryCreateDefault(errorCollector, exampleMenuLoader);
}
List<LoadedMenu> loadedMenus = configManager.tryLoadMenus(errorCollector);
for (LoadedMenu loadedMenu : loadedMenus) {
menuManager.registerMenu(loadedMenu, errorCollector);
}
List<LoadedMenu> loadedMenus = configManager.tryLoadMenus(errorCollector);
for (LoadedMenu loadedMenu : loadedMenus) {
menuManager.registerMenu(loadedMenu, errorCollector);
}
ChestCommands.lastLoadErrors = errorCollector;
return errorCollector;
}
ChestCommands.lastLoadErrors = errorCollector;
return errorCollector;
}
public static void closeAllMenus() {
for (Player player : Bukkit.getOnlinePlayers()) {
if (MenuManager.getOpenMenuView(player) != null) {
player.closeInventory();
}
}
}
public static void closeAllMenus() {
for (Player player : Bukkit.getOnlinePlayers()) {
if (MenuManager.getOpenMenuView(player) != null) {
player.closeInventory();
}
}
}
public static Plugin getPluginInstance() {
return pluginInstance;
}
public static Plugin getPluginInstance() {
return pluginInstance;
}
public static Path getDataFolderPath() {
return dataFolderPath;
}
public static Path getDataFolderPath() {
return dataFolderPath;
}
public static MenuManager getMenuManager() {
return menuManager;
}
public static MenuManager getMenuManager() {
return menuManager;
}
public static boolean hasNewVersion() {
return newVersion != null;
}
public static boolean hasNewVersion() {
return newVersion != null;
}
public static String getNewVersion() {
return newVersion;
}
public static ErrorCollector getLastLoadErrors() {
return lastLoadErrors;
}
public static String getNewVersion() {
return newVersion;
}
public static ErrorCollector getLastLoadErrors() {
return lastLoadErrors;
}
}

View File

@ -23,46 +23,46 @@ import org.bukkit.plugin.Plugin;
public class DefaultBackendAPI extends BackendAPI {
@Override
public boolean pluginMenuExists(String menuFileName) {
Preconditions.notNull(menuFileName, "menuFileName");
@Override
public boolean pluginMenuExists(String menuFileName) {
Preconditions.notNull(menuFileName, "menuFileName");
return ChestCommands.getMenuManager().getMenuByFileName(menuFileName) != null;
}
return ChestCommands.getMenuManager().getMenuByFileName(menuFileName) != null;
}
@Override
public boolean openPluginMenu(Player player, String menuFileName) {
Preconditions.notNull(player, "player");
Preconditions.notNull(menuFileName, "menuFileName");
@Override
public boolean openPluginMenu(Player player, String menuFileName) {
Preconditions.notNull(player, "player");
Preconditions.notNull(menuFileName, "menuFileName");
InternalMenu menu = ChestCommands.getMenuManager().getMenuByFileName(menuFileName);
InternalMenu menu = ChestCommands.getMenuManager().getMenuByFileName(menuFileName);
if (menu != null) {
menu.open(player);
return true;
} else {
return false;
}
}
if (menu != null) {
menu.open(player);
return true;
} else {
return false;
}
}
@Override
public ConfigurableIcon createConfigurableIcon(Material material) {
return new APIConfigurableIcon(material);
}
@Override
public ConfigurableIcon createConfigurableIcon(Material material) {
return new APIConfigurableIcon(material);
}
@Override
public Menu createMenu(Plugin owner, String title, int rows) {
return new APIMenu(owner, title, rows);
}
@Override
public Menu createMenu(Plugin owner, String title, int rows) {
return new APIMenu(owner, title, rows);
}
@Override
public StaticIcon createStaticIcon(ItemStack itemStack) {
return new APIStaticIcon(itemStack);
}
@Override
public StaticIcon createStaticIcon(ItemStack itemStack) {
return new APIStaticIcon(itemStack);
}
@Override
public void registerPlaceholder(Plugin plugin, String identifier, PlaceholderReplacer placeholderReplacer) {
PlaceholderManager.registerPluginPlaceholder(plugin, identifier, placeholderReplacer);
}
@Override
public void registerPlaceholder(Plugin plugin, String identifier, PlaceholderReplacer placeholderReplacer) {
PlaceholderManager.registerPluginPlaceholder(plugin, identifier, placeholderReplacer);
}
}

View File

@ -7,14 +7,14 @@ package me.filoghost.chestcommands;
public class Permissions {
public static final String
public static final String
BASE_PREFIX = "chestcommands.",
COMMAND_PREFIX = BASE_PREFIX + "command.",
OPEN_MENU_PREFIX = BASE_PREFIX + "open.",
BASE_PREFIX = "chestcommands.",
COMMAND_PREFIX = BASE_PREFIX + "command.",
OPEN_MENU_PREFIX = BASE_PREFIX + "open.",
UPDATE_NOTIFICATIONS = BASE_PREFIX + "update",
SEE_ERRORS = BASE_PREFIX + "errors",
SIGN_CREATE = BASE_PREFIX + "sign";
UPDATE_NOTIFICATIONS = BASE_PREFIX + "update",
SEE_ERRORS = BASE_PREFIX + "errors",
SIGN_CREATE = BASE_PREFIX + "sign";
}

View File

@ -9,6 +9,6 @@ import org.bukkit.entity.Player;
public interface Action {
void execute(Player player);
void execute(Player player);
}

View File

@ -11,16 +11,16 @@ import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class BroadcastAction implements Action {
private final PlaceholderString message;
private final PlaceholderString message;
public BroadcastAction(String serializedAction) {
message = PlaceholderString.of(Colors.addColors(serializedAction));
}
public BroadcastAction(String serializedAction) {
message = PlaceholderString.of(Colors.addColors(serializedAction));
}
@Override
public void execute(Player player) {
Bukkit.broadcastMessage(message.getValue(player));
}
@Override
public void execute(Player player) {
Bukkit.broadcastMessage(message.getValue(player));
}
}

View File

@ -11,15 +11,15 @@ import org.bukkit.entity.Player;
public class ChangeServerAction implements Action {
private final PlaceholderString targetServer;
public ChangeServerAction(String serializedAction) {
targetServer = PlaceholderString.of(serializedAction);
}
private final PlaceholderString targetServer;
public ChangeServerAction(String serializedAction) {
targetServer = PlaceholderString.of(serializedAction);
}
@Override
public void execute(Player player) {
BungeeCordHook.connect(player, targetServer.getValue(player));
}
@Override
public void execute(Player player) {
BungeeCordHook.connect(player, targetServer.getValue(player));
}
}

View File

@ -11,15 +11,15 @@ import org.bukkit.entity.Player;
public class ConsoleCommandAction implements Action {
private final PlaceholderString command;
private final PlaceholderString command;
public ConsoleCommandAction(String serializedAction) {
command = PlaceholderString.of(serializedAction);
}
public ConsoleCommandAction(String serializedAction) {
command = PlaceholderString.of(serializedAction);
}
@Override
public void execute(Player player) {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command.getValue(player));
}
@Override
public void execute(Player player) {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command.getValue(player));
}
}

View File

@ -9,15 +9,15 @@ import org.bukkit.entity.Player;
public class DisabledAction implements Action {
private final String errorMessage;
private final String errorMessage;
public DisabledAction(String errorMessage) {
this.errorMessage = errorMessage;
}
public DisabledAction(String errorMessage) {
this.errorMessage = errorMessage;
}
@Override
public void execute(Player player) {
player.sendMessage(errorMessage);
}
@Override
public void execute(Player player) {
player.sendMessage(errorMessage);
}
}

View File

@ -16,35 +16,35 @@ import org.bukkit.entity.Player;
public class DragonBarAction implements Action {
private final PlaceholderString message;
private final int seconds;
private final PlaceholderString message;
private final int seconds;
public DragonBarAction(String serialiazedAction) throws ParseException {
String message;
public DragonBarAction(String serialiazedAction) throws ParseException {
String message;
String[] split = Strings.trimmedSplit(serialiazedAction, "\\|", 2); // Max of 2 pieces
if (split.length > 1) {
try {
seconds = NumberParser.getStrictlyPositiveInteger(split[0]);
message = split[1];
} catch (ParseException e) {
throw new ParseException(Errors.Parsing.invalidBossBarTime(split[0]), e);
}
} else {
seconds = 1;
message = serialiazedAction;
}
String[] split = Strings.trimmedSplit(serialiazedAction, "\\|", 2); // Max of 2 pieces
if (split.length > 1) {
try {
seconds = NumberParser.getStrictlyPositiveInteger(split[0]);
message = split[1];
} catch (ParseException e) {
throw new ParseException(Errors.Parsing.invalidBossBarTime(split[0]), e);
}
} else {
seconds = 1;
message = serialiazedAction;
}
this.message = PlaceholderString.of(Colors.addColors(message));
}
this.message = PlaceholderString.of(Colors.addColors(message));
}
@Override
public void execute(Player player) {
if (BarAPIHook.INSTANCE.isEnabled()) {
BarAPIHook.setMessage(player, message.getValue(player), seconds);
} else {
player.sendMessage(Errors.User.configurationError("BarAPI plugin not found"));
}
}
@Override
public void execute(Player player) {
if (BarAPIHook.INSTANCE.isEnabled()) {
BarAPIHook.setMessage(player, message.getValue(player), seconds);
} else {
player.sendMessage(Errors.User.configurationError("BarAPI plugin not found"));
}
}
}

View File

@ -12,17 +12,17 @@ import org.bukkit.inventory.ItemStack;
public class GiveItemAction implements Action {
private final ItemStack itemToGive;
private final ItemStack itemToGive;
public GiveItemAction(String serializedAction) throws ParseException {
ItemStackParser reader = new ItemStackParser(serializedAction, true);
reader.checkNotAir();
itemToGive = reader.createStack();
}
public GiveItemAction(String serializedAction) throws ParseException {
ItemStackParser reader = new ItemStackParser(serializedAction, true);
reader.checkNotAir();
itemToGive = reader.createStack();
}
@Override
public void execute(Player player) {
player.getInventory().addItem(itemToGive.clone());
}
@Override
public void execute(Player player) {
player.getInventory().addItem(itemToGive.clone());
}
}

View File

@ -13,19 +13,19 @@ import org.bukkit.entity.Player;
public class GiveMoneyAction implements Action {
private final double moneyToGive;
private final double moneyToGive;
public GiveMoneyAction(String serializedAction) throws ParseException {
moneyToGive = NumberParser.getStrictlyPositiveDouble(serializedAction);
}
public GiveMoneyAction(String serializedAction) throws ParseException {
moneyToGive = NumberParser.getStrictlyPositiveDouble(serializedAction);
}
@Override
public void execute(Player player) {
if (VaultEconomyHook.INSTANCE.isEnabled()) {
VaultEconomyHook.giveMoney(player, moneyToGive);
} else {
player.sendMessage(Errors.User.configurationError("Vault with a compatible economy plugin not found"));
}
}
@Override
public void execute(Player player) {
if (VaultEconomyHook.INSTANCE.isEnabled()) {
VaultEconomyHook.giveMoney(player, moneyToGive);
} else {
player.sendMessage(Errors.User.configurationError("Vault with a compatible economy plugin not found"));
}
}
}

View File

@ -10,21 +10,21 @@ import org.bukkit.entity.Player;
public class OpCommandAction implements Action {
private final PlaceholderString command;
private final PlaceholderString command;
public OpCommandAction(String serializedAction) {
command = PlaceholderString.of(serializedAction);
}
public OpCommandAction(String serializedAction) {
command = PlaceholderString.of(serializedAction);
}
@Override
public void execute(Player player) {
if (player.isOp()) {
player.chat("/" + command.getValue(player));
} else {
player.setOp(true);
player.chat("/" + command.getValue(player));
player.setOp(false);
}
}
@Override
public void execute(Player player) {
if (player.isOp()) {
player.chat("/" + command.getValue(player));
} else {
player.setOp(true);
player.chat("/" + command.getValue(player));
player.setOp(false);
}
}
}

View File

@ -14,29 +14,29 @@ import org.bukkit.entity.Player;
public class OpenMenuAction implements Action {
private final PlaceholderString targetMenu;
public OpenMenuAction(String serializedAction) {
targetMenu = PlaceholderString.of(serializedAction);
}
private final PlaceholderString targetMenu;
public OpenMenuAction(String serializedAction) {
targetMenu = PlaceholderString.of(serializedAction);
}
@Override
public void execute(final Player player) {
String menuName = targetMenu.getValue(player);
final InternalMenu menu = ChestCommands.getMenuManager().getMenuByFileName(menuName);
if (menu != null) {
/*
* Delay the task, since this action is executed in ClickInventoryEvent
* and opening another inventory in the same moment is not a good idea.
*/
Bukkit.getScheduler().runTask(ChestCommands.getPluginInstance(), () -> {
menu.openCheckingPermission(player);
});
@Override
public void execute(final Player player) {
String menuName = targetMenu.getValue(player);
final InternalMenu menu = ChestCommands.getMenuManager().getMenuByFileName(menuName);
if (menu != null) {
/*
* Delay the task, since this action is executed in ClickInventoryEvent
* and opening another inventory in the same moment is not a good idea.
*/
Bukkit.getScheduler().runTask(ChestCommands.getPluginInstance(), () -> {
menu.openCheckingPermission(player);
});
} else {
player.sendMessage(Errors.User.configurationError("couldn't find the menu \"" + menuName + "\""));
}
}
} else {
player.sendMessage(Errors.User.configurationError("couldn't find the menu \"" + menuName + "\""));
}
}
}

View File

@ -5,6 +5,7 @@
*/
package me.filoghost.chestcommands.action;
import java.util.Optional;
import me.filoghost.chestcommands.logging.Errors;
import me.filoghost.chestcommands.parsing.NumberParser;
import me.filoghost.chestcommands.parsing.ParseException;
@ -13,49 +14,47 @@ import me.filoghost.fcommons.collection.Registry;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import java.util.Optional;
public class PlaySoundAction implements Action {
private static final Registry<Sound> SOUNDS_REGISTRY = Registry.fromEnumValues(Sound.class);
private static final Registry<Sound> SOUNDS_REGISTRY = Registry.fromEnumValues(Sound.class);
private final Sound sound;
private final float pitch;
private final float volume;
private final Sound sound;
private final float pitch;
private final float volume;
public PlaySoundAction(String serializedAction) throws ParseException {
String[] split = Strings.trimmedSplit(serializedAction, ",", 3);
public PlaySoundAction(String serializedAction) throws ParseException {
String[] split = Strings.trimmedSplit(serializedAction, ",", 3);
Optional<Sound> sound = SOUNDS_REGISTRY.find(split[0]);
if (!sound.isPresent()) {
throw new ParseException(Errors.Parsing.unknownSound(split[0]));
}
this.sound = sound.get();
Optional<Sound> sound = SOUNDS_REGISTRY.find(split[0]);
if (!sound.isPresent()) {
throw new ParseException(Errors.Parsing.unknownSound(split[0]));
}
this.sound = sound.get();
if (split.length > 1) {
try {
pitch = NumberParser.getFloat(split[1]);
} catch (ParseException e) {
throw new ParseException(Errors.Parsing.invalidSoundPitch(split[1]), e);
}
} else {
pitch = 1.0f;
}
if (split.length > 1) {
try {
pitch = NumberParser.getFloat(split[1]);
} catch (ParseException e) {
throw new ParseException(Errors.Parsing.invalidSoundPitch(split[1]), e);
}
} else {
pitch = 1.0f;
}
if (split.length > 2) {
try {
volume = NumberParser.getFloat(split[2]);
} catch (ParseException e) {
throw new ParseException(Errors.Parsing.invalidSoundVolume(split[2]), e);
}
} else {
volume = 1.0f;
}
}
if (split.length > 2) {
try {
volume = NumberParser.getFloat(split[2]);
} catch (ParseException e) {
throw new ParseException(Errors.Parsing.invalidSoundVolume(split[2]), e);
}
} else {
volume = 1.0f;
}
}
@Override
public void execute(Player player) {
player.playSound(player.getLocation(), sound, volume, pitch);
}
@Override
public void execute(Player player) {
player.playSound(player.getLocation(), sound, volume, pitch);
}
}

View File

@ -9,16 +9,16 @@ import me.filoghost.chestcommands.placeholder.PlaceholderString;
import org.bukkit.entity.Player;
public class PlayerCommandAction implements Action {
private final PlaceholderString command;
public PlayerCommandAction(String serializedAction) {
command = PlaceholderString.of(serializedAction);
}
private final PlaceholderString command;
@Override
public void execute(Player player) {
player.chat('/' + command.getValue(player));
}
public PlayerCommandAction(String serializedAction) {
command = PlaceholderString.of(serializedAction);
}
@Override
public void execute(Player player) {
player.chat('/' + command.getValue(player));
}
}

View File

@ -10,16 +10,16 @@ import me.filoghost.fcommons.Colors;
import org.bukkit.entity.Player;
public class SendMessageAction implements Action {
private final PlaceholderString message;
private final PlaceholderString message;
public SendMessageAction(String serializedAction) {
message = PlaceholderString.of(Colors.addColors(serializedAction));
}
public SendMessageAction(String serializedAction) {
message = PlaceholderString.of(Colors.addColors(serializedAction));
}
@Override
public void execute(Player player) {
player.sendMessage(message.getValue(player));
}
@Override
public void execute(Player player) {
player.sendMessage(message.getValue(player));
}
}

View File

@ -5,6 +5,8 @@
*/
package me.filoghost.chestcommands.attribute;
import java.util.ArrayList;
import java.util.List;
import me.filoghost.chestcommands.action.Action;
import me.filoghost.chestcommands.action.DisabledAction;
import me.filoghost.chestcommands.icon.InternalConfigurableIcon;
@ -12,34 +14,31 @@ import me.filoghost.chestcommands.logging.Errors;
import me.filoghost.chestcommands.parsing.ActionParser;
import me.filoghost.chestcommands.parsing.ParseException;
import java.util.ArrayList;
import java.util.List;
public class ActionsAttribute implements IconAttribute {
private final List<Action> actions;
private final List<Action> actions;
public ActionsAttribute(List<String> serializedActions, AttributeErrorHandler errorHandler) {
actions = new ArrayList<>();
public ActionsAttribute(List<String> serializedActions, AttributeErrorHandler errorHandler) {
actions = new ArrayList<>();
for (String serializedAction : serializedActions) {
if (serializedAction == null || serializedAction.isEmpty()) {
continue; // Skip
}
for (String serializedAction : serializedActions) {
if (serializedAction == null || serializedAction.isEmpty()) {
continue; // Skip
}
try {
actions.add(ActionParser.parse(serializedAction));
} catch (ParseException e) {
actions.add(new DisabledAction(Errors.User.configurationError(
"an action linked to clicking this icon was not executed because it was not valid")));
errorHandler.onListElementError(serializedAction, e);
}
}
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setClickActions(actions);
}
try {
actions.add(ActionParser.parse(serializedAction));
} catch (ParseException e) {
actions.add(new DisabledAction(Errors.User.configurationError(
"an action linked to clicking this icon was not executed because it was not valid")));
errorHandler.onListElementError(serializedAction, e);
}
}
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setClickActions(actions);
}
}

View File

@ -11,18 +11,18 @@ import me.filoghost.chestcommands.parsing.ParseException;
public class AmountAttribute implements IconAttribute {
private final int amount;
private final int amount;
public AmountAttribute(int amount, AttributeErrorHandler errorHandler) throws ParseException {
if (amount < 0) {
throw new ParseException(Errors.Parsing.zeroOrPositive);
}
this.amount = amount;
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setAmount(amount);
}
public AmountAttribute(int amount, AttributeErrorHandler errorHandler) throws ParseException {
if (amount < 0) {
throw new ParseException(Errors.Parsing.zeroOrPositive);
}
this.amount = amount;
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setAmount(amount);
}
}

View File

@ -9,6 +9,6 @@ import me.filoghost.chestcommands.parsing.ParseException;
public interface AttributeErrorHandler {
void onListElementError(String listElement, ParseException e);
void onListElementError(String listElement, ParseException e);
}

View File

@ -12,15 +12,15 @@ import org.bukkit.DyeColor;
public class BannerColorAttribute implements IconAttribute {
private final DyeColor dyeColor;
private final DyeColor dyeColor;
public BannerColorAttribute(String serializedDyeColor, AttributeErrorHandler errorHandler) throws ParseException {
this.dyeColor = ItemMetaParser.parseDyeColor(serializedDyeColor);
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setBannerColor(dyeColor);
}
public BannerColorAttribute(String serializedDyeColor, AttributeErrorHandler errorHandler) throws ParseException {
this.dyeColor = ItemMetaParser.parseDyeColor(serializedDyeColor);
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setBannerColor(dyeColor);
}
}

View File

@ -5,39 +5,38 @@
*/
package me.filoghost.chestcommands.attribute;
import java.util.ArrayList;
import java.util.List;
import me.filoghost.chestcommands.icon.InternalConfigurableIcon;
import me.filoghost.chestcommands.parsing.ItemMetaParser;
import me.filoghost.chestcommands.parsing.ParseException;
import org.bukkit.block.banner.Pattern;
import java.util.ArrayList;
import java.util.List;
public class BannerPatternsAttribute implements IconAttribute {
private final List<Pattern> patterns;
private final List<Pattern> patterns;
public BannerPatternsAttribute(List<String> serializedPatterns, AttributeErrorHandler errorHandler) {
patterns = new ArrayList<>();
public BannerPatternsAttribute(List<String> serializedPatterns, AttributeErrorHandler errorHandler) {
patterns = new ArrayList<>();
for (String serializedPattern : serializedPatterns) {
if (serializedPattern == null || serializedPattern.isEmpty()) {
continue; // Skip
}
for (String serializedPattern : serializedPatterns) {
if (serializedPattern == null || serializedPattern.isEmpty()) {
continue; // Skip
}
try {
Pattern pattern = ItemMetaParser.parseBannerPattern(serializedPattern);
patterns.add(pattern);
} catch (ParseException e) {
errorHandler.onListElementError(serializedPattern, e);
}
}
try {
Pattern pattern = ItemMetaParser.parseBannerPattern(serializedPattern);
patterns.add(pattern);
} catch (ParseException e) {
errorHandler.onListElementError(serializedPattern, e);
}
}
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setBannerPatterns(patterns);
}
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setBannerPatterns(patterns);
}
}

View File

@ -9,15 +9,15 @@ import me.filoghost.chestcommands.icon.InternalConfigurableIcon;
public class ClickPermissionAttribute implements IconAttribute {
private final String clickPermission;
private final String clickPermission;
public ClickPermissionAttribute(String clickPermission, AttributeErrorHandler errorHandler) {
this.clickPermission = clickPermission;
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setClickPermission(clickPermission);
}
public ClickPermissionAttribute(String clickPermission, AttributeErrorHandler errorHandler) {
this.clickPermission = clickPermission;
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setClickPermission(clickPermission);
}
}

View File

@ -9,15 +9,15 @@ import me.filoghost.chestcommands.icon.InternalConfigurableIcon;
public class ClickPermissionMessageAttribute implements IconAttribute {
private final String clickPermissionMessage;
private final String clickPermissionMessage;
public ClickPermissionMessageAttribute(String clickPermissionMessage, AttributeErrorHandler errorHandler) {
this.clickPermissionMessage = clickPermissionMessage;
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setNoClickPermissionMessage(clickPermissionMessage);
}
public ClickPermissionMessageAttribute(String clickPermissionMessage, AttributeErrorHandler errorHandler) {
this.clickPermissionMessage = clickPermissionMessage;
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setNoClickPermissionMessage(clickPermissionMessage);
}
}

View File

@ -9,15 +9,15 @@ import me.filoghost.chestcommands.icon.InternalConfigurableIcon;
public class DurabilityAttribute implements IconAttribute {
private final short durability;
private final short durability;
public DurabilityAttribute(short durability, AttributeErrorHandler errorHandler) {
this.durability = durability;
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setDurability(durability);
}
public DurabilityAttribute(short durability, AttributeErrorHandler errorHandler) {
this.durability = durability;
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setDurability(durability);
}
}

View File

@ -5,39 +5,38 @@
*/
package me.filoghost.chestcommands.attribute;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import me.filoghost.chestcommands.icon.InternalConfigurableIcon;
import me.filoghost.chestcommands.parsing.EnchantmentParser;
import me.filoghost.chestcommands.parsing.ParseException;
import org.bukkit.enchantments.Enchantment;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class EnchantmentsAttribute implements IconAttribute {
private final Map<Enchantment, Integer> enchantments;
private final Map<Enchantment, Integer> enchantments;
public EnchantmentsAttribute(List<String> serializedEnchantments, AttributeErrorHandler errorHandler) {
enchantments = new HashMap<>();
public EnchantmentsAttribute(List<String> serializedEnchantments, AttributeErrorHandler errorHandler) {
enchantments = new HashMap<>();
for (String serializedEnchantment : serializedEnchantments) {
if (serializedEnchantment == null || serializedEnchantment.isEmpty()) {
continue; // Skip
}
for (String serializedEnchantment : serializedEnchantments) {
if (serializedEnchantment == null || serializedEnchantment.isEmpty()) {
continue; // Skip
}
try {
EnchantmentParser.EnchantmentDetails enchantment = EnchantmentParser.parseEnchantment(serializedEnchantment);
enchantments.put(enchantment.getEnchantment(), enchantment.getLevel());
} catch (ParseException e) {
errorHandler.onListElementError(serializedEnchantment, e);
}
}
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setEnchantments(enchantments);
}
try {
EnchantmentParser.EnchantmentDetails enchantment = EnchantmentParser.parseEnchantment(serializedEnchantment);
enchantments.put(enchantment.getEnchantment(), enchantment.getLevel());
} catch (ParseException e) {
errorHandler.onListElementError(serializedEnchantment, e);
}
}
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setEnchantments(enchantments);
}
}

View File

@ -11,18 +11,18 @@ import me.filoghost.chestcommands.parsing.ParseException;
public class ExpLevelsAttribute implements IconAttribute {
private final int expLevels;
private final int expLevels;
public ExpLevelsAttribute(int expLevels, AttributeErrorHandler errorHandler) throws ParseException {
if (expLevels < 0) {
throw new ParseException(Errors.Parsing.zeroOrPositive);
}
this.expLevels = expLevels;
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setRequiredExpLevel(expLevels);
}
public ExpLevelsAttribute(int expLevels, AttributeErrorHandler errorHandler) throws ParseException {
if (expLevels < 0) {
throw new ParseException(Errors.Parsing.zeroOrPositive);
}
this.expLevels = expLevels;
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setRequiredExpLevel(expLevels);
}
}

View File

@ -9,5 +9,5 @@ import me.filoghost.chestcommands.icon.InternalConfigurableIcon;
public interface IconAttribute {
void apply(InternalConfigurableIcon icon);
void apply(InternalConfigurableIcon icon);
}

View File

@ -10,19 +10,19 @@ import me.filoghost.chestcommands.icon.InternalConfigurableIcon;
public class KeepOpenAttribute implements IconAttribute {
private final ClickResult clickResult;
private final ClickResult clickResult;
public KeepOpenAttribute(boolean keepOpen, AttributeErrorHandler errorHandler) {
if (keepOpen) {
this.clickResult = ClickResult.KEEP_OPEN;
} else {
this.clickResult = ClickResult.CLOSE;
}
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setClickResult(clickResult);
}
public KeepOpenAttribute(boolean keepOpen, AttributeErrorHandler errorHandler) {
if (keepOpen) {
this.clickResult = ClickResult.KEEP_OPEN;
} else {
this.clickResult = ClickResult.CLOSE;
}
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setClickResult(clickResult);
}
}

View File

@ -12,15 +12,15 @@ import org.bukkit.Color;
public class LeatherColorAttribute implements IconAttribute {
private final Color color;
private final Color color;
public LeatherColorAttribute(String serializedColor, AttributeErrorHandler errorHandler) throws ParseException {
this.color = ItemMetaParser.parseRGBColor(serializedColor);
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setLeatherColor(color);
}
public LeatherColorAttribute(String serializedColor, AttributeErrorHandler errorHandler) throws ParseException {
this.color = ItemMetaParser.parseRGBColor(serializedColor);
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setLeatherColor(color);
}
}

View File

@ -5,34 +5,33 @@
*/
package me.filoghost.chestcommands.attribute;
import java.util.List;
import me.filoghost.chestcommands.config.Settings;
import me.filoghost.chestcommands.icon.InternalConfigurableIcon;
import me.filoghost.fcommons.Colors;
import me.filoghost.fcommons.collection.CollectionUtils;
import java.util.List;
public class LoreAttribute implements IconAttribute {
private final List<String> lore;
public LoreAttribute(List<String> lore, AttributeErrorHandler errorHandler) {
this.lore = colorLore(lore);
}
private final List<String> lore;
public LoreAttribute(List<String> lore, AttributeErrorHandler errorHandler) {
this.lore = colorLore(lore);
}
private List<String> colorLore(List<String> input) {
return CollectionUtils.transform(input, line -> {
if (!line.isEmpty()) {
return Settings.default_color__lore + Colors.addColors(line);
} else {
return line;
}
});
}
private List<String> colorLore(List<String> input) {
return CollectionUtils.transform(input, line -> {
if (!line.isEmpty()) {
return Settings.default_color__lore + Colors.addColors(line);
} else {
return line;
}
});
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setLore(lore);
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setLore(lore);
}
}

View File

@ -11,16 +11,16 @@ import me.filoghost.chestcommands.parsing.ParseException;
import org.bukkit.Material;
public class MaterialAttribute implements IconAttribute {
private final Material material;
public MaterialAttribute(String serializedMaterial, AttributeErrorHandler errorHandler) throws ParseException {
this.material = MaterialParser.parseMaterial(serializedMaterial);
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setMaterial(material);
}
private final Material material;
public MaterialAttribute(String serializedMaterial, AttributeErrorHandler errorHandler) throws ParseException {
this.material = MaterialParser.parseMaterial(serializedMaterial);
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setMaterial(material);
}
}

View File

@ -12,22 +12,22 @@ import me.filoghost.chestcommands.util.nbt.parser.MojangsonParser;
public class NBTDataAttribute implements IconAttribute {
private final String nbtData;
private final String nbtData;
public NBTDataAttribute(String nbtData, AttributeErrorHandler errorHandler) throws ParseException {
try {
// Check that NBT syntax is valid before applying it to the icon
MojangsonParser.parse(nbtData);
} catch (MojangsonParseException e) {
throw new ParseException(e.getMessage());
}
public NBTDataAttribute(String nbtData, AttributeErrorHandler errorHandler) throws ParseException {
try {
// Check that NBT syntax is valid before applying it to the icon
MojangsonParser.parse(nbtData);
} catch (MojangsonParseException e) {
throw new ParseException(e.getMessage());
}
this.nbtData = nbtData;
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setNBTData(nbtData);
}
this.nbtData = nbtData;
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setNBTData(nbtData);
}
}

View File

@ -11,23 +11,23 @@ import me.filoghost.fcommons.Colors;
public class NameAttribute implements IconAttribute {
private final String name;
private final String name;
public NameAttribute(String name, AttributeErrorHandler errorHandler) {
this.name = colorName(name);
}
public NameAttribute(String name, AttributeErrorHandler errorHandler) {
this.name = colorName(name);
}
private String colorName(String name) {
if (!name.isEmpty()) {
return Settings.default_color__name + Colors.addColors(name);
} else {
return name;
}
}
private String colorName(String name) {
if (!name.isEmpty()) {
return Settings.default_color__name + Colors.addColors(name);
} else {
return name;
}
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setName(name);
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setName(name);
}
}

View File

@ -8,19 +8,19 @@ package me.filoghost.chestcommands.attribute;
import me.filoghost.chestcommands.icon.InternalConfigurableIcon;
public class PositionAttribute implements IconAttribute {
private final int position;
private final int position;
public PositionAttribute(int position, AttributeErrorHandler errorHandler) {
this.position = position;
}
public int getPosition() {
return position;
}
public PositionAttribute(int position, AttributeErrorHandler errorHandler) {
this.position = position;
}
public int getPosition() {
return position;
}
@Override
public void apply(InternalConfigurableIcon icon) {
// Position has no effect on the icon itself
}
@Override
public void apply(InternalConfigurableIcon icon) {
// Position has no effect on the icon itself
}
}

View File

@ -11,18 +11,18 @@ import me.filoghost.chestcommands.parsing.ParseException;
public class PriceAttribute implements IconAttribute {
private final double price;
private final double price;
public PriceAttribute(double price, AttributeErrorHandler errorHandler) throws ParseException {
if (price < 0) {
throw new ParseException(Errors.Parsing.zeroOrPositive);
}
this.price = price;
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setRequiredMoney(price);
}
public PriceAttribute(double price, AttributeErrorHandler errorHandler) throws ParseException {
if (price < 0) {
throw new ParseException(Errors.Parsing.zeroOrPositive);
}
this.price = price;
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setRequiredMoney(price);
}
}

View File

@ -5,39 +5,38 @@
*/
package me.filoghost.chestcommands.attribute;
import java.util.ArrayList;
import java.util.List;
import me.filoghost.chestcommands.icon.InternalConfigurableIcon;
import me.filoghost.chestcommands.icon.requirement.item.RequiredItem;
import me.filoghost.chestcommands.parsing.ItemStackParser;
import me.filoghost.chestcommands.parsing.ParseException;
import java.util.ArrayList;
import java.util.List;
public class RequiredItemsAttribute implements IconAttribute {
private final List<RequiredItem> requiredItems;
private final List<RequiredItem> requiredItems;
public RequiredItemsAttribute(List<String> serializedRequiredItems, AttributeErrorHandler errorHandler) {
requiredItems = new ArrayList<>();
public RequiredItemsAttribute(List<String> serializedRequiredItems, AttributeErrorHandler errorHandler) {
requiredItems = new ArrayList<>();
for (String serializedItem : serializedRequiredItems) {
try {
ItemStackParser itemReader = new ItemStackParser(serializedItem, true);
itemReader.checkNotAir();
RequiredItem requiredItem = new RequiredItem(itemReader.getMaterial(), itemReader.getAmount());
if (itemReader.hasExplicitDurability()) {
requiredItem.setRestrictiveDurability(itemReader.getDurability());
}
requiredItems.add(requiredItem);
} catch (ParseException e) {
errorHandler.onListElementError(serializedItem, e);
}
}
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setRequiredItems(requiredItems);
}
for (String serializedItem : serializedRequiredItems) {
try {
ItemStackParser itemReader = new ItemStackParser(serializedItem, true);
itemReader.checkNotAir();
RequiredItem requiredItem = new RequiredItem(itemReader.getMaterial(), itemReader.getAmount());
if (itemReader.hasExplicitDurability()) {
requiredItem.setRestrictiveDurability(itemReader.getDurability());
}
requiredItems.add(requiredItem);
} catch (ParseException e) {
errorHandler.onListElementError(serializedItem, e);
}
}
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setRequiredItems(requiredItems);
}
}

View File

@ -9,15 +9,15 @@ import me.filoghost.chestcommands.icon.InternalConfigurableIcon;
public class SkullOwnerAttribute implements IconAttribute {
private final String skullOwner;
private final String skullOwner;
public SkullOwnerAttribute(String skullOwner, AttributeErrorHandler errorHandler) {
this.skullOwner = skullOwner;
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setSkullOwner(skullOwner);
}
public SkullOwnerAttribute(String skullOwner, AttributeErrorHandler errorHandler) {
this.skullOwner = skullOwner;
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setSkullOwner(skullOwner);
}
}

View File

@ -9,15 +9,15 @@ import me.filoghost.chestcommands.icon.InternalConfigurableIcon;
public class ViewPermissionAttribute implements IconAttribute {
private final String viewPermission;
private final String viewPermission;
public ViewPermissionAttribute(String viewPermission, AttributeErrorHandler errorHandler) {
this.viewPermission = viewPermission;
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setViewPermission(viewPermission);
}
public ViewPermissionAttribute(String viewPermission, AttributeErrorHandler errorHandler) {
this.viewPermission = viewPermission;
}
@Override
public void apply(InternalConfigurableIcon icon) {
icon.setViewPermission(viewPermission);
}
}

View File

@ -20,130 +20,130 @@ import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
public class CommandHandler extends CommandFramework {
private final MenuManager menuManager;
public CommandHandler(MenuManager menuManager, String label) {
super(label);
this.menuManager = menuManager;
}
private final MenuManager menuManager;
public CommandHandler(MenuManager menuManager, String label) {
super(label);
this.menuManager = menuManager;
}
@SuppressWarnings("deprecation")
@Override
public void execute(CommandSender sender, String label, String[] args) {
if (args.length == 0) {
// This info is accessible to anyone. Please don't remove it, remember that Chest Commands is developed for free
sender.sendMessage(ChestCommands.CHAT_PREFIX);
sender.sendMessage(ChatColor.GREEN + "Version: " + ChatColor.GRAY + ChestCommands.getPluginInstance().getDescription().getVersion());
sender.sendMessage(ChatColor.GREEN + "Developer: " + ChatColor.GRAY + "filoghost");
sender.sendMessage(ChatColor.GREEN + "Commands: " + ChatColor.GRAY + "/" + label + " help");
return;
}
@SuppressWarnings("deprecation")
@Override
public void execute(CommandSender sender, String label, String[] args) {
if (args.length == 0) {
// This info is accessible to anyone. Please don't remove it, remember that Chest Commands is developed for free
sender.sendMessage(ChestCommands.CHAT_PREFIX);
sender.sendMessage(ChatColor.GREEN + "Version: " + ChatColor.GRAY + ChestCommands.getPluginInstance().getDescription().getVersion());
sender.sendMessage(ChatColor.GREEN + "Developer: " + ChatColor.GRAY + "filoghost");
sender.sendMessage(ChatColor.GREEN + "Commands: " + ChatColor.GRAY + "/" + label + " help");
return;
}
if (args[0].equalsIgnoreCase("help")) {
checkCommandPermission(sender, "help");
sender.sendMessage(ChestCommands.CHAT_PREFIX + "Commands:");
sender.sendMessage(ChatColor.WHITE + "/" + label + " reload" + ChatColor.GRAY + " - Reloads the plugin.");
sender.sendMessage(ChatColor.WHITE + "/" + label + " errors" + ChatColor.GRAY + " - Displays the last load errors on the console.");
sender.sendMessage(ChatColor.WHITE + "/" + label + " list" + ChatColor.GRAY + " - Lists the loaded menus.");
sender.sendMessage(ChatColor.WHITE + "/" + label + " open <menu> [player]" + ChatColor.GRAY + " - Opens a menu for a player.");
return;
}
if (args[0].equalsIgnoreCase("help")) {
checkCommandPermission(sender, "help");
sender.sendMessage(ChestCommands.CHAT_PREFIX + "Commands:");
sender.sendMessage(ChatColor.WHITE + "/" + label + " reload" + ChatColor.GRAY + " - Reloads the plugin.");
sender.sendMessage(ChatColor.WHITE + "/" + label + " errors" + ChatColor.GRAY + " - Displays the last load errors on the console.");
sender.sendMessage(ChatColor.WHITE + "/" + label + " list" + ChatColor.GRAY + " - Lists the loaded menus.");
sender.sendMessage(ChatColor.WHITE + "/" + label + " open <menu> [player]" + ChatColor.GRAY + " - Opens a menu for a player.");
return;
}
if (args[0].equalsIgnoreCase("errors")) {
checkCommandPermission(sender, "errors");
ErrorCollector errorCollector = ChestCommands.getLastLoadErrors();
if (args[0].equalsIgnoreCase("errors")) {
checkCommandPermission(sender, "errors");
ErrorCollector errorCollector = ChestCommands.getLastLoadErrors();
if (errorCollector.hasErrors()) {
errorCollector.logToConsole();
sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Last time the plugin loaded, " + errorCollector.getErrorsCount() + " error(s) were found.");
if (!(sender instanceof ConsoleCommandSender)) {
sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Errors were printed on the console.");
}
} else {
sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.GREEN + "Last plugin load was successful, no errors logged.");
}
return;
}
if (errorCollector.hasErrors()) {
errorCollector.logToConsole();
sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Last time the plugin loaded, " + errorCollector.getErrorsCount() + " error(s) were found.");
if (!(sender instanceof ConsoleCommandSender)) {
sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Errors were printed on the console.");
}
} else {
sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.GREEN + "Last plugin load was successful, no errors logged.");
}
return;
}
if (args[0].equalsIgnoreCase("reload")) {
checkCommandPermission(sender, "reload");
if (args[0].equalsIgnoreCase("reload")) {
checkCommandPermission(sender, "reload");
ChestCommands.closeAllMenus();
ChestCommands.closeAllMenus();
ErrorCollector errorCollector = ChestCommands.load();
ErrorCollector errorCollector = ChestCommands.load();
if (!errorCollector.hasErrors()) {
sender.sendMessage(ChestCommands.CHAT_PREFIX + "Plugin reloaded.");
} else {
errorCollector.logToConsole();
sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Plugin reloaded with " + errorCollector.getErrorsCount() + " error(s).");
if (!(sender instanceof ConsoleCommandSender)) {
sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Please check the console.");
}
}
return;
}
if (!errorCollector.hasErrors()) {
sender.sendMessage(ChestCommands.CHAT_PREFIX + "Plugin reloaded.");
} else {
errorCollector.logToConsole();
sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Plugin reloaded with " + errorCollector.getErrorsCount() + " error(s).");
if (!(sender instanceof ConsoleCommandSender)) {
sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Please check the console.");
}
}
return;
}
if (args[0].equalsIgnoreCase("open")) {
checkCommandPermission(sender, "open");
CommandValidate.minLength(args, 2, "Usage: /" + label + " open <menu> [player]");
if (args[0].equalsIgnoreCase("open")) {
checkCommandPermission(sender, "open");
CommandValidate.minLength(args, 2, "Usage: /" + label + " open <menu> [player]");
Player target;
Player target;
if (sender instanceof Player) {
if (args.length > 2) {
checkCommandPermission(sender, "open.others");
target = Bukkit.getPlayerExact(args[2]);
} else {
target = (Player) sender;
}
} else {
CommandValidate.minLength(args, 3, "You must specify a player from the console.");
target = Bukkit.getPlayerExact(args[2]);
}
if (sender instanceof Player) {
if (args.length > 2) {
checkCommandPermission(sender, "open.others");
target = Bukkit.getPlayerExact(args[2]);
} else {
target = (Player) sender;
}
} else {
CommandValidate.minLength(args, 3, "You must specify a player from the console.");
target = Bukkit.getPlayerExact(args[2]);
}
CommandValidate.notNull(target, "That player is not online.");
CommandValidate.notNull(target, "That player is not online.");
String menuName = Utils.addYamlExtension(args[1]);
InternalMenu menu = menuManager.getMenuByFileName(menuName);
CommandValidate.notNull(menu, "The menu \"" + menuName + "\" was not found.");
String menuName = Utils.addYamlExtension(args[1]);
InternalMenu menu = menuManager.getMenuByFileName(menuName);
CommandValidate.notNull(menu, "The menu \"" + menuName + "\" was not found.");
if (!sender.hasPermission(menu.getOpenPermission())) {
menu.sendNoOpenPermissionMessage(sender);
return;
}
if (!sender.hasPermission(menu.getOpenPermission())) {
menu.sendNoOpenPermissionMessage(sender);
return;
}
if (sender.getName().equalsIgnoreCase(target.getName())) {
sender.sendMessage(ChatColor.GREEN + "Opening the menu " + menuName + ".");
} else {
sender.sendMessage(ChatColor.GREEN + "Opening the menu " + menuName + " to " + target.getName() + ".");
}
if (sender.getName().equalsIgnoreCase(target.getName())) {
sender.sendMessage(ChatColor.GREEN + "Opening the menu " + menuName + ".");
} else {
sender.sendMessage(ChatColor.GREEN + "Opening the menu " + menuName + " to " + target.getName() + ".");
}
menu.open(target);
return;
}
menu.open(target);
return;
}
if (args[0].equalsIgnoreCase("list")) {
checkCommandPermission(sender, "list");
sender.sendMessage(ChestCommands.CHAT_PREFIX + "Loaded menus:");
for (String file : menuManager.getMenuFileNames()) {
sender.sendMessage(ChatColor.GRAY + "- " + ChatColor.WHITE + file);
}
if (args[0].equalsIgnoreCase("list")) {
checkCommandPermission(sender, "list");
sender.sendMessage(ChestCommands.CHAT_PREFIX + "Loaded menus:");
for (String file : menuManager.getMenuFileNames()) {
sender.sendMessage(ChatColor.GRAY + "- " + ChatColor.WHITE + file);
}
return;
}
return;
}
sender.sendMessage(ChatColor.RED + "Unknown sub-command \"" + args[0] + "\".");
}
sender.sendMessage(ChatColor.RED + "Unknown sub-command \"" + args[0] + "\".");
}
private void checkCommandPermission(CommandSender sender, String commandPermission) {
CommandValidate.isTrue(sender.hasPermission(Permissions.COMMAND_PREFIX + commandPermission), "You don't have permission.");
}
private void checkCommandPermission(CommandSender sender, String commandPermission) {
CommandValidate.isTrue(sender.hasPermission(Permissions.COMMAND_PREFIX + commandPermission), "You don't have permission.");
}
}

View File

@ -5,6 +5,15 @@
*/
package me.filoghost.chestcommands.config;
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import me.filoghost.chestcommands.logging.Errors;
import me.filoghost.chestcommands.parsing.menu.LoadedMenu;
import me.filoghost.chestcommands.parsing.menu.MenuParser;
@ -16,110 +25,100 @@ import me.filoghost.fcommons.config.exception.ConfigException;
import me.filoghost.fcommons.config.mapped.MappedConfigLoader;
import me.filoghost.fcommons.logging.ErrorCollector;
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ConfigManager extends BaseConfigManager {
private final MappedConfigLoader<Settings> settingsConfigLoader;
private final ConfigLoader placeholdersConfigLoader;
private final MappedConfigLoader<Lang> langConfigLoader;
private final MappedConfigLoader<Settings> settingsConfigLoader;
private final ConfigLoader placeholdersConfigLoader;
private final MappedConfigLoader<Lang> langConfigLoader;
public ConfigManager(Path rootDataFolder) {
super(rootDataFolder);
public ConfigManager(Path rootDataFolder) {
super(rootDataFolder);
settingsConfigLoader = getMappedConfigLoader("config.yml", Settings::new);
placeholdersConfigLoader = getConfigLoader("custom-placeholders.yml");
langConfigLoader = getMappedConfigLoader("lang.yml", Lang::new);
}
settingsConfigLoader = getMappedConfigLoader("config.yml", Settings::new);
placeholdersConfigLoader = getConfigLoader("custom-placeholders.yml");
langConfigLoader = getMappedConfigLoader("lang.yml", Lang::new);
}
public void tryLoadSettings(ErrorCollector errorCollector) {
try {
settingsConfigLoader.init();
} catch (ConfigException e) {
logConfigInitException(errorCollector, settingsConfigLoader.getFile(), e);
}
}
public void tryLoadSettings(ErrorCollector errorCollector) {
try {
settingsConfigLoader.init();
} catch (ConfigException e) {
logConfigInitException(errorCollector, settingsConfigLoader.getFile(), e);
}
}
public void tryLoadLang(ErrorCollector errorCollector) {
try {
langConfigLoader.init();
} catch (ConfigException e) {
logConfigInitException(errorCollector, langConfigLoader.getFile(), e);
}
}
public void tryLoadLang(ErrorCollector errorCollector) {
try {
langConfigLoader.init();
} catch (ConfigException e) {
logConfigInitException(errorCollector, langConfigLoader.getFile(), e);
}
}
public CustomPlaceholders tryLoadCustomPlaceholders(ErrorCollector errorCollector) {
CustomPlaceholders placeholders = new CustomPlaceholders();
public CustomPlaceholders tryLoadCustomPlaceholders(ErrorCollector errorCollector) {
CustomPlaceholders placeholders = new CustomPlaceholders();
try {
Config placeholdersConfig = placeholdersConfigLoader.init();
placeholders.load(placeholdersConfig, errorCollector);
} catch (ConfigException t) {
logConfigInitException(errorCollector, placeholdersConfigLoader.getFile(), t);
}
try {
Config placeholdersConfig = placeholdersConfigLoader.init();
placeholders.load(placeholdersConfig, errorCollector);
} catch (ConfigException t) {
logConfigInitException(errorCollector, placeholdersConfigLoader.getFile(), t);
}
return placeholders;
}
return placeholders;
}
public void tryCreateDefault(ErrorCollector errorCollector, ConfigLoader configLoader) {
try {
configLoader.createDefault();
} catch (ConfigException e) {
logConfigInitException(errorCollector, configLoader.getFile(), e);
}
}
public void tryCreateDefault(ErrorCollector errorCollector, ConfigLoader configLoader) {
try {
configLoader.createDefault();
} catch (ConfigException e) {
logConfigInitException(errorCollector, configLoader.getFile(), e);
}
}
public Path getMenusFolder() {
return rootDataFolder.resolve("menu");
}
public Path getMenusFolder() {
return rootDataFolder.resolve("menu");
}
public List<Path> getMenuFiles() throws IOException {
Preconditions.checkState(Files.isDirectory(getMenusFolder()), "menus folder doesn't exist");
public List<Path> getMenuFiles() throws IOException {
Preconditions.checkState(Files.isDirectory(getMenusFolder()), "menus folder doesn't exist");
try (Stream<Path> paths = Files.walk(getMenusFolder(), FileVisitOption.FOLLOW_LINKS)) {
return paths.filter(this::isYamlFile).collect(Collectors.toList());
}
}
try (Stream<Path> paths = Files.walk(getMenusFolder(), FileVisitOption.FOLLOW_LINKS)) {
return paths.filter(this::isYamlFile).collect(Collectors.toList());
}
}
private void logConfigInitException(ErrorCollector errorCollector, Path file, ConfigException e) {
errorCollector.add(e, Errors.Config.initException(file));
}
private void logConfigInitException(ErrorCollector errorCollector, Path file, ConfigException e) {
errorCollector.add(e, Errors.Config.initException(file));
}
public List<LoadedMenu> tryLoadMenus(ErrorCollector errorCollector) {
List<LoadedMenu> loadedMenus = new ArrayList<>();
List<Path> menuFiles;
public List<LoadedMenu> tryLoadMenus(ErrorCollector errorCollector) {
List<LoadedMenu> loadedMenus = new ArrayList<>();
List<Path> menuFiles;
try {
menuFiles = getMenuFiles();
} catch (IOException e) {
errorCollector.add(e, Errors.Config.menuListIOException(getMenusFolder()));
return Collections.emptyList();
}
try {
menuFiles = getMenuFiles();
} catch (IOException e) {
errorCollector.add(e, Errors.Config.menuListIOException(getMenusFolder()));
return Collections.emptyList();
}
for (Path menuFile : menuFiles) {
ConfigLoader menuConfigLoader = new ConfigLoader(rootDataFolder, menuFile);
for (Path menuFile : menuFiles) {
ConfigLoader menuConfigLoader = new ConfigLoader(rootDataFolder, menuFile);
try {
Config menuConfig = menuConfigLoader.load();
loadedMenus.add(MenuParser.loadMenu(menuConfig, errorCollector));
} catch (ConfigException e) {
logConfigInitException(errorCollector, menuConfigLoader.getFile(), e);
}
}
try {
Config menuConfig = menuConfigLoader.load();
loadedMenus.add(MenuParser.loadMenu(menuConfig, errorCollector));
} catch (ConfigException e) {
logConfigInitException(errorCollector, menuConfigLoader.getFile(), e);
}
}
return loadedMenus;
}
return loadedMenus;
}
private boolean isYamlFile(Path path) {
return Files.isRegularFile(path) && path.getFileName().toString().toLowerCase().endsWith(".yml");
}
private boolean isYamlFile(Path path) {
return Files.isRegularFile(path) && path.getFileName().toString().toLowerCase().endsWith(".yml");
}
}

View File

@ -5,6 +5,8 @@
*/
package me.filoghost.chestcommands.config;
import java.util.ArrayList;
import java.util.List;
import me.filoghost.chestcommands.logging.Errors;
import me.filoghost.chestcommands.placeholder.StaticPlaceholder;
import me.filoghost.fcommons.Colors;
@ -12,43 +14,40 @@ import me.filoghost.fcommons.config.Config;
import me.filoghost.fcommons.config.ConfigSection;
import me.filoghost.fcommons.logging.ErrorCollector;
import java.util.ArrayList;
import java.util.List;
public class CustomPlaceholders {
private final List<StaticPlaceholder> placeholders = new ArrayList<>();
private final List<StaticPlaceholder> placeholders = new ArrayList<>();
public void load(Config config, ErrorCollector errorCollector) {
placeholders.clear();
public void load(Config config, ErrorCollector errorCollector) {
placeholders.clear();
ConfigSection placeholdersSection = config.getConfigSection("placeholders");
if (placeholdersSection == null) {
return;
}
ConfigSection placeholdersSection = config.getConfigSection("placeholders");
if (placeholdersSection == null) {
return;
}
for (String placeholder : placeholdersSection.getKeys()) {
String replacement = Colors.addColors(placeholdersSection.getString(placeholder));
if (replacement == null) {
return;
}
for (String placeholder : placeholdersSection.getKeys()) {
String replacement = Colors.addColors(placeholdersSection.getString(placeholder));
if (replacement == null) {
return;
}
if (placeholder.length() == 0) {
errorCollector.add(Errors.Config.emptyPlaceholder(config.getSourceFile()));
continue;
}
if (placeholder.length() == 0) {
errorCollector.add(Errors.Config.emptyPlaceholder(config.getSourceFile()));
continue;
}
if (placeholder.length() > 100) {
errorCollector.add(Errors.Config.tooLongPlaceholder(config.getSourceFile(), placeholder));
continue;
}
if (placeholder.length() > 100) {
errorCollector.add(Errors.Config.tooLongPlaceholder(config.getSourceFile(), placeholder));
continue;
}
placeholders.add(new StaticPlaceholder(placeholder, replacement));
}
}
placeholders.add(new StaticPlaceholder(placeholder, replacement));
}
}
public List<StaticPlaceholder> getPlaceholders() {
return placeholders;
}
public List<StaticPlaceholder> getPlaceholders() {
return placeholders;
}
}

View File

@ -14,12 +14,12 @@ import me.filoghost.fcommons.config.mapped.modifier.ChatColors;
@IncludeStatic
public class Lang extends MappedConfig {
public static String no_open_permission = "&cYou don't have permission &e{permission} &cto use this menu.";
public static String default_no_icon_permission = "&cYou don't have permission for this icon.";
public static String no_required_item = "&cYou must have &e{amount}x {material} &c(durability: {durability}) for this.";
public static String no_money = "&cYou need {money}$ for this.";
public static String no_exp = "&cYou need {levels} XP levels for this.";
public static String menu_not_found = "&cMenu not found! " + Errors.User.notifyStaffRequest;
public static String any = "any"; // Used in no_required_item when durability is not restrictive
public static String no_open_permission = "&cYou don't have permission &e{permission} &cto use this menu.";
public static String default_no_icon_permission = "&cYou don't have permission for this icon.";
public static String no_required_item = "&cYou must have &e{amount}x {material} &c(durability: {durability}) for this.";
public static String no_money = "&cYou need {money}$ for this.";
public static String no_exp = "&cYou need {levels} XP levels for this.";
public static String menu_not_found = "&cMenu not found! " + Errors.User.notifyStaffRequest;
public static String any = "any"; // Used in no_required_item when durability is not restrictive
}

View File

@ -13,15 +13,15 @@ import me.filoghost.fcommons.config.mapped.modifier.ChatColors;
@IncludeStatic
public class Settings extends MappedConfig {
public static String default_color__name = "&f";
public static String default_color__lore = "&7";
public static boolean update_notifications = true;
public static int anti_click_spam_delay = 200;
public static String default_color__name = "&f";
public static String default_color__lore = "&7";
public static boolean update_notifications = true;
public static int anti_click_spam_delay = 200;
public Settings() {
setHeader(
"ChestCommands main configuration file.",
"Documentation: https://filoghost.me/docs/chest-commands");
}
public Settings() {
setHeader(
"ChestCommands main configuration file.",
"Documentation: https://filoghost.me/docs/chest-commands");
}
}

View File

@ -11,25 +11,25 @@ import org.bukkit.entity.Player;
public enum BarAPIHook implements PluginHook {
INSTANCE;
private boolean enabled;
INSTANCE;
@Override
public void setup() {
enabled = Bukkit.getPluginManager().getPlugin("BarAPI") != null;
}
@Override
public boolean isEnabled() {
return enabled;
}
@SuppressWarnings("deprecation")
public static void setMessage(Player player, String message, int seconds) {
INSTANCE.checkEnabledState();
BarAPI.setMessage(player, message, seconds);
}
private boolean enabled;
@Override
public void setup() {
enabled = Bukkit.getPluginManager().getPlugin("BarAPI") != null;
}
@Override
public boolean isEnabled() {
return enabled;
}
@SuppressWarnings("deprecation")
public static void setMessage(Player player, String message, int seconds) {
INSTANCE.checkEnabledState();
BarAPI.setMessage(player, message, seconds);
}
}

View File

@ -5,50 +5,49 @@
*/
package me.filoghost.chestcommands.hook;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import me.filoghost.chestcommands.ChestCommands;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public enum BungeeCordHook implements PluginHook {
INSTANCE;
@Override
public void setup() {
if (!Bukkit.getMessenger().isOutgoingChannelRegistered(ChestCommands.getPluginInstance(), "BungeeCord")) {
Bukkit.getMessenger().registerOutgoingPluginChannel(ChestCommands.getPluginInstance(), "BungeeCord");
}
}
INSTANCE;
@Override
public boolean isEnabled() {
return true;
}
public static void connect(Player player, String server) {
INSTANCE.checkEnabledState();
if (server.length() == 0) {
player.sendMessage(ChatColor.RED + "Target server was an empty string, cannot connect to it.");
return;
}
@Override
public void setup() {
if (!Bukkit.getMessenger().isOutgoingChannelRegistered(ChestCommands.getPluginInstance(), "BungeeCord")) {
Bukkit.getMessenger().registerOutgoingPluginChannel(ChestCommands.getPluginInstance(), "BungeeCord");
}
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
@Override
public boolean isEnabled() {
return true;
}
try {
dataOutputStream.writeUTF("Connect");
dataOutputStream.writeUTF(server); // Target Server
} catch (IOException ex) {
throw new AssertionError();
}
public static void connect(Player player, String server) {
INSTANCE.checkEnabledState();
player.sendPluginMessage(ChestCommands.getPluginInstance(), "BungeeCord", byteArrayOutputStream.toByteArray());
}
if (server.length() == 0) {
player.sendMessage(ChatColor.RED + "Target server was an empty string, cannot connect to it.");
return;
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
try {
dataOutputStream.writeUTF("Connect");
dataOutputStream.writeUTF(server); // Target Server
} catch (IOException ex) {
throw new AssertionError();
}
player.sendPluginMessage(ChestCommands.getPluginInstance(), "BungeeCord", byteArrayOutputStream.toByteArray());
}
}

View File

@ -11,30 +11,30 @@ import org.bukkit.entity.Player;
public enum PlaceholderAPIHook implements PluginHook {
INSTANCE;
private boolean enabled;
INSTANCE;
@Override
public void setup() {
enabled = Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null;
}
private boolean enabled;
@Override
public boolean isEnabled() {
return enabled;
}
@Override
public void setup() {
enabled = Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null;
}
public static boolean hasPlaceholders(String message) {
INSTANCE.checkEnabledState();
return PlaceholderAPI.containsPlaceholders(message);
}
@Override
public boolean isEnabled() {
return enabled;
}
public static String setPlaceholders(String message, Player viewer) {
INSTANCE.checkEnabledState();
public static boolean hasPlaceholders(String message) {
INSTANCE.checkEnabledState();
return PlaceholderAPI.setPlaceholders(viewer, message);
}
return PlaceholderAPI.containsPlaceholders(message);
}
public static String setPlaceholders(String message, Player viewer) {
INSTANCE.checkEnabledState();
return PlaceholderAPI.setPlaceholders(viewer, message);
}
}

View File

@ -9,13 +9,13 @@ import me.filoghost.fcommons.Preconditions;
public interface PluginHook {
void setup();
boolean isEnabled();
default void checkEnabledState() {
Preconditions.checkState(isEnabled(), "Plugin hook " + getClass().getSimpleName() + " is not enabled");
}
void setup();
boolean isEnabled();
default void checkEnabledState() {
Preconditions.checkState(isEnabled(), "Plugin hook " + getClass().getSimpleName() + " is not enabled");
}
}

View File

@ -14,72 +14,72 @@ import org.bukkit.plugin.RegisteredServiceProvider;
public enum VaultEconomyHook implements PluginHook {
INSTANCE;
private Economy economy;
INSTANCE;
private Economy economy;
@Override
public void setup() {
economy = null;
if (Bukkit.getPluginManager().getPlugin("Vault") == null) {
return;
}
RegisteredServiceProvider<Economy> economyServiceProvider = Bukkit.getServicesManager().getRegistration(Economy.class);
if (economyServiceProvider == null) {
return;
}
economy = economyServiceProvider.getProvider();
}
@Override
public void setup() {
economy = null;
if (Bukkit.getPluginManager().getPlugin("Vault") == null) {
return;
}
RegisteredServiceProvider<Economy> economyServiceProvider = Bukkit.getServicesManager().getRegistration(Economy.class);
if (economyServiceProvider == null) {
return;
}
economy = economyServiceProvider.getProvider();
}
@Override
public boolean isEnabled() {
return economy != null;
}
@Override
public boolean isEnabled() {
return economy != null;
}
public static double getMoney(Player player) {
INSTANCE.checkEnabledState();
return INSTANCE.economy.getBalance(player, player.getWorld().getName());
}
public static double getMoney(Player player) {
INSTANCE.checkEnabledState();
return INSTANCE.economy.getBalance(player, player.getWorld().getName());
}
public static boolean hasMoney(Player player, double minimum) {
INSTANCE.checkEnabledState();
checkPositiveAmount(minimum);
public static boolean hasMoney(Player player, double minimum) {
INSTANCE.checkEnabledState();
checkPositiveAmount(minimum);
double balance = INSTANCE.economy.getBalance(player, player.getWorld().getName());
return balance >= minimum;
}
double balance = INSTANCE.economy.getBalance(player, player.getWorld().getName());
return balance >= minimum;
}
/**
* @return true if the operation was successful.
*/
public static boolean takeMoney(Player player, double amount) {
INSTANCE.checkEnabledState();
checkPositiveAmount(amount);
/**
* @return true if the operation was successful.
*/
public static boolean takeMoney(Player player, double amount) {
INSTANCE.checkEnabledState();
checkPositiveAmount(amount);
EconomyResponse response = INSTANCE.economy.withdrawPlayer(player, player.getWorld().getName(), amount);
return response.transactionSuccess();
}
EconomyResponse response = INSTANCE.economy.withdrawPlayer(player, player.getWorld().getName(), amount);
return response.transactionSuccess();
}
public static boolean giveMoney(Player player, double amount) {
INSTANCE.checkEnabledState();
checkPositiveAmount(amount);
public static boolean giveMoney(Player player, double amount) {
INSTANCE.checkEnabledState();
checkPositiveAmount(amount);
EconomyResponse response = INSTANCE.economy.depositPlayer(player, player.getWorld().getName(), amount);
return response.transactionSuccess();
}
private static void checkPositiveAmount(double amount) {
Preconditions.checkArgument(amount >= 0.0, "amount cannot be negative");
}
EconomyResponse response = INSTANCE.economy.depositPlayer(player, player.getWorld().getName(), amount);
return response.transactionSuccess();
}
private static void checkPositiveAmount(double amount) {
Preconditions.checkArgument(amount >= 0.0, "amount cannot be negative");
}
public static String formatMoney(double amount) {
if (INSTANCE.economy != null) {
return INSTANCE.economy.format(amount);
} else {
return Double.toString(amount);
}
}
public static String formatMoney(double amount) {
if (INSTANCE.economy != null) {
return INSTANCE.economy.format(amount);
} else {
return Double.toString(amount);
}
}
}

View File

@ -11,20 +11,20 @@ import org.bukkit.Material;
public class APIConfigurableIcon extends BaseConfigurableIcon implements ConfigurableIcon {
private ClickHandler clickHandler;
private ClickHandler clickHandler;
public APIConfigurableIcon(Material material) {
super(material);
}
public APIConfigurableIcon(Material material) {
super(material);
}
@Override
public void setClickHandler(ClickHandler clickHandler) {
this.clickHandler = clickHandler;
}
@Override
public void setClickHandler(ClickHandler clickHandler) {
this.clickHandler = clickHandler;
}
@Override
public ClickHandler getClickHandler() {
return clickHandler;
}
@Override
public ClickHandler getClickHandler() {
return clickHandler;
}
}

View File

@ -13,38 +13,38 @@ import org.bukkit.inventory.ItemStack;
public class APIStaticIcon implements StaticIcon {
private ItemStack itemStack;
private ClickHandler clickHandler;
private ItemStack itemStack;
private ClickHandler clickHandler;
public APIStaticIcon(ItemStack itemStack) {
Preconditions.notNull(itemStack, "itemStack");
this.itemStack = itemStack;
}
public APIStaticIcon(ItemStack itemStack) {
Preconditions.notNull(itemStack, "itemStack");
this.itemStack = itemStack;
}
@Override
public ItemStack getItemStack() {
return itemStack;
}
@Override
public ItemStack getItemStack() {
return itemStack;
}
@Override
public void setItemStack(ItemStack itemStack) {
Preconditions.notNull(itemStack, "itemStack");
this.itemStack = itemStack;
}
@Override
public void setItemStack(ItemStack itemStack) {
Preconditions.notNull(itemStack, "itemStack");
this.itemStack = itemStack;
}
@Override
public ClickHandler getClickHandler() {
return clickHandler;
}
@Override
public ClickHandler getClickHandler() {
return clickHandler;
}
@Override
public void setClickHandler(ClickHandler clickHandler) {
this.clickHandler = clickHandler;
}
@Override
public void setClickHandler(ClickHandler clickHandler) {
this.clickHandler = clickHandler;
}
@Override
public ItemStack render(Player viewer) {
return itemStack;
}
@Override
public ItemStack render(Player viewer) {
return itemStack;
}
}

View File

@ -5,6 +5,11 @@
*/
package me.filoghost.chestcommands.icon;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import me.filoghost.chestcommands.api.Icon;
import me.filoghost.chestcommands.placeholder.PlaceholderString;
import me.filoghost.chestcommands.placeholder.PlaceholderStringList;
@ -28,298 +33,292 @@ import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.inventory.meta.SkullMeta;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class BaseConfigurableIcon implements Icon {
private Material material;
private int amount;
private short durability;
private Material material;
private int amount;
private short durability;
private String nbtData;
private PlaceholderString name;
private PlaceholderStringList lore;
private Map<Enchantment, Integer> enchantments;
private Color leatherColor;
private PlaceholderString skullOwner;
private DyeColor bannerColor;
private List<Pattern> bannerPatterns;
private boolean placeholdersEnabled;
protected ItemStack cachedRendering; // Cache the rendered item when possible and if state hasn't changed
private String nbtData;
private PlaceholderString name;
private PlaceholderStringList lore;
private Map<Enchantment, Integer> enchantments;
private Color leatherColor;
private PlaceholderString skullOwner;
private DyeColor bannerColor;
private List<Pattern> bannerPatterns;
private boolean placeholdersEnabled;
public BaseConfigurableIcon(Material material) {
this.material = material;
this.amount = 1;
}
protected ItemStack cachedRendering; // Cache the rendered item when possible and if state hasn't changed
protected boolean shouldCacheRendering() {
if (placeholdersEnabled && hasDynamicPlaceholders()) {
return false;
} else {
return true;
}
}
public BaseConfigurableIcon(Material material) {
this.material = material;
this.amount = 1;
}
private boolean hasDynamicPlaceholders() {
return (name != null && name.hasDynamicPlaceholders())
|| (lore != null && lore.hasDynamicPlaceholders())
|| (skullOwner != null && skullOwner.hasDynamicPlaceholders());
}
protected boolean shouldCacheRendering() {
if (placeholdersEnabled && hasDynamicPlaceholders()) {
return false;
} else {
return true;
}
}
public void setMaterial(Material material) {
this.material = material;
cachedRendering = null;
}
private boolean hasDynamicPlaceholders() {
return (name != null && name.hasDynamicPlaceholders())
|| (lore != null && lore.hasDynamicPlaceholders())
|| (skullOwner != null && skullOwner.hasDynamicPlaceholders());
}
public Material getMaterial() {
return material;
}
public void setMaterial(Material material) {
this.material = material;
cachedRendering = null;
}
public void setAmount(int amount) {
Preconditions.checkArgument(amount > 0, "amount must be greater than 0");
this.amount = Math.min(amount, 127);
cachedRendering = null;
}
public Material getMaterial() {
return material;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
Preconditions.checkArgument(amount > 0, "amount must be greater than 0");
this.amount = Math.min(amount, 127);
cachedRendering = null;
}
public void setDurability(short durability) {
Preconditions.checkArgument(durability >= 0, "durability must be 0 or greater");
this.durability = durability;
cachedRendering = null;
}
public int getAmount() {
return amount;
}
public short getDurability() {
return durability;
}
public void setDurability(short durability) {
Preconditions.checkArgument(durability >= 0, "durability must be 0 or greater");
this.durability = durability;
cachedRendering = null;
}
public void setNBTData(String nbtData) {
if (nbtData != null) {
try {
MojangsonParser.parse(nbtData);
} catch (MojangsonParseException e) {
throw new IllegalArgumentException("invalid nbtData", e);
}
}
this.nbtData = nbtData;
cachedRendering = null;
}
public short getDurability() {
return durability;
}
public String getNBTData() {
return nbtData;
}
public void setNBTData(String nbtData) {
if (nbtData != null) {
try {
MojangsonParser.parse(nbtData);
} catch (MojangsonParseException e) {
throw new IllegalArgumentException("invalid nbtData", e);
}
}
this.nbtData = nbtData;
cachedRendering = null;
}
public void setName(String name) {
this.name = PlaceholderString.of(name);
cachedRendering = null;
}
public String getNBTData() {
return nbtData;
}
public String getName() {
if (name != null) {
return name.getOriginalValue();
} else {
return null;
}
}
public void setName(String name) {
this.name = PlaceholderString.of(name);
cachedRendering = null;
}
public void setLore(String... lore) {
if (lore != null) {
setLore(Arrays.asList(lore));
}
}
public String getName() {
if (name != null) {
return name.getOriginalValue();
} else {
return null;
}
}
public void setLore(List<String> lore) {
if (lore != null) {
this.lore = new PlaceholderStringList(CollectionUtils.replaceNulls(lore, ""));
} else {
this.lore = null;
}
cachedRendering = null;
}
public void setLore(String... lore) {
if (lore != null) {
setLore(Arrays.asList(lore));
}
}
public List<String> getLore() {
if (lore != null) {
return new ArrayList<>(lore.getOriginalValue());
} else {
return null;
}
}
public void setLore(List<String> lore) {
if (lore != null) {
this.lore = new PlaceholderStringList(CollectionUtils.replaceNulls(lore, ""));
} else {
this.lore = null;
}
cachedRendering = null;
}
public void setEnchantments(Map<Enchantment, Integer> enchantments) {
this.enchantments = CollectionUtils.copy(enchantments);
cachedRendering = null;
}
public List<String> getLore() {
if (lore != null) {
return new ArrayList<>(lore.getOriginalValue());
} else {
return null;
}
}
public Map<Enchantment, Integer> getEnchantments() {
return CollectionUtils.copy(enchantments);
}
public void setEnchantments(Map<Enchantment, Integer> enchantments) {
this.enchantments = CollectionUtils.copy(enchantments);
cachedRendering = null;
}
public void addEnchantment(Enchantment enchantment) {
addEnchantment(enchantment, 1);
}
public Map<Enchantment, Integer> getEnchantments() {
return CollectionUtils.copy(enchantments);
}
public void addEnchantment(Enchantment enchantment, Integer level) {
if (enchantments == null) {
enchantments = new HashMap<>();
}
enchantments.put(enchantment, level);
cachedRendering = null;
}
public void addEnchantment(Enchantment enchantment) {
addEnchantment(enchantment, 1);
}
public void removeEnchantment(Enchantment enchantment) {
if (enchantments == null) {
return;
}
enchantments.remove(enchantment);
cachedRendering = null;
}
public void addEnchantment(Enchantment enchantment, Integer level) {
if (enchantments == null) {
enchantments = new HashMap<>();
}
enchantments.put(enchantment, level);
cachedRendering = null;
}
public Color getLeatherColor() {
return leatherColor;
}
public void removeEnchantment(Enchantment enchantment) {
if (enchantments == null) {
return;
}
enchantments.remove(enchantment);
cachedRendering = null;
}
public void setLeatherColor(Color leatherColor) {
this.leatherColor = leatherColor;
cachedRendering = null;
}
public Color getLeatherColor() {
return leatherColor;
}
public String getSkullOwner() {
if (skullOwner != null) {
return skullOwner.getOriginalValue();
} else {
return null;
}
}
public void setLeatherColor(Color leatherColor) {
this.leatherColor = leatherColor;
cachedRendering = null;
}
public void setSkullOwner(String skullOwner) {
this.skullOwner = PlaceholderString.of(skullOwner);
cachedRendering = null;
}
public String getSkullOwner() {
if (skullOwner != null) {
return skullOwner.getOriginalValue();
} else {
return null;
}
}
public DyeColor getBannerColor() {
return bannerColor;
}
public void setSkullOwner(String skullOwner) {
this.skullOwner = PlaceholderString.of(skullOwner);
cachedRendering = null;
}
public void setBannerColor(DyeColor bannerColor) {
this.bannerColor = bannerColor;
cachedRendering = null;
}
public DyeColor getBannerColor() {
return bannerColor;
}
public List<Pattern> getBannerPatterns() {
return CollectionUtils.copy(bannerPatterns);
}
public void setBannerColor(DyeColor bannerColor) {
this.bannerColor = bannerColor;
cachedRendering = null;
}
public void setBannerPatterns(List<Pattern> bannerPatterns) {
this.bannerPatterns = CollectionUtils.copy(bannerPatterns);
cachedRendering = null;
}
public List<Pattern> getBannerPatterns() {
return CollectionUtils.copy(bannerPatterns);
}
public void setPlaceholdersEnabled(boolean placeholdersEnabled) {
this.placeholdersEnabled = placeholdersEnabled;
cachedRendering = null;
}
public void setBannerPatterns(List<Pattern> bannerPatterns) {
this.bannerPatterns = CollectionUtils.copy(bannerPatterns);
cachedRendering = null;
}
public String renderName(Player viewer) {
if (name == null) {
return null;
}
if (!placeholdersEnabled) {
return name.getOriginalValue();
}
public void setPlaceholdersEnabled(boolean placeholdersEnabled) {
this.placeholdersEnabled = placeholdersEnabled;
cachedRendering = null;
}
String name = this.name.getValue(viewer);
public String renderName(Player viewer) {
if (name == null) {
return null;
}
if (!placeholdersEnabled) {
return name.getOriginalValue();
}
if (name.isEmpty()) {
// Add a color to display the name empty
return ChatColor.WHITE.toString();
} else {
return name;
}
}
String name = this.name.getValue(viewer);
public List<String> renderLore(Player viewer) {
if (lore == null) {
return null;
}
if (!placeholdersEnabled) {
return lore.getOriginalValue();
}
if (name.isEmpty()) {
// Add a color to display the name empty
return ChatColor.WHITE.toString();
} else {
return name;
}
}
return lore.getValue(viewer);
}
public List<String> renderLore(Player viewer) {
if (lore == null) {
return null;
}
if (!placeholdersEnabled) {
return lore.getOriginalValue();
}
@Override
@SuppressWarnings("deprecation")
public ItemStack render(Player viewer) {
if (shouldCacheRendering() && cachedRendering != null) {
// Performance: return a cached item
return cachedRendering;
}
return lore.getValue(viewer);
}
ItemStack itemStack = new ItemStack(material, amount, durability);
@Override
@SuppressWarnings("deprecation")
public ItemStack render(Player viewer) {
if (shouldCacheRendering() && cachedRendering != null) {
// Performance: return a cached item
return cachedRendering;
}
// First try to apply NBT data
if (nbtData != null) {
try {
// Note: this method should not throw any exception. It should log directly to the console
Bukkit.getUnsafe().modifyItemStack(itemStack, nbtData);
} catch (Throwable t) {
this.nbtData = null;
Log.warning("Could not apply NBT data to an item.", t);
}
}
ItemStack itemStack = new ItemStack(material, amount, durability);
// Then apply data from config nodes, overwriting NBT data if there are conflicting values
ItemMeta itemMeta = itemStack.getItemMeta();
// First try to apply NBT data
if (nbtData != null) {
try {
// Note: this method should not throw any exception. It should log directly to the console
Bukkit.getUnsafe().modifyItemStack(itemStack, nbtData);
} catch (Throwable t) {
this.nbtData = null;
Log.warning("Could not apply NBT data to an item.", t);
}
}
if (itemMeta != null) {
itemMeta.setDisplayName(renderName(viewer));
itemMeta.setLore(renderLore(viewer));
// Then apply data from config nodes, overwriting NBT data if there are conflicting values
ItemMeta itemMeta = itemStack.getItemMeta();
if (leatherColor != null && itemMeta instanceof LeatherArmorMeta) {
((LeatherArmorMeta) itemMeta).setColor(leatherColor);
}
if (itemMeta != null) {
itemMeta.setDisplayName(renderName(viewer));
itemMeta.setLore(renderLore(viewer));
if (skullOwner != null && itemMeta instanceof SkullMeta) {
String skullOwner = this.skullOwner.getValue(viewer);
((SkullMeta) itemMeta).setOwner(skullOwner);
}
if (leatherColor != null && itemMeta instanceof LeatherArmorMeta) {
((LeatherArmorMeta) itemMeta).setColor(leatherColor);
}
if (itemMeta instanceof BannerMeta) {
BannerMeta bannerMeta = (BannerMeta) itemMeta;
if (bannerColor != null) {
bannerMeta.setBaseColor(bannerColor);
}
if (bannerPatterns != null) {
((BannerMeta) itemMeta).setPatterns(bannerPatterns);
}
}
if (skullOwner != null && itemMeta instanceof SkullMeta) {
String skullOwner = this.skullOwner.getValue(viewer);
((SkullMeta) itemMeta).setOwner(skullOwner);
}
// Hide all text details (damage, enchantments, potions, etc,)
if (itemMeta.getItemFlags().isEmpty()) {
itemMeta.addItemFlags(ItemFlag.values());
}
if (itemMeta instanceof BannerMeta) {
BannerMeta bannerMeta = (BannerMeta) itemMeta;
if (bannerColor != null) {
bannerMeta.setBaseColor(bannerColor);
}
if (bannerPatterns != null) {
((BannerMeta) itemMeta).setPatterns(bannerPatterns);
}
}
itemStack.setItemMeta(itemMeta);
}
// Hide all text details (damage, enchantments, potions, etc,)
if (itemMeta.getItemFlags().isEmpty()) {
itemMeta.addItemFlags(ItemFlag.values());
}
if (enchantments != null) {
enchantments.forEach(itemStack::addUnsafeEnchantment);
}
itemStack.setItemMeta(itemMeta);
}
if (enchantments != null) {
enchantments.forEach(itemStack::addUnsafeEnchantment);
}
if (shouldCacheRendering()) {
cachedRendering = itemStack;
}
if (shouldCacheRendering()) {
cachedRendering = itemStack;
}
return itemStack;
}
return itemStack;
}
}

View File

@ -9,47 +9,47 @@ import me.filoghost.fcommons.Strings;
import org.bukkit.entity.Player;
public class IconPermission {
private final String permission;
private final boolean negated;
private final String permission;
private final boolean negated;
public IconPermission(String permission) {
if (permission != null) {
permission = permission.trim();
}
if (Strings.isEmpty(permission)) {
this.permission = null;
negated = false;
} else {
if (permission.startsWith("-")) {
this.permission = permission.substring(1);
negated = true;
} else {
this.permission = permission;
negated = false;
}
}
}
private boolean hasPermission(Player player) {
if (isEmpty()) {
return true;
}
public IconPermission(String permission) {
if (permission != null) {
permission = permission.trim();
}
if (Strings.isEmpty(permission)) {
this.permission = null;
negated = false;
} else {
if (permission.startsWith("-")) {
this.permission = permission.substring(1);
negated = true;
} else {
this.permission = permission;
negated = false;
}
}
}
private boolean hasPermission(Player player) {
if (isEmpty()) {
return true;
}
if (negated) {
return !player.hasPermission(permission);
} else {
return player.hasPermission(permission);
}
}
if (negated) {
return !player.hasPermission(permission);
} else {
return player.hasPermission(permission);
}
}
public boolean isEmpty() {
return this.permission == null;
}
public boolean isEmpty() {
return this.permission == null;
}
public static boolean hasPermission(Player player, IconPermission permission) {
return permission == null || permission.hasPermission(player);
}
public static boolean hasPermission(Player player, IconPermission permission) {
return permission == null || permission.hasPermission(player);
}
}

View File

@ -6,6 +6,7 @@
package me.filoghost.chestcommands.icon;
import com.google.common.collect.ImmutableList;
import java.util.List;
import me.filoghost.chestcommands.action.Action;
import me.filoghost.chestcommands.action.OpenMenuAction;
import me.filoghost.chestcommands.api.ClickResult;
@ -23,170 +24,168 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.List;
public class InternalConfigurableIcon extends BaseConfigurableIcon implements RefreshableIcon {
private IconPermission viewPermission;
private IconPermission clickPermission;
private String noClickPermissionMessage;
private IconPermission viewPermission;
private IconPermission clickPermission;
private String noClickPermissionMessage;
private RequiredMoney requiredMoney;
private RequiredExpLevel requiredExpLevel;
private RequiredItems requiredItems;
private RequiredMoney requiredMoney;
private RequiredExpLevel requiredExpLevel;
private RequiredItems requiredItems;
private ImmutableList<Action> clickActions;
private ClickResult clickResult;
private ImmutableList<Action> clickActions;
private ClickResult clickResult;
public InternalConfigurableIcon(Material material) {
super(material);
setPlaceholdersEnabled(true);
this.clickResult = ClickResult.CLOSE;
}
public InternalConfigurableIcon(Material material) {
super(material);
setPlaceholdersEnabled(true);
this.clickResult = ClickResult.CLOSE;
}
public boolean canViewIcon(Player player) {
return IconPermission.hasPermission(player, viewPermission);
}
public boolean hasViewPermission() {
return viewPermission != null && !viewPermission.isEmpty();
}
public boolean canViewIcon(Player player) {
return IconPermission.hasPermission(player, viewPermission);
}
public boolean hasViewPermission() {
return viewPermission != null && !viewPermission.isEmpty();
}
public void setClickPermission(String permission) {
this.clickPermission = new IconPermission(permission);
}
public void setNoClickPermissionMessage(String noClickPermissionMessage) {
this.noClickPermissionMessage = noClickPermissionMessage;
}
public void setViewPermission(String viewPermission) {
this.viewPermission = new IconPermission(viewPermission);
}
public void setClickPermission(String permission) {
this.clickPermission = new IconPermission(permission);
}
public void setNoClickPermissionMessage(String noClickPermissionMessage) {
this.noClickPermissionMessage = noClickPermissionMessage;
}
public void setViewPermission(String viewPermission) {
this.viewPermission = new IconPermission(viewPermission);
}
public void setRequiredMoney(double requiredMoney) {
if (requiredMoney > 0.0) {
this.requiredMoney = new RequiredMoney(requiredMoney);
} else {
this.requiredMoney = null;
}
}
public void setRequiredMoney(double requiredMoney) {
if (requiredMoney > 0.0) {
this.requiredMoney = new RequiredMoney(requiredMoney);
} else {
this.requiredMoney = null;
}
}
public void setRequiredExpLevel(int requiredLevels) {
if (requiredLevels > 0) {
this.requiredExpLevel = new RequiredExpLevel(requiredLevels);
} else {
this.requiredExpLevel = null;
}
}
public void setRequiredExpLevel(int requiredLevels) {
if (requiredLevels > 0) {
this.requiredExpLevel = new RequiredExpLevel(requiredLevels);
} else {
this.requiredExpLevel = null;
}
}
public void setRequiredItems(List<RequiredItem> requiredItems) {
if (requiredItems != null) {
this.requiredItems = new RequiredItems(requiredItems);
} else {
this.requiredItems = null;
}
}
public void setRequiredItems(List<RequiredItem> requiredItems) {
if (requiredItems != null) {
this.requiredItems = new RequiredItems(requiredItems);
} else {
this.requiredItems = null;
}
}
public void setClickActions(List<Action> clickActions) {
this.clickActions = CollectionUtils.immutableCopy(clickActions);
}
@Override
public ItemStack render(Player viewer) {
if (canViewIcon(viewer)) {
return super.render(viewer);
} else {
return null;
}
}
public void setClickActions(List<Action> clickActions) {
this.clickActions = CollectionUtils.immutableCopy(clickActions);
}
@Override
public ItemStack render(Player viewer) {
if (canViewIcon(viewer)) {
return super.render(viewer);
} else {
return null;
}
}
@Override
protected boolean shouldCacheRendering() {
return super.shouldCacheRendering() && !hasViewPermission();
}
@Override
protected boolean shouldCacheRendering() {
return super.shouldCacheRendering() && !hasViewPermission();
}
public void setClickResult(ClickResult clickResult) {
Preconditions.notNull(clickResult, "clickResult");
this.clickResult = clickResult;
}
public void setClickResult(ClickResult clickResult) {
Preconditions.notNull(clickResult, "clickResult");
this.clickResult = clickResult;
}
@Override
public ClickResult onClick(MenuView menuView, Player player) {
if (!IconPermission.hasPermission(player, viewPermission)) {
return ClickResult.KEEP_OPEN;
}
@Override
public ClickResult onClick(MenuView menuView, Player player) {
if (!IconPermission.hasPermission(player, viewPermission)) {
return ClickResult.KEEP_OPEN;
}
if (!IconPermission.hasPermission(player, clickPermission)) {
if (noClickPermissionMessage != null) {
player.sendMessage(noClickPermissionMessage);
} else {
player.sendMessage(Lang.default_no_icon_permission);
}
return clickResult;
}
if (!IconPermission.hasPermission(player, clickPermission)) {
if (noClickPermissionMessage != null) {
player.sendMessage(noClickPermissionMessage);
} else {
player.sendMessage(Lang.default_no_icon_permission);
}
return clickResult;
}
// Check all the requirements
Requirement[] requirements = {requiredMoney, requiredExpLevel, requiredItems};
boolean hasAllRequirements = Requirement.hasAllCosts(player, requirements);
if (!hasAllRequirements) {
return clickResult;
}
// Check all the requirements
Requirement[] requirements = {requiredMoney, requiredExpLevel, requiredItems};
boolean hasAllRequirements = Requirement.hasAllCosts(player, requirements);
if (!hasAllRequirements) {
return clickResult;
}
// If all requirements are satisfied, take their cost
boolean takenAllCosts = Requirement.takeAllCosts(player, requirements);
if (!takenAllCosts) {
return clickResult;
}
boolean hasOpenMenuAction = false;
if (clickActions != null) {
for (Action action : clickActions) {
action.execute(player);
if (action instanceof OpenMenuAction) {
hasOpenMenuAction = true;
}
}
}
// If all requirements are satisfied, take their cost
boolean takenAllCosts = Requirement.takeAllCosts(player, requirements);
if (!takenAllCosts) {
return clickResult;
}
boolean hasOpenMenuAction = false;
if (clickActions != null) {
for (Action action : clickActions) {
action.execute(player);
if (action instanceof OpenMenuAction) {
hasOpenMenuAction = true;
}
}
}
// Update the menu after taking requirement costs and executing all actions
menuView.refresh();
// Force menu to stay open if actions open another menu
if (hasOpenMenuAction) {
return ClickResult.KEEP_OPEN;
} else {
return clickResult;
}
}
// Update the menu after taking requirement costs and executing all actions
menuView.refresh();
// Force menu to stay open if actions open another menu
if (hasOpenMenuAction) {
return ClickResult.KEEP_OPEN;
} else {
return clickResult;
}
}
@Override
public ItemStack updateRendering(Player viewer, ItemStack currentRendering) {
if (currentRendering != null && shouldCacheRendering()) {
// Internal icons do not change, no need to update if the item is already rendered
return currentRendering;
}
@Override
public ItemStack updateRendering(Player viewer, ItemStack currentRendering) {
if (currentRendering != null && shouldCacheRendering()) {
// Internal icons do not change, no need to update if the item is already rendered
return currentRendering;
}
if (!canViewIcon(viewer)) {
// Hide the current item
return null;
}
if (!canViewIcon(viewer)) {
// Hide the current item
return null;
}
if (currentRendering == null) {
// Render item normally
return render(viewer);
} else {
// Internal icons are loaded and then never change, we can safely update only name and lore (for performance)
ItemMeta meta = currentRendering.getItemMeta();
meta.setDisplayName(renderName(viewer));
meta.setLore(renderLore(viewer));
currentRendering.setItemMeta(meta);
return currentRendering;
}
}
if (currentRendering == null) {
// Render item normally
return render(viewer);
} else {
// Internal icons are loaded and then never change, we can safely update only name and lore (for performance)
ItemMeta meta = currentRendering.getItemMeta();
meta.setDisplayName(renderName(viewer));
meta.setLore(renderLore(viewer));
currentRendering.setItemMeta(meta);
return currentRendering;
}
}
}

View File

@ -9,7 +9,7 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public interface RefreshableIcon {
ItemStack updateRendering(Player viewer, ItemStack currentRendering);
ItemStack updateRendering(Player viewer, ItemStack currentRendering);
}

View File

@ -11,32 +11,32 @@ import org.bukkit.entity.Player;
public class RequiredExpLevel implements Requirement {
private final int levels;
public RequiredExpLevel(int levels) {
Preconditions.checkArgument(levels > 0, "levels must be positive");
this.levels = levels;
}
private final int levels;
@Override
public boolean hasCost(Player player) {
if (player.getLevel() < levels) {
player.sendMessage(Lang.no_exp.replace("{levels}", Integer.toString(levels)));
return false;
}
return true;
}
public RequiredExpLevel(int levels) {
Preconditions.checkArgument(levels > 0, "levels must be positive");
this.levels = levels;
}
@Override
public boolean takeCost(Player player) {
int newLevel = player.getLevel() - levels;
if (newLevel < 0) {
newLevel = 0;
}
player.setLevel(newLevel);
return true;
}
@Override
public boolean hasCost(Player player) {
if (player.getLevel() < levels) {
player.sendMessage(Lang.no_exp.replace("{levels}", Integer.toString(levels)));
return false;
}
return true;
}
@Override
public boolean takeCost(Player player) {
int newLevel = player.getLevel() - levels;
if (newLevel < 0) {
newLevel = 0;
}
player.setLevel(newLevel);
return true;
}
}

View File

@ -13,39 +13,39 @@ import org.bukkit.entity.Player;
public class RequiredMoney implements Requirement {
private final double moneyAmount;
public RequiredMoney(double moneyAmount) {
Preconditions.checkArgument(moneyAmount > 0.0, "money amount must be positive");
this.moneyAmount = moneyAmount;
}
private final double moneyAmount;
@Override
public boolean hasCost(Player player) {
if (!VaultEconomyHook.INSTANCE.isEnabled()) {
player.sendMessage(Errors.User.configurationError(
"the item has a price, but Vault with a compatible economy plugin was not found. "
+ "For security, the action has been blocked"));
return false;
}
public RequiredMoney(double moneyAmount) {
Preconditions.checkArgument(moneyAmount > 0.0, "money amount must be positive");
this.moneyAmount = moneyAmount;
}
if (!VaultEconomyHook.hasMoney(player, moneyAmount)) {
player.sendMessage(Lang.no_money.replace("{money}", VaultEconomyHook.formatMoney(moneyAmount)));
return false;
}
return true;
}
@Override
public boolean hasCost(Player player) {
if (!VaultEconomyHook.INSTANCE.isEnabled()) {
player.sendMessage(Errors.User.configurationError(
"the item has a price, but Vault with a compatible economy plugin was not found. "
+ "For security, the action has been blocked"));
return false;
}
@Override
public boolean takeCost(Player player) {
boolean success = VaultEconomyHook.takeMoney(player, moneyAmount);
if (!success) {
player.sendMessage(Errors.User.configurationError("a money transaction couldn't be executed"));
}
return success;
}
if (!VaultEconomyHook.hasMoney(player, moneyAmount)) {
player.sendMessage(Lang.no_money.replace("{money}", VaultEconomyHook.formatMoney(moneyAmount)));
return false;
}
return true;
}
@Override
public boolean takeCost(Player player) {
boolean success = VaultEconomyHook.takeMoney(player, moneyAmount);
if (!success) {
player.sendMessage(Errors.User.configurationError("a money transaction couldn't be executed"));
}
return success;
}
}

View File

@ -8,32 +8,32 @@ package me.filoghost.chestcommands.icon.requirement;
import org.bukkit.entity.Player;
public interface Requirement {
boolean hasCost(Player player);
boolean takeCost(Player player);
static boolean hasAllCosts(Player player, Requirement... requirements) {
for (Requirement requirement : requirements) {
if (requirement != null && !requirement.hasCost(player)) {
return false;
}
}
return true;
}
static boolean takeAllCosts(Player player, Requirement... requirements) {
for (Requirement requirement : requirements) {
if (requirement != null) {
boolean success = requirement.takeCost(player);
if (!success) {
return false;
}
}
}
return true;
}
boolean hasCost(Player player);
boolean takeCost(Player player);
static boolean hasAllCosts(Player player, Requirement... requirements) {
for (Requirement requirement : requirements) {
if (requirement != null && !requirement.hasCost(player)) {
return false;
}
}
return true;
}
static boolean takeAllCosts(Player player, Requirement... requirements) {
for (Requirement requirement : requirements) {
if (requirement != null) {
boolean success = requirement.takeCost(player);
if (!success) {
return false;
}
}
}
return true;
}
}

View File

@ -5,80 +5,79 @@
*/
package me.filoghost.chestcommands.icon.requirement.item;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import me.filoghost.fcommons.MaterialsHelper;
import me.filoghost.fcommons.Preconditions;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class InventoryTakeHelper {
private final PlayerInventory inventory;
private final List<RemainingItem> remainingItems;
private final PlayerInventory inventory;
private final List<RemainingItem> remainingItems;
private boolean success;
private boolean success;
public InventoryTakeHelper(PlayerInventory inventory) {
this.inventory = inventory;
this.remainingItems = new ArrayList<>();
public InventoryTakeHelper(PlayerInventory inventory) {
this.inventory = inventory;
this.remainingItems = new ArrayList<>();
for (int slotIndex = 0; slotIndex < inventory.getSize(); slotIndex++) {
ItemStack item = inventory.getItem(slotIndex);
if (item != null && !MaterialsHelper.isAir(item.getType())) {
remainingItems.add(new RemainingItem(slotIndex, item));
}
}
}
for (int slotIndex = 0; slotIndex < inventory.getSize(); slotIndex++) {
ItemStack item = inventory.getItem(slotIndex);
if (item != null && !MaterialsHelper.isAir(item.getType())) {
remainingItems.add(new RemainingItem(slotIndex, item));
}
}
}
public boolean prepareTakeItems(List<RequiredItem> requiredItems) {
List<RequiredItem> missingItems = new ArrayList<>();
public boolean prepareTakeItems(List<RequiredItem> requiredItems) {
List<RequiredItem> missingItems = new ArrayList<>();
// Sort required items: check required items with a restrictive durability first
List<RequiredItem> sortedRequiredItems = requiredItems.stream()
.sorted(Comparator.comparing(RequiredItem::hasRestrictiveDurability).reversed())
.collect(Collectors.toList());
// Sort required items: check required items with a restrictive durability first
List<RequiredItem> sortedRequiredItems = requiredItems.stream()
.sorted(Comparator.comparing(RequiredItem::hasRestrictiveDurability).reversed())
.collect(Collectors.toList());
for (RequiredItem requiredItem : sortedRequiredItems) {
int remainingRequiredAmount = requiredItem.getAmount();
for (RequiredItem requiredItem : sortedRequiredItems) {
int remainingRequiredAmount = requiredItem.getAmount();
for (RemainingItem remainingItem : remainingItems) {
if (remainingItem.getAmount() > 0 && requiredItem.isMatchingType(remainingItem)) {
int takenAmount = remainingItem.subtract(remainingRequiredAmount);
remainingRequiredAmount -= takenAmount;
if (remainingRequiredAmount == 0) {
break;
}
}
}
for (RemainingItem remainingItem : remainingItems) {
if (remainingItem.getAmount() > 0 && requiredItem.isMatchingType(remainingItem)) {
int takenAmount = remainingItem.subtract(remainingRequiredAmount);
remainingRequiredAmount -= takenAmount;
if (remainingRequiredAmount == 0) {
break;
}
}
}
// Couldn't take the required amount of an item
if (remainingRequiredAmount > 0) {
missingItems.add(requiredItem);
}
}
// Couldn't take the required amount of an item
if (remainingRequiredAmount > 0) {
missingItems.add(requiredItem);
}
}
success = missingItems.isEmpty();
return success;
}
success = missingItems.isEmpty();
return success;
}
public void applyTakeItems() {
Preconditions.checkState(success, "items take preparation was not run or successful");
public void applyTakeItems() {
Preconditions.checkState(success, "items take preparation was not run or successful");
for (RemainingItem remainingItem : remainingItems) {
int slotIndex = remainingItem.getSlotIndex();
ItemStack inventoryItem = inventory.getItem(slotIndex);
if (remainingItem.getAmount() != inventoryItem.getAmount()) {
if (remainingItem.getAmount() > 0) {
inventoryItem.setAmount(remainingItem.getAmount());
} else {
inventory.setItem(slotIndex, null);
}
}
}
}
for (RemainingItem remainingItem : remainingItems) {
int slotIndex = remainingItem.getSlotIndex();
ItemStack inventoryItem = inventory.getItem(slotIndex);
if (remainingItem.getAmount() != inventoryItem.getAmount()) {
if (remainingItem.getAmount() > 0) {
inventoryItem.setAmount(remainingItem.getAmount());
} else {
inventory.setItem(slotIndex, null);
}
}
}
}
}

View File

@ -10,39 +10,39 @@ import org.bukkit.inventory.ItemStack;
public class RemainingItem {
private final int slotIndex;
private final Material material;
private final short durability;
private int amount;
private final int slotIndex;
private final Material material;
private final short durability;
private int amount;
public RemainingItem(int slotIndex, ItemStack item) {
this.slotIndex = slotIndex;
this.material = item.getType();
this.durability = item.getDurability();
this.amount = item.getAmount();
}
public RemainingItem(int slotIndex, ItemStack item) {
this.slotIndex = slotIndex;
this.material = item.getType();
this.durability = item.getDurability();
this.amount = item.getAmount();
}
public int getSlotIndex() {
return slotIndex;
}
public int getSlotIndex() {
return slotIndex;
}
public Material getMaterial() {
return material;
}
public Material getMaterial() {
return material;
}
public short getDurability() {
return durability;
}
public short getDurability() {
return durability;
}
public int getAmount() {
return amount;
}
public int getAmount() {
return amount;
}
public int subtract(int minusAmount) {
int subtractedAmount = Math.min(minusAmount, this.amount);
public int subtract(int minusAmount) {
int subtractedAmount = Math.min(minusAmount, this.amount);
this.amount -= subtractedAmount;
return subtractedAmount;
}
this.amount -= subtractedAmount;
return subtractedAmount;
}
}

View File

@ -10,51 +10,51 @@ import org.bukkit.Material;
public class RequiredItem {
private final Material material;
private final int amount;
private short durability;
private boolean isDurabilityRestrictive = false;
private final Material material;
private final int amount;
private short durability;
private boolean isDurabilityRestrictive = false;
public RequiredItem(Material material, int amount) {
Preconditions.checkArgumentNotAir(material, "material");
public RequiredItem(Material material, int amount) {
Preconditions.checkArgumentNotAir(material, "material");
this.material = material;
this.amount = amount;
}
this.material = material;
this.amount = amount;
}
public Material getMaterial() {
return material;
}
public Material getMaterial() {
return material;
}
public int getAmount() {
return amount;
}
public int getAmount() {
return amount;
}
public short getDurability() {
return durability;
}
public short getDurability() {
return durability;
}
public void setRestrictiveDurability(short durability) {
Preconditions.checkArgument(durability >= 0, "durability must be 0 or greater");
public void setRestrictiveDurability(short durability) {
Preconditions.checkArgument(durability >= 0, "durability must be 0 or greater");
this.durability = durability;
isDurabilityRestrictive = true;
}
this.durability = durability;
isDurabilityRestrictive = true;
}
public boolean hasRestrictiveDurability() {
return isDurabilityRestrictive;
}
public boolean hasRestrictiveDurability() {
return isDurabilityRestrictive;
}
public boolean isMatchingType(RemainingItem item) {
return item != null && item.getMaterial() == material && isMatchingDurability(item.getDurability());
}
private boolean isMatchingDurability(short durability) {
if (isDurabilityRestrictive) {
return this.durability == durability;
} else {
return true;
}
}
public boolean isMatchingType(RemainingItem item) {
return item != null && item.getMaterial() == material && isMatchingDurability(item.getDurability());
}
private boolean isMatchingDurability(short durability) {
if (isDurabilityRestrictive) {
return this.durability == durability;
} else {
return true;
}
}
}

View File

@ -6,49 +6,48 @@
package me.filoghost.chestcommands.icon.requirement.item;
import com.google.common.collect.ImmutableList;
import java.util.List;
import me.filoghost.chestcommands.config.Lang;
import me.filoghost.chestcommands.icon.requirement.Requirement;
import me.filoghost.chestcommands.util.Utils;
import org.bukkit.entity.Player;
import java.util.List;
public class RequiredItems implements Requirement {
private final List<RequiredItem> items;
public RequiredItems(List<RequiredItem> items) {
this.items = ImmutableList.copyOf(items);
}
private final List<RequiredItem> items;
public RequiredItems(List<RequiredItem> items) {
this.items = ImmutableList.copyOf(items);
}
@Override
public boolean hasCost(Player player) {
InventoryTakeHelper inventoryTakeHelper = new InventoryTakeHelper(player.getInventory());
boolean hasItems = inventoryTakeHelper.prepareTakeItems(items);
@Override
public boolean hasCost(Player player) {
InventoryTakeHelper inventoryTakeHelper = new InventoryTakeHelper(player.getInventory());
boolean hasItems = inventoryTakeHelper.prepareTakeItems(items);
if (!hasItems) {
for (RequiredItem item : items) {
player.sendMessage(Lang.no_required_item
.replace("{material}", Utils.formatEnum(item.getMaterial()))
.replace("{amount}", Integer.toString(item.getAmount()))
.replace("{durability}", item.hasRestrictiveDurability() ? Short.toString(item.getDurability()) : Lang.any));
}
}
return hasItems;
}
if (!hasItems) {
for (RequiredItem item : items) {
player.sendMessage(Lang.no_required_item
.replace("{material}", Utils.formatEnum(item.getMaterial()))
.replace("{amount}", Integer.toString(item.getAmount()))
.replace("{durability}", item.hasRestrictiveDurability() ? Short.toString(item.getDurability()) : Lang.any));
}
}
return hasItems;
}
@Override
public boolean takeCost(Player player) {
InventoryTakeHelper inventoryTakeHelper = new InventoryTakeHelper(player.getInventory());
boolean hasItems = inventoryTakeHelper.prepareTakeItems(items);
@Override
public boolean takeCost(Player player) {
InventoryTakeHelper inventoryTakeHelper = new InventoryTakeHelper(player.getInventory());
boolean hasItems = inventoryTakeHelper.prepareTakeItems(items);
if (!hasItems) {
return false;
}
inventoryTakeHelper.applyTakeItems();
return true;
}
if (!hasItems) {
return false;
}
inventoryTakeHelper.applyTakeItems();
return true;
}
}

View File

@ -7,22 +7,22 @@ package me.filoghost.chestcommands.inventory;
public class ArrayGrid<T> extends Grid<T> {
private final T[] elements;
private final T[] elements;
@SuppressWarnings("unchecked")
public ArrayGrid(int rows, int columns) {
super(rows, columns);
this.elements = (T[]) new Object[getSize()];
}
@SuppressWarnings("unchecked")
public ArrayGrid(int rows, int columns) {
super(rows, columns);
this.elements = (T[]) new Object[getSize()];
}
@Override
protected T getByIndex0(int ordinalIndex) {
return elements[ordinalIndex];
}
@Override
protected T getByIndex0(int ordinalIndex) {
return elements[ordinalIndex];
}
@Override
protected void setByIndex0(int ordinalIndex, T element) {
elements[ordinalIndex] = element;
}
@Override
protected void setByIndex0(int ordinalIndex, T element) {
elements[ordinalIndex] = element;
}
}

View File

@ -17,53 +17,53 @@ import org.bukkit.inventory.ItemStack;
*/
public class DefaultMenuView implements MenuView {
private final BaseMenu menu;
private final InventoryGrid bukkitInventory;
private final Player viewer;
private final BaseMenu menu;
private final InventoryGrid bukkitInventory;
private final Player viewer;
public DefaultMenuView(BaseMenu menu, Player viewer) {
this.menu = menu;
this.viewer = viewer;
this.bukkitInventory = new InventoryGrid(new MenuInventoryHolder(this), menu.getRowCount(), menu.getTitle());
refresh();
}
public DefaultMenuView(BaseMenu menu, Player viewer) {
this.menu = menu;
this.viewer = viewer;
this.bukkitInventory = new InventoryGrid(new MenuInventoryHolder(this), menu.getRowCount(), menu.getTitle());
refresh();
}
@Override
public void refresh() {
for (int i = 0; i < menu.getIcons().getSize(); i++) {
Icon icon = menu.getIcons().getByIndex(i);
@Override
public void refresh() {
for (int i = 0; i < menu.getIcons().getSize(); i++) {
Icon icon = menu.getIcons().getByIndex(i);
if (icon == null) {
bukkitInventory.setByIndex(i, null);
} else if (icon instanceof RefreshableIcon) {
ItemStack newItemStack = ((RefreshableIcon) icon).updateRendering(viewer, bukkitInventory.getByIndex(i));
bukkitInventory.setByIndex(i, newItemStack);
} else {
bukkitInventory.setByIndex(i, icon.render(viewer));
}
}
}
if (icon == null) {
bukkitInventory.setByIndex(i, null);
} else if (icon instanceof RefreshableIcon) {
ItemStack newItemStack = ((RefreshableIcon) icon).updateRendering(viewer, bukkitInventory.getByIndex(i));
bukkitInventory.setByIndex(i, newItemStack);
} else {
bukkitInventory.setByIndex(i, icon.render(viewer));
}
}
}
public void open(Player viewer) {
viewer.openInventory(bukkitInventory.getInventory());
}
public void open(Player viewer) {
viewer.openInventory(bukkitInventory.getInventory());
}
public Icon getIcon(int slot) {
if (slot < 0 || slot >= bukkitInventory.getSize()) {
return null;
}
public Icon getIcon(int slot) {
if (slot < 0 || slot >= bukkitInventory.getSize()) {
return null;
}
return menu.getIcons().getByIndex(slot);
}
return menu.getIcons().getByIndex(slot);
}
@Override
public BaseMenu getMenu() {
return menu;
}
@Override
public BaseMenu getMenu() {
return menu;
}
@Override
public Player getViewer() {
return viewer;
}
@Override
public Player getViewer() {
return viewer;
}
}

View File

@ -24,57 +24,57 @@ import me.filoghost.fcommons.Preconditions;
*
*/
public abstract class Grid<T> {
private final int rows, columns, size;
private final int rows, columns, size;
public Grid(int rows, int columns) {
this.rows = rows;
this.columns = columns;
this.size = rows * columns;
}
public Grid(int rows, int columns) {
this.rows = rows;
this.columns = columns;
this.size = rows * columns;
}
public final void set(int row, int column, T element) {
setByIndex(toOrdinalIndex(row, column), element);
}
public final void set(int row, int column, T element) {
setByIndex(toOrdinalIndex(row, column), element);
}
public final T get(int row, int column) {
return getByIndex(toOrdinalIndex(row, column));
}
public final T getByIndex(int ordinalIndex) {
Preconditions.checkIndex(ordinalIndex, getSize(), "ordinalIndex");
return getByIndex0(ordinalIndex);
}
public final T get(int row, int column) {
return getByIndex(toOrdinalIndex(row, column));
}
public final T getByIndex(int ordinalIndex) {
Preconditions.checkIndex(ordinalIndex, getSize(), "ordinalIndex");
return getByIndex0(ordinalIndex);
}
protected abstract T getByIndex0(int ordinalIndex);
protected abstract T getByIndex0(int ordinalIndex);
public final void setByIndex(int ordinalIndex, T element) {
Preconditions.checkIndex(ordinalIndex, getSize(), "ordinalIndex");
setByIndex0(ordinalIndex, element);
}
public final void setByIndex(int ordinalIndex, T element) {
Preconditions.checkIndex(ordinalIndex, getSize(), "ordinalIndex");
setByIndex0(ordinalIndex, element);
}
protected abstract void setByIndex0(int ordinalIndex, T element);
protected abstract void setByIndex0(int ordinalIndex, T element);
private int toOrdinalIndex(int row, int column) {
Preconditions.checkIndex(row, getRows(), "row");
Preconditions.checkIndex(column, getColumns(), "column");
private int toOrdinalIndex(int row, int column) {
Preconditions.checkIndex(row, getRows(), "row");
Preconditions.checkIndex(column, getColumns(), "column");
int ordinalIndex = row * getColumns() + column;
Preconditions.checkIndex(ordinalIndex, getSize(), "ordinalIndex");
return ordinalIndex;
}
public int getRows() {
return rows;
}
public int getColumns() {
return columns;
}
int ordinalIndex = row * getColumns() + column;
Preconditions.checkIndex(ordinalIndex, getSize(), "ordinalIndex");
return ordinalIndex;
}
public int getRows() {
return rows;
}
public int getColumns() {
return columns;
}
public int getSize() {
return size;
}
public int getSize() {
return size;
}
}

View File

@ -11,25 +11,25 @@ import org.bukkit.inventory.ItemStack;
public class InventoryGrid extends Grid<ItemStack> {
private final Inventory inventory;
private final Inventory inventory;
public InventoryGrid(MenuInventoryHolder inventoryHolder, int rows, String title) {
super(rows, 9);
this.inventory = Bukkit.createInventory(inventoryHolder, getSize(), title);
}
public InventoryGrid(MenuInventoryHolder inventoryHolder, int rows, String title) {
super(rows, 9);
this.inventory = Bukkit.createInventory(inventoryHolder, getSize(), title);
}
public Inventory getInventory() {
return inventory;
}
public Inventory getInventory() {
return inventory;
}
@Override
protected ItemStack getByIndex0(int ordinalIndex) {
return inventory.getItem(ordinalIndex);
}
@Override
protected ItemStack getByIndex0(int ordinalIndex) {
return inventory.getItem(ordinalIndex);
}
@Override
protected void setByIndex0(int ordinalIndex, ItemStack element) {
inventory.setItem(ordinalIndex, element);
}
@Override
protected void setByIndex0(int ordinalIndex, ItemStack element) {
inventory.setItem(ordinalIndex, element);
}
}

View File

@ -12,25 +12,25 @@ import org.bukkit.inventory.InventoryHolder;
public class MenuInventoryHolder implements InventoryHolder {
private final DefaultMenuView menuView;
private final DefaultMenuView menuView;
public MenuInventoryHolder(DefaultMenuView menuView) {
Preconditions.notNull(menuView, "menuView");
this.menuView = menuView;
}
public MenuInventoryHolder(DefaultMenuView menuView) {
Preconditions.notNull(menuView, "menuView");
this.menuView = menuView;
}
@Override
public Inventory getInventory() {
/*
* This inventory will not do anything.
* I'm 90% sure that it doesn't break any other plugin,
* because the only way you can get here is using InventoryClickEvent,
* that is cancelled by ChestCommands, or using InventoryOpenEvent.
*/
return Bukkit.createInventory(null, 9);
}
@Override
public Inventory getInventory() {
/*
* This inventory will not do anything.
* I'm 90% sure that it doesn't break any other plugin,
* because the only way you can get here is using InventoryClickEvent,
* that is cancelled by ChestCommands, or using InventoryOpenEvent.
*/
return Bukkit.createInventory(null, 9);
}
public DefaultMenuView getMenuView() {
return menuView;
}
public DefaultMenuView getMenuView() {
return menuView;
}
}

View File

@ -5,52 +5,51 @@
*/
package me.filoghost.chestcommands.legacy;
import me.filoghost.fcommons.Preconditions;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import me.filoghost.fcommons.Preconditions;
public class Backup {
private final Path dataFolder;
private final Path backupFolder;
private final Path infoFile;
private final Path dataFolder;
private final Path backupFolder;
private final Path infoFile;
public Backup(Path dataFolder, String backupName) {
this.dataFolder = dataFolder;
Path backupsFolder = dataFolder.resolve("old_files");
this.backupFolder = backupsFolder.resolve(backupName);
this.infoFile = backupsFolder.resolve("readme.txt");
}
public Backup(Path dataFolder, String backupName) {
this.dataFolder = dataFolder;
Path backupsFolder = dataFolder.resolve("old_files");
this.backupFolder = backupsFolder.resolve(backupName);
this.infoFile = backupsFolder.resolve("readme.txt");
}
public static Backup newTimestampedBackup(Path dataFolder) {
String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd-HH.mm"));
String backupName = "backup_" + date;
return new Backup(dataFolder, backupName);
}
public static Backup newTimestampedBackup(Path dataFolder) {
String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd-HH.mm"));
String backupName = "backup_" + date;
return new Backup(dataFolder, backupName);
}
public void addFile(Path fileToBackup) throws IOException {
Preconditions.checkArgument(fileToBackup.startsWith(dataFolder), "file is not inside data folder");
Path destination = backupFolder.resolve(dataFolder.relativize(fileToBackup));
Files.createDirectories(destination.getParent());
public void addFile(Path fileToBackup) throws IOException {
Preconditions.checkArgument(fileToBackup.startsWith(dataFolder), "file is not inside data folder");
Path destination = backupFolder.resolve(dataFolder.relativize(fileToBackup));
Files.createDirectories(destination.getParent());
// Add backup file if no already present
if (!Files.isRegularFile(destination)) {
Files.copy(fileToBackup, destination);
}
// Add backup file if no already present
if (!Files.isRegularFile(destination)) {
Files.copy(fileToBackup, destination);
}
// Add README file if not already present
if (!Files.isRegularFile(infoFile)) {
Files.write(infoFile, Arrays.asList(
"Files in this folders are copies of original configuration files that have been automatically upgraded.",
"",
"Note: some configuration upgrades remove comments and other formatting (such as empty lines)."
));
}
}
// Add README file if not already present
if (!Files.isRegularFile(infoFile)) {
Files.write(infoFile, Arrays.asList(
"Files in this folders are copies of original configuration files that have been automatically upgraded.",
"",
"Note: some configuration upgrades remove comments and other formatting (such as empty lines)."
));
}
}
}

View File

@ -7,8 +7,8 @@ package me.filoghost.chestcommands.legacy;
public class UpgradeExecutorException extends Exception {
public UpgradeExecutorException(String message, Throwable cause) {
super(message, cause);
}
public UpgradeExecutorException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -6,6 +6,11 @@
package me.filoghost.chestcommands.legacy;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import me.filoghost.chestcommands.config.ConfigManager;
import me.filoghost.chestcommands.legacy.upgrade.Upgrade;
import me.filoghost.chestcommands.legacy.upgrade.UpgradeTask;
@ -20,74 +25,68 @@ import me.filoghost.fcommons.collection.CollectionUtils;
import me.filoghost.fcommons.config.ConfigLoader;
import me.filoghost.fcommons.logging.Log;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
public class UpgradeList {
/*
* Note: order of declaration determines order of execution
*/
private static final ImmutableList<Upgrade> orderedUpgrades = ImmutableList.of(
multiTaskUpgrade("v4.0-menus-rename", (configManager) -> {
return createMenuTasks(configManager, v4_0_MenuNodeRenameUpgradeTask::new);
}),
/*
* Note: order of declaration determines order of execution
*/
private static final ImmutableList<Upgrade> orderedUpgrades = ImmutableList.of(
multiTaskUpgrade("v4.0-menus-rename", (configManager) -> {
return createMenuTasks(configManager, v4_0_MenuNodeRenameUpgradeTask::new);
}),
// Reformat after nodes have already been renamed
multiTaskUpgrade("v4.0-menus-reformat", (configManager) -> {
String legacyCommandSeparator = readLegacyCommandSeparator(configManager);
return createMenuTasks(configManager,
file -> new v4_0_MenuReformatUpgradeTask(configManager, file, legacyCommandSeparator));
}),
// Reformat after nodes have already been renamed
multiTaskUpgrade("v4.0-menus-reformat", (configManager) -> {
String legacyCommandSeparator = readLegacyCommandSeparator(configManager);
return createMenuTasks(configManager,
file -> new v4_0_MenuReformatUpgradeTask(configManager, file, legacyCommandSeparator));
}),
// Upgrade config after reading the command separator for menus
singleTaskUpgrade("v4.0-config", v4_0_SettingsUpgradeTask::new),
singleTaskUpgrade("v4.0-placeholders", v4_0_PlaceholdersUpgradeTask::new),
singleTaskUpgrade("v4.0-lang", v4_0_LangUpgradeTask::new)
);
// Upgrade config after reading the command separator for menus
singleTaskUpgrade("v4.0-config", v4_0_SettingsUpgradeTask::new),
singleTaskUpgrade("v4.0-placeholders", v4_0_PlaceholdersUpgradeTask::new),
singleTaskUpgrade("v4.0-lang", v4_0_LangUpgradeTask::new)
);
private static Upgrade singleTaskUpgrade(String id, Upgrade.SingleTaskSupplier upgradeTaskSupplier) {
return new Upgrade(id, configManager -> {
return Collections.singletonList(upgradeTaskSupplier.getTask(configManager));
});
}
private static Upgrade singleTaskUpgrade(String id, Upgrade.SingleTaskSupplier upgradeTaskSupplier) {
return new Upgrade(id, configManager -> {
return Collections.singletonList(upgradeTaskSupplier.getTask(configManager));
});
}
private static Upgrade multiTaskUpgrade(String id, Upgrade.MultiTaskSupplier upgradeTasksSupplier) {
return new Upgrade(id, upgradeTasksSupplier);
}
private static Upgrade multiTaskUpgrade(String id, Upgrade.MultiTaskSupplier upgradeTasksSupplier) {
return new Upgrade(id, upgradeTasksSupplier);
}
private static List<UpgradeTask> createMenuTasks(ConfigManager configManager, Function<Path, UpgradeTask> menuTaskSupplier) throws UpgradeTaskException {
List<Path> menuFiles = getMenuFiles(configManager);
return CollectionUtils.transform(menuFiles, menuTaskSupplier);
}
private static List<UpgradeTask> createMenuTasks(ConfigManager configManager, Function<Path, UpgradeTask> menuTaskSupplier) throws UpgradeTaskException {
List<Path> menuFiles = getMenuFiles(configManager);
return CollectionUtils.transform(menuFiles, menuTaskSupplier);
}
private static List<Path> getMenuFiles(ConfigManager configManager) throws UpgradeTaskException {
try {
return configManager.getMenuFiles();
} catch (IOException e) {
throw new UpgradeTaskException(Errors.Upgrade.menuListIOException, e);
}
}
private static List<Path> getMenuFiles(ConfigManager configManager) throws UpgradeTaskException {
try {
return configManager.getMenuFiles();
} catch (IOException e) {
throw new UpgradeTaskException(Errors.Upgrade.menuListIOException, e);
}
}
private static String readLegacyCommandSeparator(ConfigManager configManager) {
ConfigLoader settingsConfigLoader = configManager.getConfigLoader("config.yml");
private static String readLegacyCommandSeparator(ConfigManager configManager) {
ConfigLoader settingsConfigLoader = configManager.getConfigLoader("config.yml");
if (!settingsConfigLoader.fileExists()) {
return null;
}
if (!settingsConfigLoader.fileExists()) {
return null;
}
try {
return settingsConfigLoader.load().getString("multiple-commands-separator");
} catch (Throwable t) {
Log.warning("Failed to load \"" + settingsConfigLoader.getFile() + "\", assuming default command separator \";\".");
return null;
}
}
try {
return settingsConfigLoader.load().getString("multiple-commands-separator");
} catch (Throwable t) {
Log.warning("Failed to load \"" + settingsConfigLoader.getFile() + "\", assuming default command separator \";\".");
return null;
}
}
public static ImmutableList<Upgrade> getOrderedUpgrades() {
return orderedUpgrades;
}
public static ImmutableList<Upgrade> getOrderedUpgrades() {
return orderedUpgrades;
}
}

View File

@ -5,8 +5,6 @@
*/
package me.filoghost.chestcommands.legacy;
import me.filoghost.chestcommands.legacy.upgrade.Upgrade;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@ -15,52 +13,53 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import me.filoghost.chestcommands.legacy.upgrade.Upgrade;
public class UpgradesDoneRegistry {
private final Path saveFile;
private final Set<String> upgradesDone;
private boolean needSave;
private final Path saveFile;
private final Set<String> upgradesDone;
private boolean needSave;
public UpgradesDoneRegistry(Path saveFile) throws IOException {
this.saveFile = saveFile;
this.upgradesDone = new HashSet<>();
public UpgradesDoneRegistry(Path saveFile) throws IOException {
this.saveFile = saveFile;
this.upgradesDone = new HashSet<>();
if (Files.isRegularFile(saveFile)) {
try (Stream<String> lines = Files.lines(saveFile)) {
lines.filter(s -> !s.startsWith("#"))
.forEach(upgradesDone::add);
}
}
}
if (Files.isRegularFile(saveFile)) {
try (Stream<String> lines = Files.lines(saveFile)) {
lines.filter(s -> !s.startsWith("#"))
.forEach(upgradesDone::add);
}
}
}
public void setAllDone() {
for (Upgrade upgrade : UpgradeList.getOrderedUpgrades()) {
setDone(upgrade);
}
}
public void setAllDone() {
for (Upgrade upgrade : UpgradeList.getOrderedUpgrades()) {
setDone(upgrade);
}
}
public void setDone(Upgrade upgrade) {
if (upgradesDone.add(upgrade.getID())) {
needSave = true;
}
}
public void setDone(Upgrade upgrade) {
if (upgradesDone.add(upgrade.getID())) {
needSave = true;
}
}
public boolean isDone(Upgrade upgrade) {
return upgradesDone.contains(upgrade.getID());
}
public boolean isDone(Upgrade upgrade) {
return upgradesDone.contains(upgrade.getID());
}
public void save() throws IOException {
if (needSave) {
List<String> lines = new ArrayList<>();
lines.add("#");
lines.add("# WARNING: manually editing this file is not recommended");
lines.add("#");
lines.addAll(upgradesDone);
Files.createDirectories(saveFile.getParent());
Files.write(saveFile, lines);
needSave = false;
}
}
public void save() throws IOException {
if (needSave) {
List<String> lines = new ArrayList<>();
lines.add("#");
lines.add("# WARNING: manually editing this file is not recommended");
lines.add("#");
lines.addAll(upgradesDone);
Files.createDirectories(saveFile.getParent());
Files.write(saveFile, lines);
needSave = false;
}
}
}

View File

@ -5,6 +5,9 @@
*/
package me.filoghost.chestcommands.legacy;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import me.filoghost.chestcommands.config.ConfigManager;
import me.filoghost.chestcommands.legacy.upgrade.Upgrade;
import me.filoghost.chestcommands.legacy.upgrade.UpgradeTask;
@ -13,92 +16,88 @@ import me.filoghost.chestcommands.logging.Errors;
import me.filoghost.fcommons.logging.ErrorCollector;
import me.filoghost.fcommons.logging.Log;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
public class UpgradesExecutor {
private final ConfigManager configManager;
private boolean allUpgradesSuccessful;
private UpgradesDoneRegistry upgradesDoneRegistry;
private final ConfigManager configManager;
private boolean allUpgradesSuccessful;
private UpgradesDoneRegistry upgradesDoneRegistry;
public UpgradesExecutor(ConfigManager configManager) {
this.configManager = configManager;
}
public UpgradesExecutor(ConfigManager configManager) {
this.configManager = configManager;
}
public boolean run(boolean isFreshInstall, ErrorCollector errorCollector) throws UpgradeExecutorException {
this.allUpgradesSuccessful = true;
Path upgradesDoneFile = configManager.getRootDataFolder().resolve(".upgrades-done");
public boolean run(boolean isFreshInstall, ErrorCollector errorCollector) throws UpgradeExecutorException {
this.allUpgradesSuccessful = true;
Path upgradesDoneFile = configManager.getRootDataFolder().resolve(".upgrades-done");
try {
upgradesDoneRegistry = new UpgradesDoneRegistry(upgradesDoneFile);
} catch (IOException e) {
// Upgrades can't proceed if metadata file is not read correctly
throw new UpgradeExecutorException(Errors.Upgrade.metadataReadError(upgradesDoneFile), e);
}
try {
upgradesDoneRegistry = new UpgradesDoneRegistry(upgradesDoneFile);
} catch (IOException e) {
// Upgrades can't proceed if metadata file is not read correctly
throw new UpgradeExecutorException(Errors.Upgrade.metadataReadError(upgradesDoneFile), e);
}
if (isFreshInstall) {
// Mark all currently existing upgrades as already done, assuming default configuration files are up to date
upgradesDoneRegistry.setAllDone();
} else {
// Run missing upgrades
Backup backup = Backup.newTimestampedBackup(configManager.getRootDataFolder());
runMissingUpgrades(backup, errorCollector);
}
if (isFreshInstall) {
// Mark all currently existing upgrades as already done, assuming default configuration files are up to date
upgradesDoneRegistry.setAllDone();
} else {
// Run missing upgrades
Backup backup = Backup.newTimestampedBackup(configManager.getRootDataFolder());
runMissingUpgrades(backup, errorCollector);
}
try {
upgradesDoneRegistry.save();
} catch (IOException e) {
// Upgrades can't proceed if metadata file is not saved correctly
throw new UpgradeExecutorException(Errors.Upgrade.metadataSaveError(upgradesDoneFile), e);
}
try {
upgradesDoneRegistry.save();
} catch (IOException e) {
// Upgrades can't proceed if metadata file is not saved correctly
throw new UpgradeExecutorException(Errors.Upgrade.metadataSaveError(upgradesDoneFile), e);
}
return allUpgradesSuccessful;
}
return allUpgradesSuccessful;
}
private void runMissingUpgrades(Backup backup, ErrorCollector errorCollector) {
for (Upgrade upgrade : UpgradeList.getOrderedUpgrades()) {
if (!upgradesDoneRegistry.isDone(upgrade)) {
boolean allTasksSuccessful = tryRunUpgradeTasks(upgrade, backup, errorCollector);
private void runMissingUpgrades(Backup backup, ErrorCollector errorCollector) {
for (Upgrade upgrade : UpgradeList.getOrderedUpgrades()) {
if (!upgradesDoneRegistry.isDone(upgrade)) {
boolean allTasksSuccessful = tryRunUpgradeTasks(upgrade, backup, errorCollector);
// Consider an upgrade "done" if all its tasks were completed successfully
if (allTasksSuccessful) {
upgradesDoneRegistry.setDone(upgrade);
} else {
allUpgradesSuccessful = false;
}
}
}
}
// Consider an upgrade "done" if all its tasks were completed successfully
if (allTasksSuccessful) {
upgradesDoneRegistry.setDone(upgrade);
} else {
allUpgradesSuccessful = false;
}
}
}
}
private boolean tryRunUpgradeTasks(Upgrade upgrade, Backup backup, ErrorCollector errorCollector) {
boolean allTasksSuccessful = true;
private boolean tryRunUpgradeTasks(Upgrade upgrade, Backup backup, ErrorCollector errorCollector) {
boolean allTasksSuccessful = true;
List<UpgradeTask> upgradeTasks;
try {
upgradeTasks = upgrade.createUpgradeTasks(configManager);
} catch (UpgradeTaskException e) {
errorCollector.add(e, Errors.Upgrade.failedToPrepareUpgradeTasks);
return false;
}
List<UpgradeTask> upgradeTasks;
try {
upgradeTasks = upgrade.createUpgradeTasks(configManager);
} catch (UpgradeTaskException e) {
errorCollector.add(e, Errors.Upgrade.failedToPrepareUpgradeTasks);
return false;
}
for (UpgradeTask upgradeTask : upgradeTasks) {
try {
boolean modified = upgradeTask.runAndBackupIfNecessary(backup);
if (modified) {
Log.info("Automatically upgraded configuration file \"" + upgradeTask.getUpgradedFile() + "\". "
+ "A backup of the old file has been saved.");
}
} catch (UpgradeTaskException e) {
allTasksSuccessful = false;
errorCollector.add(e, Errors.Upgrade.failedSingleUpgrade(upgradeTask.getOriginalFile()));
}
}
for (UpgradeTask upgradeTask : upgradeTasks) {
try {
boolean modified = upgradeTask.runAndBackupIfNecessary(backup);
if (modified) {
Log.info("Automatically upgraded configuration file \"" + upgradeTask.getUpgradedFile() + "\". "
+ "A backup of the old file has been saved.");
}
} catch (UpgradeTaskException e) {
allTasksSuccessful = false;
errorCollector.add(e, Errors.Upgrade.failedSingleUpgrade(upgradeTask.getOriginalFile()));
}
}
return allTasksSuccessful;
}
return allTasksSuccessful;
}
}

View File

@ -11,24 +11,24 @@ import java.util.regex.Pattern;
public class RegexReplacer implements Function<String, String> {
private final Pattern regex;
private final Function<Matcher, String> replaceCallback;
private final Pattern regex;
private final Function<Matcher, String> replaceCallback;
public RegexReplacer(Pattern regex, Function<Matcher, String> replaceCallback) {
this.regex = regex;
this.replaceCallback = replaceCallback;
}
public RegexReplacer(Pattern regex, Function<Matcher, String> replaceCallback) {
this.regex = regex;
this.replaceCallback = replaceCallback;
}
@Override
public String apply(String string) {
Matcher matcher = regex.matcher(string);
StringBuffer output = new StringBuffer();
@Override
public String apply(String string) {
Matcher matcher = regex.matcher(string);
StringBuffer output = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(output, replaceCallback.apply(matcher));
}
matcher.appendTail(output);
while (matcher.find()) {
matcher.appendReplacement(output, replaceCallback.apply(matcher));
}
matcher.appendTail(output);
return output.toString();
}
return output.toString();
}
}

View File

@ -5,10 +5,6 @@
*/
package me.filoghost.chestcommands.legacy.upgrade;
import me.filoghost.fcommons.config.ConfigErrors;
import me.filoghost.fcommons.config.exception.ConfigLoadException;
import me.filoghost.fcommons.config.exception.ConfigSaveException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@ -18,77 +14,80 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import me.filoghost.fcommons.config.ConfigErrors;
import me.filoghost.fcommons.config.exception.ConfigLoadException;
import me.filoghost.fcommons.config.exception.ConfigSaveException;
public abstract class RegexUpgradeTask extends UpgradeTask {
private final Path file;
private List<String> newContents;
private Stream<String> linesStream;
private final Path file;
private List<String> newContents;
private Stream<String> linesStream;
public RegexUpgradeTask(Path file) {
this.file = file;
}
public RegexUpgradeTask(Path file) {
this.file = file;
}
@Override
public final Path getOriginalFile() {
return file;
}
@Override
public final Path getOriginalFile() {
return file;
}
@Override
public final Path getUpgradedFile() {
return file;
}
@Override
public final Path getUpgradedFile() {
return file;
}
@Override
public final void computeChanges() throws ConfigLoadException {
if (!Files.isRegularFile(file)) {
return;
}
@Override
public final void computeChanges() throws ConfigLoadException {
if (!Files.isRegularFile(file)) {
return;
}
List<String> lines;
try {
lines = Files.readAllLines(file);
} catch (IOException e) {
throw new ConfigLoadException(ConfigErrors.readIOException, e);
}
List<String> lines;
try {
lines = Files.readAllLines(file);
} catch (IOException e) {
throw new ConfigLoadException(ConfigErrors.readIOException, e);
}
this.linesStream = lines.stream();
computeRegexChanges();
this.linesStream = lines.stream();
computeRegexChanges();
newContents = linesStream.collect(Collectors.toList());
newContents = linesStream.collect(Collectors.toList());
if (!newContents.equals(lines)) {
setSaveRequired();
}
}
if (!newContents.equals(lines)) {
setSaveRequired();
}
}
@Override
public final void saveChanges() throws ConfigSaveException {
try {
Files.write(file, newContents);
} catch (IOException e) {
throw new ConfigSaveException(ConfigErrors.writeDataIOException, e);
}
}
@Override
public final void saveChanges() throws ConfigSaveException {
try {
Files.write(file, newContents);
} catch (IOException e) {
throw new ConfigSaveException(ConfigErrors.writeDataIOException, e);
}
}
protected abstract void computeRegexChanges();
protected abstract void computeRegexChanges();
protected void replaceString(String target, String replacement) {
replaceRegex(
Pattern.compile(Pattern.quote(target)),
matcher -> replacement
);
}
protected void replaceString(String target, String replacement) {
replaceRegex(
Pattern.compile(Pattern.quote(target)),
matcher -> replacement
);
}
protected void replaceSubNode(String oldNode, String newNode) {
replaceRegex(
Pattern.compile("(^\\s+)" + Pattern.quote(oldNode) + "(:)"),
matcher -> matcher.group(1) + newNode + matcher.group(2)
);
}
protected void replaceSubNode(String oldNode, String newNode) {
replaceRegex(
Pattern.compile("(^\\s+)" + Pattern.quote(oldNode) + "(:)"),
matcher -> matcher.group(1) + newNode + matcher.group(2)
);
}
protected void replaceRegex(Pattern regex, Function<Matcher, String> replaceCallback) {
linesStream = linesStream.map(new RegexReplacer(regex, replaceCallback));
}
protected void replaceRegex(Pattern regex, Function<Matcher, String> replaceCallback) {
linesStream = linesStream.map(new RegexReplacer(regex, replaceCallback));
}
}

View File

@ -5,40 +5,39 @@
*/
package me.filoghost.chestcommands.legacy.upgrade;
import me.filoghost.chestcommands.config.ConfigManager;
import java.util.List;
import me.filoghost.chestcommands.config.ConfigManager;
public class Upgrade {
private final String id;
private final MultiTaskSupplier upgradeTasksSupplier;
private final String id;
private final MultiTaskSupplier upgradeTasksSupplier;
public Upgrade(String id, MultiTaskSupplier taskSupplier) {
this.id = id;
this.upgradeTasksSupplier = taskSupplier;
}
public Upgrade(String id, MultiTaskSupplier taskSupplier) {
this.id = id;
this.upgradeTasksSupplier = taskSupplier;
}
public String getID() {
return id;
}
public String getID() {
return id;
}
public List<UpgradeTask> createUpgradeTasks(ConfigManager configManager) throws UpgradeTaskException {
return upgradeTasksSupplier.getTasks(configManager);
}
public List<UpgradeTask> createUpgradeTasks(ConfigManager configManager) throws UpgradeTaskException {
return upgradeTasksSupplier.getTasks(configManager);
}
@FunctionalInterface
public interface SingleTaskSupplier {
@FunctionalInterface
public interface SingleTaskSupplier {
UpgradeTask getTask(ConfigManager configManager) throws UpgradeTaskException;
UpgradeTask getTask(ConfigManager configManager) throws UpgradeTaskException;
}
}
@FunctionalInterface
public interface MultiTaskSupplier {
@FunctionalInterface
public interface MultiTaskSupplier {
List<UpgradeTask> getTasks(ConfigManager configManager) throws UpgradeTaskException;
List<UpgradeTask> getTasks(ConfigManager configManager) throws UpgradeTaskException;
}
}
}

View File

@ -5,60 +5,59 @@
*/
package me.filoghost.chestcommands.legacy.upgrade;
import java.io.IOException;
import java.nio.file.Path;
import me.filoghost.chestcommands.legacy.Backup;
import me.filoghost.chestcommands.logging.Errors;
import me.filoghost.fcommons.Preconditions;
import me.filoghost.fcommons.config.exception.ConfigLoadException;
import me.filoghost.fcommons.config.exception.ConfigSaveException;
import java.io.IOException;
import java.nio.file.Path;
public abstract class UpgradeTask {
private boolean saveRequired;
private boolean hasRun;
private boolean saveRequired;
private boolean hasRun;
protected void setSaveRequired() {
this.saveRequired = true;
}
protected void setSaveRequired() {
this.saveRequired = true;
}
public boolean runAndBackupIfNecessary(Backup backup) throws UpgradeTaskException {
Preconditions.checkState(!hasRun, "Upgrade task has already run");
hasRun = true;
public boolean runAndBackupIfNecessary(Backup backup) throws UpgradeTaskException {
Preconditions.checkState(!hasRun, "Upgrade task has already run");
hasRun = true;
try {
computeChanges();
} catch (ConfigLoadException e) {
throw new UpgradeTaskException(Errors.Upgrade.loadError(getOriginalFile()), e);
}
try {
computeChanges();
} catch (ConfigLoadException e) {
throw new UpgradeTaskException(Errors.Upgrade.loadError(getOriginalFile()), e);
}
if (saveRequired) {
try {
backup.addFile(getOriginalFile());
} catch (IOException e) {
throw new UpgradeTaskException(Errors.Upgrade.backupError(getOriginalFile()), e);
}
if (saveRequired) {
try {
backup.addFile(getOriginalFile());
} catch (IOException e) {
throw new UpgradeTaskException(Errors.Upgrade.backupError(getOriginalFile()), e);
}
try {
saveChanges();
} catch (ConfigSaveException e) {
throw new UpgradeTaskException(Errors.Upgrade.saveError(getUpgradedFile()), e);
}
try {
saveChanges();
} catch (ConfigSaveException e) {
throw new UpgradeTaskException(Errors.Upgrade.saveError(getUpgradedFile()), e);
}
return true;
return true;
} else {
return false;
}
}
} else {
return false;
}
}
public abstract Path getOriginalFile();
public abstract Path getOriginalFile();
public abstract Path getUpgradedFile();
public abstract Path getUpgradedFile();
protected abstract void computeChanges() throws ConfigLoadException;
protected abstract void computeChanges() throws ConfigLoadException;
protected abstract void saveChanges() throws ConfigSaveException;
protected abstract void saveChanges() throws ConfigSaveException;
}

View File

@ -7,8 +7,8 @@ package me.filoghost.chestcommands.legacy.upgrade;
public class UpgradeTaskException extends Exception {
public UpgradeTaskException(String message, Throwable cause) {
super(message, cause);
}
public UpgradeTaskException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -5,62 +5,61 @@
*/
package me.filoghost.chestcommands.legacy.upgrade;
import java.nio.file.Path;
import me.filoghost.fcommons.config.Config;
import me.filoghost.fcommons.config.ConfigLoader;
import me.filoghost.fcommons.config.exception.ConfigLoadException;
import me.filoghost.fcommons.config.exception.ConfigSaveException;
import java.nio.file.Path;
public abstract class YamlUpgradeTask extends UpgradeTask {
private final ConfigLoader configLoader;
private Config updatedConfig;
private final ConfigLoader configLoader;
private Config updatedConfig;
public YamlUpgradeTask(ConfigLoader configLoader) {
this.configLoader = configLoader;
}
public YamlUpgradeTask(ConfigLoader configLoader) {
this.configLoader = configLoader;
}
@Override
public final Path getOriginalFile() {
return configLoader.getFile();
}
@Override
public final Path getOriginalFile() {
return configLoader.getFile();
}
@Override
public final Path getUpgradedFile() {
return configLoader.getFile();
}
@Override
public final Path getUpgradedFile() {
return configLoader.getFile();
}
@Override
public final void computeChanges() throws ConfigLoadException {
if (!configLoader.fileExists()) {
return;
}
Config config = configLoader.load();
computeYamlChanges(config);
this.updatedConfig = config;
}
@Override
public final void computeChanges() throws ConfigLoadException {
if (!configLoader.fileExists()) {
return;
}
Config config = configLoader.load();
computeYamlChanges(config);
this.updatedConfig = config;
}
@Override
public final void saveChanges() throws ConfigSaveException {
configLoader.save(updatedConfig);
}
@Override
public final void saveChanges() throws ConfigSaveException {
configLoader.save(updatedConfig);
}
protected abstract void computeYamlChanges(Config config);
protected abstract void computeYamlChanges(Config config);
protected void removeNode(Config config, String node) {
if (config.contains(node)) {
config.remove(node);
setSaveRequired();
}
}
protected void removeNode(Config config, String node) {
if (config.contains(node)) {
config.remove(node);
setSaveRequired();
}
}
protected void replaceStringValue(Config settingsConfig, String node, String target, String replacement) {
String value = settingsConfig.getString(node);
if (value.contains(target)) {
settingsConfig.setString(node, value.replace(target, replacement));
setSaveRequired();
}
}
protected void replaceStringValue(Config settingsConfig, String node, String target, String replacement) {
String value = settingsConfig.getString(node);
if (value.contains(target)) {
settingsConfig.setString(node, value.replace(target, replacement));
setSaveRequired();
}
}
}

View File

@ -11,15 +11,15 @@ import me.filoghost.fcommons.config.Config;
public class v4_0_LangUpgradeTask extends YamlUpgradeTask {
public v4_0_LangUpgradeTask(ConfigManager configManager) {
super(configManager.getConfigLoader("lang.yml"));
}
public v4_0_LangUpgradeTask(ConfigManager configManager) {
super(configManager.getConfigLoader("lang.yml"));
}
@Override
public void computeYamlChanges(Config settingsConfig) {
removeNode(settingsConfig, "open-menu");
removeNode(settingsConfig, "open-menu-others");
replaceStringValue(settingsConfig, "no-required-item", "{datavalue}", "{durability}");
}
@Override
public void computeYamlChanges(Config settingsConfig) {
removeNode(settingsConfig, "open-menu");
removeNode(settingsConfig, "open-menu-others");
replaceStringValue(settingsConfig, "no-required-item", "{datavalue}", "{durability}");
}
}

View File

@ -5,29 +5,28 @@
*/
package me.filoghost.chestcommands.legacy.v4_0;
import java.nio.file.Path;
import me.filoghost.chestcommands.legacy.upgrade.RegexUpgradeTask;
import me.filoghost.chestcommands.parsing.icon.AttributeType;
import java.nio.file.Path;
public class v4_0_MenuNodeRenameUpgradeTask extends RegexUpgradeTask {
public v4_0_MenuNodeRenameUpgradeTask(Path menuFile) {
super(menuFile);
}
@Override
protected void computeRegexChanges() {
replaceSubNode("command", "commands");
replaceSubNode("open-action", "open-actions");
replaceSubNode("id", "material");
public v4_0_MenuNodeRenameUpgradeTask(Path menuFile) {
super(menuFile);
}
@Override
protected void computeRegexChanges() {
replaceSubNode("command", "commands");
replaceSubNode("open-action", "open-actions");
replaceSubNode("id", "material");
replaceSubNode("ID", AttributeType.MATERIAL.getAttributeName());
replaceSubNode("DATA-VALUE", AttributeType.DURABILITY.getAttributeName());
replaceSubNode("NBT", AttributeType.NBT_DATA.getAttributeName());
replaceSubNode("ENCHANTMENT", AttributeType.ENCHANTMENTS.getAttributeName());
replaceSubNode("COMMAND", AttributeType.ACTIONS.getAttributeName());
replaceSubNode("COMMANDS", AttributeType.ACTIONS.getAttributeName());
replaceSubNode("REQUIRED-ITEM", AttributeType.REQUIRED_ITEMS.getAttributeName());
}
replaceSubNode("ID", AttributeType.MATERIAL.getAttributeName());
replaceSubNode("DATA-VALUE", AttributeType.DURABILITY.getAttributeName());
replaceSubNode("NBT", AttributeType.NBT_DATA.getAttributeName());
replaceSubNode("ENCHANTMENT", AttributeType.ENCHANTMENTS.getAttributeName());
replaceSubNode("COMMAND", AttributeType.ACTIONS.getAttributeName());
replaceSubNode("COMMANDS", AttributeType.ACTIONS.getAttributeName());
replaceSubNode("REQUIRED-ITEM", AttributeType.REQUIRED_ITEMS.getAttributeName());
}
}

View File

@ -5,6 +5,11 @@
*/
package me.filoghost.chestcommands.legacy.v4_0;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
import me.filoghost.chestcommands.config.ConfigManager;
import me.filoghost.chestcommands.legacy.upgrade.YamlUpgradeTask;
import me.filoghost.chestcommands.parsing.icon.AttributeType;
@ -14,154 +19,148 @@ import me.filoghost.fcommons.config.Config;
import me.filoghost.fcommons.config.ConfigSection;
import me.filoghost.fcommons.config.ConfigValueType;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
public class v4_0_MenuReformatUpgradeTask extends YamlUpgradeTask {
private final String legacyCommandSeparator;
private final String legacyCommandSeparator;
public v4_0_MenuReformatUpgradeTask(ConfigManager configManager, Path menuFile, String legacyCommandSeparator) {
super(configManager.getConfigLoader(menuFile));
this.legacyCommandSeparator = legacyCommandSeparator;
}
public v4_0_MenuReformatUpgradeTask(ConfigManager configManager, Path menuFile, String legacyCommandSeparator) {
super(configManager.getConfigLoader(menuFile));
this.legacyCommandSeparator = legacyCommandSeparator;
}
@Override
public void computeYamlChanges(Config menuConfig) {
menuConfig.setHeader(null);
@Override
public void computeYamlChanges(Config menuConfig) {
menuConfig.setHeader(null);
for (String key : menuConfig.getKeys()) {
ConfigSection section = menuConfig.getConfigSection(key);
if (section == null) {
continue;
}
for (String key : menuConfig.getKeys()) {
ConfigSection section = menuConfig.getConfigSection(key);
if (section == null) {
continue;
}
if (key.equals(MenuSettingsNode.ROOT_SECTION)) {
upgradeMenuSettings(section);
} else {
upgradeIcon(section);
}
}
}
if (key.equals(MenuSettingsNode.ROOT_SECTION)) {
upgradeMenuSettings(section);
} else {
upgradeIcon(section);
}
}
}
private void upgradeMenuSettings(ConfigSection section) {
expandInlineList(section, MenuSettingsNode.COMMANDS, ";");
expandInlineList(section, MenuSettingsNode.OPEN_ACTIONS, legacyCommandSeparator);
updateActionPrefixes(section, MenuSettingsNode.OPEN_ACTIONS);
}
private void upgradeMenuSettings(ConfigSection section) {
expandInlineList(section, MenuSettingsNode.COMMANDS, ";");
expandInlineList(section, MenuSettingsNode.OPEN_ACTIONS, legacyCommandSeparator);
updateActionPrefixes(section, MenuSettingsNode.OPEN_ACTIONS);
}
private void upgradeIcon(ConfigSection section) {
expandInlineList(section, AttributeType.ENCHANTMENTS.getAttributeName(), ";");
expandInlineList(section, AttributeType.ACTIONS.getAttributeName(), legacyCommandSeparator);
updateActionPrefixes(section, AttributeType.ACTIONS.getAttributeName());
expandSingletonList(section, AttributeType.REQUIRED_ITEMS.getAttributeName());
expandInlineItemstack(section);
}
private void upgradeIcon(ConfigSection section) {
expandInlineList(section, AttributeType.ENCHANTMENTS.getAttributeName(), ";");
expandInlineList(section, AttributeType.ACTIONS.getAttributeName(), legacyCommandSeparator);
updateActionPrefixes(section, AttributeType.ACTIONS.getAttributeName());
expandSingletonList(section, AttributeType.REQUIRED_ITEMS.getAttributeName());
expandInlineItemstack(section);
}
private void updateActionPrefixes(ConfigSection config, String node) {
List<String> actions = config.getStringList(node);
if (actions == null) {
return;
}
private void updateActionPrefixes(ConfigSection config, String node) {
List<String> actions = config.getStringList(node);
if (actions == null) {
return;
}
for (int i = 0; i < actions.size(); i++) {
String oldAction = actions.get(i);
String newAction = oldAction;
newAction = replacePrefix(newAction, "menu:", "open:");
newAction = replacePrefix(newAction, "givemoney:", "give-money:");
newAction = replacePrefix(newAction, "dragonbar:", "dragon-bar:");
newAction = replacePrefix(newAction, "server ", "server: ");
for (int i = 0; i < actions.size(); i++) {
String oldAction = actions.get(i);
String newAction = oldAction;
newAction = replacePrefix(newAction, "menu:", "open:");
newAction = replacePrefix(newAction, "givemoney:", "give-money:");
newAction = replacePrefix(newAction, "dragonbar:", "dragon-bar:");
newAction = replacePrefix(newAction, "server ", "server: ");
if (!newAction.equals(oldAction)) {
setSaveRequired();
actions.set(i, newAction);
}
}
if (!newAction.equals(oldAction)) {
setSaveRequired();
actions.set(i, newAction);
}
}
config.setStringList(node, actions);
}
config.setStringList(node, actions);
}
private String replacePrefix(String action, String oldPrefix, String newPrefix) {
if (action.startsWith(oldPrefix)) {
setSaveRequired();
return newPrefix + action.substring(oldPrefix.length());
} else {
return action;
}
}
private String replacePrefix(String action, String oldPrefix, String newPrefix) {
if (action.startsWith(oldPrefix)) {
setSaveRequired();
return newPrefix + action.substring(oldPrefix.length());
} else {
return action;
}
}
private void expandInlineItemstack(ConfigSection section) {
String material = section.getString(AttributeType.MATERIAL.getAttributeName());
if (material == null) {
return;
}
private void expandInlineItemstack(ConfigSection section) {
String material = section.getString(AttributeType.MATERIAL.getAttributeName());
if (material == null) {
return;
}
if (material.contains(",")) {
String[] parts = Strings.trimmedSplit(material, ",", 2);
if (!section.contains(AttributeType.AMOUNT.getAttributeName())) {
try {
section.setInt(AttributeType.AMOUNT.getAttributeName(), Integer.parseInt(parts[1]));
} catch (NumberFormatException e) {
section.setString(AttributeType.AMOUNT.getAttributeName(), parts[1]);
}
}
material = parts[0];
section.setString(AttributeType.MATERIAL.getAttributeName(), material);
setSaveRequired();
}
if (material.contains(",")) {
String[] parts = Strings.trimmedSplit(material, ",", 2);
if (!section.contains(AttributeType.AMOUNT.getAttributeName())) {
try {
section.setInt(AttributeType.AMOUNT.getAttributeName(), Integer.parseInt(parts[1]));
} catch (NumberFormatException e) {
section.setString(AttributeType.AMOUNT.getAttributeName(), parts[1]);
}
}
material = parts[0];
section.setString(AttributeType.MATERIAL.getAttributeName(), material);
setSaveRequired();
}
if (material.contains(":")) {
String[] parts = Strings.trimmedSplit(material, ":", 2);
if (!section.contains(AttributeType.DURABILITY.getAttributeName())) {
try {
section.setInt(AttributeType.DURABILITY.getAttributeName(), Integer.parseInt(parts[1]));
} catch (NumberFormatException e) {
section.setString(AttributeType.DURABILITY.getAttributeName(), parts[1]);
}
}
material = parts[0];
section.setString(AttributeType.MATERIAL.getAttributeName(), material);
setSaveRequired();
}
}
if (material.contains(":")) {
String[] parts = Strings.trimmedSplit(material, ":", 2);
if (!section.contains(AttributeType.DURABILITY.getAttributeName())) {
try {
section.setInt(AttributeType.DURABILITY.getAttributeName(), Integer.parseInt(parts[1]));
} catch (NumberFormatException e) {
section.setString(AttributeType.DURABILITY.getAttributeName(), parts[1]);
}
}
material = parts[0];
section.setString(AttributeType.MATERIAL.getAttributeName(), material);
setSaveRequired();
}
}
private void expandInlineList(ConfigSection config, String node, String separator) {
if (config.get(node).isValidAs(ConfigValueType.STRING)) {
config.setStringList(node, splitListElements(config.getString(node), separator));
setSaveRequired();
}
}
private void expandInlineList(ConfigSection config, String node, String separator) {
if (config.get(node).isValidAs(ConfigValueType.STRING)) {
config.setStringList(node, splitListElements(config.getString(node), separator));
setSaveRequired();
}
}
private void expandSingletonList(ConfigSection config, String node) {
if (config.get(node).isValidAs(ConfigValueType.STRING)) {
config.setStringList(node, Collections.singletonList(config.getString(node)));
setSaveRequired();
}
}
private void expandSingletonList(ConfigSection config, String node) {
if (config.get(node).isValidAs(ConfigValueType.STRING)) {
config.setStringList(node, Collections.singletonList(config.getString(node)));
setSaveRequired();
}
}
private List<String> splitListElements(String input, String separator) {
if (separator == null || separator.length() == 0) {
separator = ";";
}
private List<String> splitListElements(String input, String separator) {
if (separator == null || separator.length() == 0) {
separator = ";";
}
String[] splitValues = Strings.trimmedSplit(input, Pattern.quote(separator));
List<String> values = new ArrayList<>();
String[] splitValues = Strings.trimmedSplit(input, Pattern.quote(separator));
List<String> values = new ArrayList<>();
for (String value : splitValues) {
if (!value.isEmpty()) {
values.add(value);
}
}
for (String value : splitValues) {
if (!value.isEmpty()) {
values.add(value);
}
}
// Return a list with an empty value to avoid displaying the empty list value "[]" in the YML file
if (values.isEmpty()) {
values.add("");
}
// Return a list with an empty value to avoid displaying the empty list value "[]" in the YML file
if (values.isEmpty()) {
values.add("");
}
return values;
}
return values;
}
}

View File

@ -5,6 +5,10 @@
*/
package me.filoghost.chestcommands.legacy.v4_0;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import me.filoghost.chestcommands.config.ConfigManager;
import me.filoghost.chestcommands.legacy.upgrade.UpgradeTask;
import me.filoghost.fcommons.Strings;
@ -15,89 +19,84 @@ import me.filoghost.fcommons.config.exception.ConfigLoadException;
import me.filoghost.fcommons.config.exception.ConfigSaveException;
import org.apache.commons.lang.StringEscapeUtils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class v4_0_PlaceholdersUpgradeTask extends UpgradeTask {
private final Path oldPlaceholdersFile;
private final ConfigLoader newPlaceholdersConfigLoader;
private Config updatedConfig;
private final Path oldPlaceholdersFile;
private final ConfigLoader newPlaceholdersConfigLoader;
private Config updatedConfig;
public v4_0_PlaceholdersUpgradeTask(ConfigManager configManager) {
this.oldPlaceholdersFile = configManager.getRootDataFolder().resolve("placeholders.yml");
this.newPlaceholdersConfigLoader = configManager.getConfigLoader("custom-placeholders.yml");
}
public v4_0_PlaceholdersUpgradeTask(ConfigManager configManager) {
this.oldPlaceholdersFile = configManager.getRootDataFolder().resolve("placeholders.yml");
this.newPlaceholdersConfigLoader = configManager.getConfigLoader("custom-placeholders.yml");
}
@Override
public Path getOriginalFile() {
return oldPlaceholdersFile;
}
@Override
public Path getOriginalFile() {
return oldPlaceholdersFile;
}
@Override
public Path getUpgradedFile() {
return newPlaceholdersConfigLoader.getFile();
}
@Override
public Path getUpgradedFile() {
return newPlaceholdersConfigLoader.getFile();
}
@Override
public void computeChanges() throws ConfigLoadException {
if (!Files.isRegularFile(oldPlaceholdersFile)) {
return;
}
@Override
public void computeChanges() throws ConfigLoadException {
if (!Files.isRegularFile(oldPlaceholdersFile)) {
return;
}
// Do NOT load the new placeholder configuration from disk, as it should only contain placeholders imported from the old file
Config newPlaceholdersConfig = new Config(newPlaceholdersConfigLoader.getFile());
List<String> lines;
try {
lines = Files.readAllLines(oldPlaceholdersFile);
} catch (IOException e) {
throw new ConfigLoadException(ConfigErrors.readIOException, e);
}
// Do NOT load the new placeholder configuration from disk, as it should only contain placeholders imported from the old file
Config newPlaceholdersConfig = new Config(newPlaceholdersConfigLoader.getFile());
List<String> lines;
try {
lines = Files.readAllLines(oldPlaceholdersFile);
} catch (IOException e) {
throw new ConfigLoadException(ConfigErrors.readIOException, e);
}
for (String line : lines) {
// Comment or empty line
if (line.isEmpty() || line.startsWith("#")) {
continue;
}
for (String line : lines) {
// Comment or empty line
if (line.isEmpty() || line.startsWith("#")) {
continue;
}
// Ignore bad line
if (!line.contains(":")) {
continue;
}
// Ignore bad line
if (!line.contains(":")) {
continue;
}
String[] parts = Strings.trimmedSplit(line, ":", 2);
String placeholder = unquote(parts[0]);
String replacement = StringEscapeUtils.unescapeJava(unquote(parts[1]));
String[] parts = Strings.trimmedSplit(line, ":", 2);
String placeholder = unquote(parts[0]);
String replacement = StringEscapeUtils.unescapeJava(unquote(parts[1]));
newPlaceholdersConfig.setString("placeholders." + placeholder, replacement);
setSaveRequired();
}
newPlaceholdersConfig.setString("placeholders." + placeholder, replacement);
setSaveRequired();
}
this.updatedConfig = newPlaceholdersConfig;
}
this.updatedConfig = newPlaceholdersConfig;
}
@Override
public void saveChanges() throws ConfigSaveException {
try {
Files.deleteIfExists(oldPlaceholdersFile);
} catch (IOException ignored) {}
newPlaceholdersConfigLoader.save(updatedConfig);
}
@Override
public void saveChanges() throws ConfigSaveException {
try {
Files.deleteIfExists(oldPlaceholdersFile);
} catch (IOException ignored) {}
newPlaceholdersConfigLoader.save(updatedConfig);
}
private static String unquote(String input) {
if (input.length() < 2) {
// Too short, cannot be a quoted string
return input;
}
if (input.startsWith("'") && input.endsWith("'")) {
return input.substring(1, input.length() - 1);
} else if (input.startsWith("\"") && input.endsWith("\"")) {
return input.substring(1, input.length() - 1);
}
private static String unquote(String input) {
if (input.length() < 2) {
// Too short, cannot be a quoted string
return input;
}
if (input.startsWith("'") && input.endsWith("'")) {
return input.substring(1, input.length() - 1);
} else if (input.startsWith("\"") && input.endsWith("\"")) {
return input.substring(1, input.length() - 1);
}
return input;
}
return input;
}
}

View File

@ -11,15 +11,15 @@ import me.filoghost.fcommons.config.Config;
public class v4_0_SettingsUpgradeTask extends YamlUpgradeTask {
public v4_0_SettingsUpgradeTask(ConfigManager configManager) {
super(configManager.getConfigLoader("config.yml"));
}
public v4_0_SettingsUpgradeTask(ConfigManager configManager) {
super(configManager.getConfigLoader("config.yml"));
}
@Override
public void computeYamlChanges(Config settingsConfig) {
removeNode(settingsConfig, "use-only-commands-without-args");
removeNode(settingsConfig, "use-console-colors");
removeNode(settingsConfig, "multiple-commands-separator");
}
@Override
public void computeYamlChanges(Config settingsConfig) {
removeNode(settingsConfig, "use-only-commands-without-args");
removeNode(settingsConfig, "use-console-colors");
removeNode(settingsConfig, "multiple-commands-separator");
}
}

View File

@ -13,40 +13,40 @@ import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
public class CommandListener implements Listener {
private final MenuManager menuManager;
public CommandListener(MenuManager menuManager) {
this.menuManager = menuManager;
}
private final MenuManager menuManager;
public CommandListener(MenuManager menuManager) {
this.menuManager = menuManager;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onCommand(PlayerCommandPreprocessEvent event) {
String command = getCommandName(event.getMessage());
if (command == null) {
return;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onCommand(PlayerCommandPreprocessEvent event) {
String command = getCommandName(event.getMessage());
if (command == null) {
return;
}
InternalMenu menu = menuManager.getMenuByOpenCommand(command);
if (menu == null) {
return;
}
event.setCancelled(true);
menu.openCheckingPermission(event.getPlayer());
}
private static String getCommandName(String fullCommand) {
if (!fullCommand.startsWith("/")) {
return null;
}
int firstSpace = fullCommand.indexOf(' ');
if (firstSpace >= 1) {
return fullCommand.substring(1, firstSpace);
} else {
return fullCommand.substring(1);
}
}
InternalMenu menu = menuManager.getMenuByOpenCommand(command);
if (menu == null) {
return;
}
event.setCancelled(true);
menu.openCheckingPermission(event.getPlayer());
}
private static String getCommandName(String fullCommand) {
if (!fullCommand.startsWith("/")) {
return null;
}
int firstSpace = fullCommand.indexOf(' ');
if (firstSpace >= 1) {
return fullCommand.substring(1, firstSpace);
} else {
return fullCommand.substring(1);
}
}
}

View File

@ -5,6 +5,8 @@
*/
package me.filoghost.chestcommands.listener;
import java.util.Map;
import java.util.WeakHashMap;
import me.filoghost.chestcommands.ChestCommands;
import me.filoghost.chestcommands.api.ClickResult;
import me.filoghost.chestcommands.api.Icon;
@ -21,73 +23,70 @@ import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.Inventory;
import java.util.Map;
import java.util.WeakHashMap;
public class InventoryListener implements Listener {
private final MenuManager menuManager;
private final Map<Player, Long> antiClickSpam;
private final MenuManager menuManager;
private final Map<Player, Long> antiClickSpam;
public InventoryListener(MenuManager menuManager) {
this.menuManager = menuManager;
this.antiClickSpam = new WeakHashMap<>();
}
public InventoryListener(MenuManager menuManager) {
this.menuManager = menuManager;
this.antiClickSpam = new WeakHashMap<>();
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false)
public void onInteract(PlayerInteractEvent event) {
if (event.hasItem() && event.getAction() != Action.PHYSICAL) {
menuManager.openMenuByItem(event.getPlayer(), event.getItem(), event.getAction());
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false)
public void onEarlyInventoryClick(InventoryClickEvent event) {
if (MenuManager.isMenuInventory(event.getInventory())) {
// Cancel the event as early as possible
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false)
public void onLateInventoryClick(InventoryClickEvent event) {
Inventory inventory = event.getInventory();
DefaultMenuView menuView = MenuManager.getOpenMenuView(inventory);
if (menuView == null) {
return;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false)
public void onInteract(PlayerInteractEvent event) {
if (event.hasItem() && event.getAction() != Action.PHYSICAL) {
menuManager.openMenuByItem(event.getPlayer(), event.getItem(), event.getAction());
}
}
// Cancel the event again just in case a plugin un-cancels it
event.setCancelled(true);
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false)
public void onEarlyInventoryClick(InventoryClickEvent event) {
if (MenuManager.isMenuInventory(event.getInventory())) {
// Cancel the event as early as possible
event.setCancelled(true);
}
}
int slot = event.getRawSlot();
Player clicker = (Player) event.getWhoClicked();
Icon icon = menuView.getIcon(slot);
if (icon == null) {
return;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false)
public void onLateInventoryClick(InventoryClickEvent event) {
Inventory inventory = event.getInventory();
DefaultMenuView menuView = MenuManager.getOpenMenuView(inventory);
if (menuView == null) {
return;
}
Long cooldownUntil = antiClickSpam.get(clicker);
long now = System.currentTimeMillis();
int minDelay = Settings.anti_click_spam_delay;
// Cancel the event again just in case a plugin un-cancels it
event.setCancelled(true);
if (minDelay > 0) {
if (cooldownUntil != null && cooldownUntil > now) {
return;
} else {
antiClickSpam.put(clicker, now + minDelay);
}
}
int slot = event.getRawSlot();
Player clicker = (Player) event.getWhoClicked();
Icon icon = menuView.getIcon(slot);
if (icon == null) {
return;
}
// Only handle the click AFTER the event has finished
Bukkit.getScheduler().runTask(ChestCommands.getPluginInstance(), () -> {
ClickResult result = icon.onClick(menuView, clicker);
Long cooldownUntil = antiClickSpam.get(clicker);
long now = System.currentTimeMillis();
int minDelay = Settings.anti_click_spam_delay;
if (result == ClickResult.CLOSE) {
clicker.closeInventory();
}
});
}
if (minDelay > 0) {
if (cooldownUntil != null && cooldownUntil > now) {
return;
} else {
antiClickSpam.put(clicker, now + minDelay);
}
}
// Only handle the click AFTER the event has finished
Bukkit.getScheduler().runTask(ChestCommands.getPluginInstance(), () -> {
ClickResult result = icon.onClick(menuView, clicker);
if (result == ClickResult.CLOSE) {
clicker.closeInventory();
}
});
}
}

View File

@ -16,20 +16,20 @@ import org.bukkit.event.player.PlayerJoinEvent;
public class JoinListener implements Listener {
@EventHandler
public void onJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
@EventHandler
public void onJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
if (ChestCommands.getLastLoadErrors().hasErrors() && player.hasPermission(Permissions.SEE_ERRORS)) {
player.sendMessage(
ChestCommands.CHAT_PREFIX + ChatColor.RED + "The plugin found " + ChestCommands.getLastLoadErrors().getErrorsCount()
+ " error(s) last time it was loaded. You can see them by doing \"/cc reload\" in the console.");
}
if (ChestCommands.getLastLoadErrors().hasErrors() && player.hasPermission(Permissions.SEE_ERRORS)) {
player.sendMessage(
ChestCommands.CHAT_PREFIX + ChatColor.RED + "The plugin found " + ChestCommands.getLastLoadErrors().getErrorsCount()
+ " error(s) last time it was loaded. You can see them by doing \"/cc reload\" in the console.");
}
if (ChestCommands.hasNewVersion() && Settings.update_notifications && player.hasPermission(Permissions.UPDATE_NOTIFICATIONS)) {
player.sendMessage(ChestCommands.CHAT_PREFIX + "Found an update: " + ChestCommands.getNewVersion() + ". Download:");
player.sendMessage(ChatColor.DARK_GREEN + ">> " + ChatColor.GREEN + "http://dev.bukkit.org/bukkit-plugins/chest-commands");
}
}
if (ChestCommands.hasNewVersion() && Settings.update_notifications && player.hasPermission(Permissions.UPDATE_NOTIFICATIONS)) {
player.sendMessage(ChestCommands.CHAT_PREFIX + "Found an update: " + ChestCommands.getNewVersion() + ". Download:");
player.sendMessage(ChatColor.DARK_GREEN + ">> " + ChatColor.GREEN + "http://dev.bukkit.org/bukkit-plugins/chest-commands");
}
}
}

View File

@ -22,97 +22,97 @@ import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
public class SignListener implements Listener {
private static final int HEADER_LINE = 0;
private static final int FILENAME_LINE = 1;
private static final String SIGN_CREATION_TRIGGER = "[menu]";
private static final ChatColor VALID_SIGN_COLOR = ChatColor.DARK_BLUE;
private static final String VALID_SIGN_HEADER = VALID_SIGN_COLOR + SIGN_CREATION_TRIGGER;
private final MenuManager menuManager;
public SignListener(MenuManager menuManager) {
this.menuManager = menuManager;
}
private static final int HEADER_LINE = 0;
private static final int FILENAME_LINE = 1;
private static final String SIGN_CREATION_TRIGGER = "[menu]";
private static final ChatColor VALID_SIGN_COLOR = ChatColor.DARK_BLUE;
private static final String VALID_SIGN_HEADER = VALID_SIGN_COLOR + SIGN_CREATION_TRIGGER;
private final MenuManager menuManager;
public SignListener(MenuManager menuManager) {
this.menuManager = menuManager;
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onSignClick(PlayerInteractEvent event) {
if (event.getAction() != Action.RIGHT_CLICK_BLOCK) {
return;
}
BlockState clickedBlockState = event.getClickedBlock().getState();
if (!(clickedBlockState instanceof Sign)) {
return;
}
Sign sign = (Sign) clickedBlockState;
if (!sign.getLine(HEADER_LINE).equalsIgnoreCase(VALID_SIGN_HEADER)) {
return;
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onSignClick(PlayerInteractEvent event) {
if (event.getAction() != Action.RIGHT_CLICK_BLOCK) {
return;
}
BlockState clickedBlockState = event.getClickedBlock().getState();
if (!(clickedBlockState instanceof Sign)) {
return;
}
Sign sign = (Sign) clickedBlockState;
if (!sign.getLine(HEADER_LINE).equalsIgnoreCase(VALID_SIGN_HEADER)) {
return;
}
String menuFileName = Utils.addYamlExtension(sign.getLine(FILENAME_LINE).trim());
InternalMenu menu = menuManager.getMenuByFileName(menuFileName);
if (menu == null) {
event.getPlayer().sendMessage(Lang.menu_not_found);
return;
}
menu.openCheckingPermission(event.getPlayer());
}
String menuFileName = Utils.addYamlExtension(sign.getLine(FILENAME_LINE).trim());
InternalMenu menu = menuManager.getMenuByFileName(menuFileName);
if (menu == null) {
event.getPlayer().sendMessage(Lang.menu_not_found);
return;
}
menu.openCheckingPermission(event.getPlayer());
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreateMenuSign(SignChangeEvent event) {
Player player = event.getPlayer();
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreateMenuSign(SignChangeEvent event) {
Player player = event.getPlayer();
if (isCreatingMenuSign(event.getLine(HEADER_LINE)) && canCreateMenuSign(player)) {
String menuFileName = event.getLine(FILENAME_LINE).trim();
if (menuFileName.isEmpty()) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "You must write a menu name in the second line.");
return;
}
menuFileName = Utils.addYamlExtension(menuFileName);
InternalMenu menu = menuManager.getMenuByFileName(menuFileName);
if (menu == null) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "Menu \"" + menuFileName + "\" was not found.");
return;
}
event.setLine(HEADER_LINE, VALID_SIGN_COLOR + event.getLine(HEADER_LINE));
player.sendMessage(ChatColor.GREEN + "Successfully created a sign for the menu " + menuFileName + ".");
}
}
if (isCreatingMenuSign(event.getLine(HEADER_LINE)) && canCreateMenuSign(player)) {
String menuFileName = event.getLine(FILENAME_LINE).trim();
if (menuFileName.isEmpty()) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "You must write a menu name in the second line.");
return;
}
menuFileName = Utils.addYamlExtension(menuFileName);
InternalMenu menu = menuManager.getMenuByFileName(menuFileName);
if (menu == null) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "Menu \"" + menuFileName + "\" was not found.");
return;
}
event.setLine(HEADER_LINE, VALID_SIGN_COLOR + event.getLine(HEADER_LINE));
player.sendMessage(ChatColor.GREEN + "Successfully created a sign for the menu " + menuFileName + ".");
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onSignChangeMonitor(SignChangeEvent event) {
// Prevent players without permissions from creating menu signs
if (isValidMenuSign(event.getLine(HEADER_LINE)) && !canCreateMenuSign(event.getPlayer())) {
event.setLine(HEADER_LINE, ChatColor.stripColor(event.getLine(HEADER_LINE)));
}
}
private boolean isCreatingMenuSign(String headerLine) {
return headerLine.equalsIgnoreCase(SIGN_CREATION_TRIGGER);
}
private boolean isValidMenuSign(String headerLine) {
return headerLine.equalsIgnoreCase(VALID_SIGN_HEADER);
}
private boolean canCreateMenuSign(Player player) {
return player.hasPermission(Permissions.SIGN_CREATE);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onSignChangeMonitor(SignChangeEvent event) {
// Prevent players without permissions from creating menu signs
if (isValidMenuSign(event.getLine(HEADER_LINE)) && !canCreateMenuSign(event.getPlayer())) {
event.setLine(HEADER_LINE, ChatColor.stripColor(event.getLine(HEADER_LINE)));
}
}
private boolean isCreatingMenuSign(String headerLine) {
return headerLine.equalsIgnoreCase(SIGN_CREATION_TRIGGER);
}
private boolean isValidMenuSign(String headerLine) {
return headerLine.equalsIgnoreCase(VALID_SIGN_HEADER);
}
private boolean canCreateMenuSign(Player player) {
return player.hasPermission(Permissions.SIGN_CREATE);
}
}

View File

@ -9,32 +9,32 @@ import java.util.List;
class ErrorPrintInfo {
private final int index;
private final List<String> message;
private final String details;
private final Throwable cause;
private final int index;
private final List<String> message;
private final String details;
private final Throwable cause;
public ErrorPrintInfo(int index, List<String> message, String details, Throwable cause) {
this.index = index;
this.message = message;
this.details = details;
this.cause = cause;
}
public ErrorPrintInfo(int index, List<String> message, String details, Throwable cause) {
this.index = index;
this.message = message;
this.details = details;
this.cause = cause;
}
public int getIndex() {
return index;
}
public int getIndex() {
return index;
}
public List<String> getMessage() {
return message;
}
public List<String> getMessage() {
return message;
}
public String getDetails() {
return details;
}
public String getDetails() {
return details;
}
public Throwable getCause() {
return cause;
}
public Throwable getCause() {
return cause;
}
}

Some files were not shown because too many files have changed in this diff Show More