Merge pull request #58 from filoghost/v4

Merge v4 update
This commit is contained in:
filoghost 2020-08-16 16:24:28 +02:00 committed by GitHub
commit 6bd0c916c4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
279 changed files with 10387 additions and 6017 deletions

View File

@ -5,7 +5,7 @@ labels: Bug
---
<!--
⚠️ READ BELOW BEFOR SUBMITTING ⚠️
⚠️ READ BELOW BEFORE SUBMITTING ⚠️
Before opening a bug report:
* Read the FAQ: https://filoghost.me/docs/chest-commands/faq

View File

@ -5,7 +5,7 @@ labels: Enhancement
---
<!--
⚠️ READ BELOW BEFOR SUBMITTING ⚠️
⚠️ READ BELOW BEFORE SUBMITTING ⚠️
Please only suggest changes that would benefit many users, not just a specific situation.

View File

@ -5,7 +5,7 @@ labels: Help
---
<!--
⚠️ READ BELOW BEFOR SUBMITTING ⚠️
⚠️ READ BELOW BEFORE SUBMITTING ⚠️
Before asking for help:
* Read the documentation: https://filoghost.me/docs/chest-commands

View File

@ -5,7 +5,7 @@ labels: Documentation
---
<!--
⚠️ READ BELOW BEFOR SUBMITTING ⚠️
⚠️ READ BELOW BEFORE SUBMITTING ⚠️
You MUST fill out the template below, without modifying or deleting the existing text, otherwise the issue will be automatically closed.

View File

@ -1,126 +0,0 @@
<?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>
<parent>
<groupId>com.gmail.filoghost.chestcommands</groupId>
<artifactId>chestcommands-parent</artifactId>
<version>3.3.1</version>
</parent>
<artifactId>chestcommands-plugin</artifactId>
<name>ChestCommands Plugin</name>
<repositories>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
</repository>
<repository>
<id>vault-repo</id>
<url>http://nexus.hc.to/content/repositories/pub_releases</url>
</repository>
<repository>
<id>confuser-repo</id>
<url>https://ci.frostcast.net/plugin/repository/everything/</url>
</repository>
<repository>
<id>bstats-repo</id>
<url>https://repo.codemc.org/repository/maven-public/</url>
</repository>
<repository>
<id>placeholderapi-repo</id>
<url>http://repo.extendedclip.com/content/repositories/placeholderapi/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>${spigot-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.6</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>me.confuser</groupId>
<artifactId>BarAPI</artifactId>
<version>3.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.9.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit-lite</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
<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>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/</exclude>
</excludes>
</filter>
</filters>
<relocations>
<relocation>
<pattern>org.bstats</pattern>
<shadedPattern>com.gmail.filoghost.chestcommands.metrics</shadedPattern>
</relocation>
</relocations>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,323 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands;
import com.gmail.filoghost.chestcommands.SimpleUpdater.ResponseHandler;
import com.gmail.filoghost.chestcommands.bridge.BarAPIBridge;
import com.gmail.filoghost.chestcommands.bridge.EconomyBridge;
import com.gmail.filoghost.chestcommands.bridge.PlaceholderAPIBridge;
import com.gmail.filoghost.chestcommands.command.CommandHandler;
import com.gmail.filoghost.chestcommands.command.framework.CommandFramework;
import com.gmail.filoghost.chestcommands.config.AsciiPlaceholders;
import com.gmail.filoghost.chestcommands.config.Lang;
import com.gmail.filoghost.chestcommands.config.Settings;
import com.gmail.filoghost.chestcommands.config.yaml.PluginConfig;
import com.gmail.filoghost.chestcommands.internal.BoundItem;
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
import com.gmail.filoghost.chestcommands.internal.MenuData;
import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder;
import com.gmail.filoghost.chestcommands.listener.CommandListener;
import com.gmail.filoghost.chestcommands.listener.InventoryListener;
import com.gmail.filoghost.chestcommands.listener.JoinListener;
import com.gmail.filoghost.chestcommands.listener.SignListener;
import com.gmail.filoghost.chestcommands.serializer.CommandSerializer;
import com.gmail.filoghost.chestcommands.serializer.MenuSerializer;
import com.gmail.filoghost.chestcommands.task.ErrorLoggerTask;
import com.gmail.filoghost.chestcommands.task.RefreshMenusTask;
import com.gmail.filoghost.chestcommands.util.BukkitUtils;
import com.gmail.filoghost.chestcommands.util.CaseInsensitiveMap;
import com.gmail.filoghost.chestcommands.util.ErrorLogger;
import com.gmail.filoghost.chestcommands.util.Utils;
import org.bstats.bukkit.MetricsLite;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ChestCommands extends JavaPlugin {
public static final String CHAT_PREFIX = ChatColor.DARK_GREEN + "[" + ChatColor.GREEN + "ChestCommands" + ChatColor.DARK_GREEN + "] " + ChatColor.GREEN;
private static ChestCommands instance;
private static Settings settings;
private static Lang lang;
private static Map<String, ExtendedIconMenu> fileNameToMenuMap;
private static Map<String, ExtendedIconMenu> commandsToMenuMap;
private static Set<BoundItem> boundItems;
private static int lastReloadErrors;
private static String newVersion;
@Override
public void onEnable() {
if (instance != null) {
getLogger().warning("Please do not use /reload or plugin reloaders. Do \"/cc reload\" instead.");
return;
}
instance = this;
fileNameToMenuMap = CaseInsensitiveMap.create();
commandsToMenuMap = CaseInsensitiveMap.create();
boundItems = Utils.newHashSet();
settings = new Settings(new PluginConfig(this, "config.yml"));
lang = new Lang(new PluginConfig(this, "lang.yml"));
if (!EconomyBridge.setupEconomy()) {
getLogger().warning("Vault with a compatible economy plugin was not found! Icons with a PRICE or commands that give money will not work.");
}
if (BarAPIBridge.setupPlugin()) {
getLogger().info("Hooked BarAPI");
}
if (PlaceholderAPIBridge.setupPlugin()) {
getLogger().info("Hooked PlaceholderAPI");
}
if (settings.update_notifications) {
new SimpleUpdater(this, 56919).checkForUpdates(new ResponseHandler() {
@Override
public void onUpdateFound(String newVersion) {
ChestCommands.newVersion = newVersion;
if (settings.use_console_colors) {
Bukkit.getConsoleSender().sendMessage(CHAT_PREFIX + "Found a new version: " + newVersion + ChatColor.WHITE + " (yours: v" + getDescription().getVersion() + ")");
Bukkit.getConsoleSender().sendMessage(CHAT_PREFIX + ChatColor.WHITE + "Download it on Bukkit Dev:");
Bukkit.getConsoleSender().sendMessage(CHAT_PREFIX + ChatColor.WHITE + "dev.bukkit.org/bukkit-plugins/chest-commands");
} else {
getLogger().info("Found a new version available: " + newVersion);
getLogger().info("Download it on Bukkit Dev:");
getLogger().info("dev.bukkit.org/bukkit-plugins/chest-commands");
}
}
});
}
// Start bStats metrics
new MetricsLite(this);
Bukkit.getPluginManager().registerEvents(new CommandListener(), this);
Bukkit.getPluginManager().registerEvents(new InventoryListener(), this);
Bukkit.getPluginManager().registerEvents(new JoinListener(), this);
Bukkit.getPluginManager().registerEvents(new SignListener(), this);
CommandFramework.register(this, new CommandHandler("chestcommands"));
ErrorLogger errorLogger = new ErrorLogger();
load(errorLogger);
lastReloadErrors = errorLogger.getSize();
if (errorLogger.hasErrors()) {
Bukkit.getScheduler().scheduleSyncDelayedTask(this, new ErrorLoggerTask(errorLogger), 10L);
}
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new RefreshMenusTask(), 2L, 2L);
}
@Override
public void onDisable() {
closeAllMenus();
}
public void load(ErrorLogger errorLogger) {
fileNameToMenuMap.clear();
commandsToMenuMap.clear();
boundItems.clear();
CommandSerializer.checkClassConstructors(errorLogger);
try {
settings.load();
} catch (IOException e) {
e.printStackTrace();
getLogger().warning("I/O error while using the configuration. Default values will be used.");
} catch (InvalidConfigurationException e) {
e.printStackTrace();
getLogger().warning("The config.yml was not a valid YAML, please look at the error above. Default values will be used.");
} catch (Exception e) {
e.printStackTrace();
getLogger().warning("Unhandled error while reading the values for the configuration! Please inform the developer.");
}
try {
lang.load();
} catch (IOException e) {
e.printStackTrace();
getLogger().warning("I/O error while using the language file. Default values will be used.");
} catch (InvalidConfigurationException e) {
e.printStackTrace();
getLogger().warning("The lang.yml was not a valid YAML, please look at the error above. Default values will be used.");
} catch (Exception e) {
e.printStackTrace();
getLogger().warning("Unhandled error while reading the values for the configuration! Please inform the developer.");
}
try {
AsciiPlaceholders.load(errorLogger);
} catch (IOException e) {
e.printStackTrace();
getLogger().warning("I/O error while reading the placeholders. They will not work.");
} catch (Exception e) {
e.printStackTrace();
getLogger().warning("Unhandled error while reading the placeholders! Please inform the developer.");
}
// Load the menus
File menusFolder = new File(getDataFolder(), "menu");
if (!menusFolder.isDirectory()) {
// Create the directory with the default menu
menusFolder.mkdirs();
BukkitUtils.saveResourceSafe(this, "menu" + File.separator + "example.yml");
}
List<PluginConfig> menusList = loadMenus(menusFolder);
for (PluginConfig menuConfig : menusList) {
try {
menuConfig.load();
} catch (IOException e) {
e.printStackTrace();
errorLogger.addError("I/O error while loading the menu \"" + menuConfig.getFileName() + "\". Is the file in use?");
continue;
} catch (InvalidConfigurationException e) {
e.printStackTrace();
errorLogger.addError("Invalid YAML configuration for the menu \"" + menuConfig.getFileName() + "\". Please look at the error above, or use an online YAML parser (google is your friend).");
continue;
}
MenuData data = MenuSerializer.loadMenuData(menuConfig, errorLogger);
ExtendedIconMenu iconMenu = MenuSerializer.loadMenu(menuConfig, data.getTitle(), data.getRows(), errorLogger);
if (fileNameToMenuMap.containsKey(menuConfig.getFileName())) {
errorLogger.addError("Two menus have the same file name \"" + menuConfig.getFileName() + "\" with different cases. There will be problems opening one of these two menus.");
}
fileNameToMenuMap.put(menuConfig.getFileName(), iconMenu);
if (data.hasCommands()) {
for (String command : data.getCommands()) {
if (!command.isEmpty()) {
if (commandsToMenuMap.containsKey(command)) {
errorLogger.addError("The menus \"" + commandsToMenuMap.get(command).getFileName() + "\" and \"" + menuConfig.getFileName() + "\" have the same command \"" + command + "\". Only one will be opened.");
}
commandsToMenuMap.put(command, iconMenu);
}
}
}
iconMenu.setRefreshTicks(data.getRefreshTenths());
if (data.getOpenActions() != null) {
iconMenu.setOpenActions(data.getOpenActions());
}
if (data.hasBoundMaterial() && data.getClickType() != null) {
BoundItem boundItem = new BoundItem(iconMenu, data.getBoundMaterial(), data.getClickType());
if (data.hasBoundDataValue()) {
boundItem.setRestrictiveData(data.getBoundDataValue());
}
boundItems.add(boundItem);
}
}
// Register the BungeeCord plugin channel
if (!Bukkit.getMessenger().isOutgoingChannelRegistered(this, "BungeeCord")) {
Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
}
}
/**
* Loads all the configuration files recursively into a list.
*/
private List<PluginConfig> loadMenus(File file) {
List<PluginConfig> list = Utils.newArrayList();
if (file.isDirectory()) {
for (File subFile : file.listFiles()) {
list.addAll(loadMenus(subFile));
}
} else if (file.isFile()) {
if (file.getName().endsWith(".yml")) {
list.add(new PluginConfig(this, file));
}
}
return list;
}
public static void closeAllMenus() {
for (Player player : BukkitUtils.getOnlinePlayers()) {
if (player.getOpenInventory() != null) {
if (player.getOpenInventory().getTopInventory().getHolder() instanceof MenuInventoryHolder || player.getOpenInventory().getBottomInventory().getHolder() instanceof MenuInventoryHolder) {
player.closeInventory();
}
}
}
}
public static ChestCommands getInstance() {
return instance;
}
public static Settings getSettings() {
return settings;
}
public static Lang getLang() {
return lang;
}
public static boolean hasNewVersion() {
return newVersion != null;
}
public static String getNewVersion() {
return newVersion;
}
public static Map<String, ExtendedIconMenu> getFileNameToMenuMap() {
return fileNameToMenuMap;
}
public static Map<String, ExtendedIconMenu> getCommandToMenuMap() {
return commandsToMenuMap;
}
public static Set<BoundItem> getBoundItems() {
return boundItems;
}
public static int getLastReloadErrors() {
return lastReloadErrors;
}
public static void setLastReloadErrors(int lastReloadErrors) {
ChestCommands.lastReloadErrors = lastReloadErrors;
}
}

View File

@ -1,28 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands;
public class Permissions {
public static final String
UPDATE_NOTIFICATIONS = "chestcommands.update",
SEE_ERRORS = "chestcommands.errors",
SIGN_CREATE = "chestcommands.sign",
COMMAND_BASE = "chestcommands.command.",
OPEN_MENU_BASE = "chestcommands.open.";
}

View File

@ -1,221 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands;
import com.google.common.primitives.Ints;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A very simple and lightweight updater, without download features.
*
* @author filoghost
*/
public final class SimpleUpdater {
private static Pattern VERSION_PATTERN = Pattern.compile("v?([0-9\\.]+)");
private Plugin plugin;
private int projectId;
public SimpleUpdater(Plugin plugin, int projectId) {
if (plugin == null) {
throw new NullPointerException("Plugin cannot be null");
}
this.plugin = plugin;
this.projectId = projectId;
}
/**
* This method creates a new async thread to check for updates.
*
* @param responseHandler the response handler
*/
public void checkForUpdates(final ResponseHandler responseHandler) {
Thread updaterThread = new Thread(new Runnable() {
@Override
public void run() {
try {
JSONArray filesArray = (JSONArray) readJson("https://api.curseforge.com/servermods/files?projectIds=" + projectId);
if (filesArray.size() == 0) {
// The array cannot be empty, there must be at least one file.
// The project ID is not valid or curse returned a wrong response.
return;
}
String updateName = (String) ((JSONObject) filesArray.get(filesArray.size() - 1)).get("name");
final PluginVersion remoteVersion = new PluginVersion(updateName);
PluginVersion localVersion = new PluginVersion(plugin.getDescription().getVersion());
if (remoteVersion.isNewerThan(localVersion)) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
responseHandler.onUpdateFound(remoteVersion.toString());
}
});
}
} catch (IOException e) {
plugin.getLogger().warning("Could not contact BukkitDev to check for updates.");
} catch (InvalidVersionException e) {
plugin.getLogger().warning("Could not check for updates because of a version format error: " + e.getMessage() + ".");
plugin.getLogger().warning("Please notify the author of this error.");
} catch (Exception e) {
e.printStackTrace();
plugin.getLogger().warning("Unable to check for updates: unhandled exception.");
}
}
});
updaterThread.start();
}
private Object readJson(String url) throws MalformedURLException, IOException {
URLConnection conn = new URL(url).openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(8000);
conn.addRequestProperty("User-Agent", "Updater (by filoghost)");
conn.setDoOutput(true);
return JSONValue.parse(new BufferedReader(new InputStreamReader(conn.getInputStream())));
}
private static class PluginVersion {
// The version extracted from a string, e.g. "Chest Commands v1.3" becomes [1, 3]
private int[] versionNumbers;
private boolean isDevBuild;
public PluginVersion(String input) throws InvalidVersionException {
if (input == null) {
throw new InvalidVersionException("input was null");
}
Matcher matcher = VERSION_PATTERN.matcher(input);
if (!matcher.find()) {
throw new InvalidVersionException("version pattern not found in \"" + input + "\"");
}
// Get the first group of the matcher (without the "v")
String version = matcher.group(1);
// Replace multiple full stops (probably typos) with a single full stop, and split the version with them
String[] versionParts = version.replaceAll("[\\.]{2,}", ".").split("\\.");
// Convert the strings to integers in order to compare them
this.versionNumbers = new int[versionParts.length];
for (int i = 0; i < versionParts.length; i++) {
try {
this.versionNumbers[i] = Integer.parseInt(versionParts[i]);
} catch (NumberFormatException e) {
throw new InvalidVersionException("invalid number in \"" + input + "\"");
}
}
this.isDevBuild = input.contains("SNAPSHOT");
}
/**
* Compares this version with another version, using the array "versionNumbers".
* Examples:
* v1.12 is newer than v1.2 ([1, 12] is newer than [1, 2])
* v2.01 is equal to v2.1 ([2, 1] is equal to [2, 1])
*
* @return true if this version is newer than the other, false if equal or older
*/
public boolean isNewerThan(PluginVersion other) {
int longest = Math.max(this.versionNumbers.length, other.versionNumbers.length);
for (int i = 0; i < longest; i++) {
int thisVersionPart = i < this.versionNumbers.length ? this.versionNumbers[i] : 0;
int otherVersionPart = i < other.versionNumbers.length ? other.versionNumbers[i] : 0;
int diff = thisVersionPart - otherVersionPart;
if (diff > 0) {
return true;
} else if (diff < 0) {
return false;
}
// Continue the loop until diff = 0
}
// If we get here, they're the same version, check dev builds.
// This version is newer only if it's not a dev build and the other is.
if (other.isDevBuild && !this.isDevBuild) {
return true;
}
return false;
}
@Override
public String toString() {
return "v" + Ints.join(".", versionNumbers);
}
}
private static class InvalidVersionException extends Exception {
private static final long serialVersionUID = 1L;
public InvalidVersionException(String message) {
super(message);
}
}
public interface ResponseHandler {
/**
* Called when the updater finds a new version.
*
* @param newVersion - the new version
*/
public void onUpdateFound(final String newVersion);
}
}

View File

@ -1,49 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.api;
import com.gmail.filoghost.chestcommands.ChestCommands;
import org.bukkit.entity.Player;
public class ChestCommandsAPI {
/**
* Checks if a menu with a given file name was loaded by the plugin.
*
* @return true - if the menu was found.
*/
public static boolean isPluginMenu(String yamlFile) {
return ChestCommands.getFileNameToMenuMap().containsKey(yamlFile);
}
/**
* Opens a menu loaded by ChestCommands to a player.
* NOTE: this method ignores permissions.
*
* @param player - the player that will see the GUI.
* @param yamlFile - the file name of the menu to open. The .yml extension CANNOT be omitted.
* @return true - if the menu was found and opened, false if not.
*/
public static boolean openPluginMenu(Player player, String yamlFile) {
IconMenu menu = ChestCommands.getFileNameToMenuMap().get(yamlFile);
if (menu != null) {
menu.open(player);
return true;
} else {
return false;
}
}
}

View File

@ -1,27 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.api;
import org.bukkit.entity.Player;
public interface ClickHandler {
/**
* @param player - the player that clicked on the icon.
* @return true if the menu should be closed, false otherwise.
*/
public boolean onClick(Player player);
}

View File

@ -1,350 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.api;
import com.gmail.filoghost.chestcommands.ChestCommands;
import com.gmail.filoghost.chestcommands.internal.VariableManager;
import com.gmail.filoghost.chestcommands.util.Utils;
import org.bukkit.*;
import org.bukkit.block.banner.Pattern;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BannerMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.inventory.meta.SkullMeta;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
public class Icon {
private Material material;
private int amount;
private short dataValue;
private String nbtData;
private String name;
private List<String> lore;
private Map<Enchantment, Integer> enchantments;
private Color color;
private String skullOwner;
private DyeColor bannerColor;
private List<Pattern> bannerPatterns;
protected boolean closeOnClick;
private ClickHandler clickHandler;
private boolean nameHasVariables;
private boolean[] loreLinesWithVariables;
private boolean skullOwnerHasVariables;
private ItemStack cachedItem; // When there are no variables, we don't recreate the item
public Icon() {
enchantments = new HashMap<Enchantment, Integer>();
closeOnClick = true;
amount = 1;
}
public boolean hasVariables() {
return nameHasVariables || loreLinesWithVariables != null || skullOwnerHasVariables;
}
public void setMaterial(Material material) {
if (material == Material.AIR) material = null;
this.material = material;
}
public Material getMaterial() {
return material;
}
public void setAmount(int amount) {
if (amount < 1) amount = 1;
else if (amount > 127) amount = 127;
this.amount = amount;
}
public int getAmount() {
return amount;
}
public void setDataValue(short dataValue) {
if (dataValue < 0) dataValue = 0;
this.dataValue = dataValue;
}
public short getDataValue() {
return dataValue;
}
public void setNBTData(String nbtData) {
this.nbtData = nbtData;
}
public String getNBTData() {
return nbtData;
}
public void setName(String name) {
this.name = name;
this.nameHasVariables = VariableManager.hasVariables(name);
}
public boolean hasName() {
return name != null;
}
public void setLore(String... lore) {
if (lore != null) {
setLore(Arrays.asList(lore));
}
}
public void setLore(List<String> lore) {
this.lore = lore;
this.loreLinesWithVariables = null;
if (lore != null) {
for (int i = 0; i < lore.size(); i++) {
if (VariableManager.hasVariables(lore.get(i))) {
if (this.loreLinesWithVariables == null) {
this.loreLinesWithVariables = new boolean[lore.size()];
}
loreLinesWithVariables[i] = true;
}
}
}
}
public boolean hasLore() {
return lore != null && lore.size() > 0;
}
public List<String> getLore() {
return lore;
}
public void setEnchantments(Map<Enchantment, Integer> enchantments) {
if (enchantments == null) {
this.enchantments.clear();
return;
}
this.enchantments = enchantments;
}
public Map<Enchantment, Integer> getEnchantments() {
return new HashMap<Enchantment, Integer>(enchantments);
}
public void addEnchantment(Enchantment ench) {
addEnchantment(ench, 1);
}
public void addEnchantment(Enchantment ench, Integer level) {
enchantments.put(ench, level);
}
public void removeEnchantment(Enchantment ench) {
enchantments.remove(ench);
}
public void clearEnchantments() {
enchantments.clear();
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public String getSkullOwner() {
return skullOwner;
}
public void setSkullOwner(String skullOwner) {
this.skullOwner = skullOwner;
this.skullOwnerHasVariables = VariableManager.hasVariables(skullOwner);
}
public DyeColor getBannerColor() {
return bannerColor;
}
public void setBannerColor(DyeColor bannerColor) {
this.bannerColor = bannerColor;
}
public List<Pattern> getBannerPatterns() {
return bannerPatterns;
}
public void setBannerPatterns(List<Pattern> bannerPatterns) {
this.bannerPatterns = bannerPatterns;
}
public void setCloseOnClick(boolean closeOnClick) {
this.closeOnClick = closeOnClick;
}
public void setClickHandler(ClickHandler clickHandler) {
this.clickHandler = clickHandler;
}
public ClickHandler getClickHandler() {
return clickHandler;
}
protected String calculateName(Player pov) {
if (hasName()) {
String name = this.name;
if (pov != null && nameHasVariables) {
name = VariableManager.setVariables(name, pov);
}
if (name.isEmpty()) {
// Add a color to display the name empty
return ChatColor.WHITE.toString();
} else {
return name;
}
}
return null;
}
protected List<String> calculateLore(Player pov) {
List<String> output = null;
if (hasLore()) {
output = Utils.newArrayList();
if (pov != null && loreLinesWithVariables != null) {
for (int i = 0; i < lore.size(); i++) {
String line = lore.get(i);
if (loreLinesWithVariables[i]) {
line = VariableManager.setVariables(line, pov);
}
output.add(line);
}
} else {
// Otherwise just copy the lines
output.addAll(lore);
}
}
if (material == null) {
if (output == null) {
output = Utils.newArrayList();
}
// Add an error message
output.add(ChatColor.RED + "(Invalid material)");
}
return output;
}
@SuppressWarnings("deprecation")
public ItemStack createItemstack(Player pov) {
if (!this.hasVariables() && cachedItem != null) {
// Performance
return cachedItem;
}
// If the material is not set, display BEDROCK
ItemStack itemStack = (material != null) ? new ItemStack(material, amount, dataValue) : new ItemStack(Material.BEDROCK, amount);
// 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;
ChestCommands.getInstance().getLogger().log(Level.WARNING, "Could not apply NBT-DATA to an item.", t);
}
}
// Then apply data from config nodes, overwriting NBT data if there are confliting values
ItemMeta itemMeta = itemStack.getItemMeta();
if (hasName()) {
itemMeta.setDisplayName(calculateName(pov));
}
if (hasLore()) {
itemMeta.setLore(calculateLore(pov));
}
if (color != null && itemMeta instanceof LeatherArmorMeta) {
((LeatherArmorMeta) itemMeta).setColor(color);
}
if (skullOwner != null && itemMeta instanceof SkullMeta) {
String skullOwner = this.skullOwner;
if(skullOwnerHasVariables) {
skullOwner = VariableManager.setVariables(skullOwner, pov);
}
((SkullMeta) itemMeta).setOwner(skullOwner);
}
if (bannerColor != null && itemMeta instanceof BannerMeta) {
BannerMeta bannerMeta = (BannerMeta) itemMeta;
bannerMeta.setBaseColor(bannerColor);
if (bannerPatterns != null) {
((BannerMeta) itemMeta).setPatterns(bannerPatterns);
}
}
itemStack.setItemMeta(itemMeta);
if (enchantments.size() > 0) {
for (Entry<Enchantment, Integer> entry : enchantments.entrySet()) {
itemStack.addUnsafeEnchantment(entry.getKey(), entry.getValue());
}
}
if (!this.hasVariables()) {
// If there are no variables, cache the item
cachedItem = itemStack;
}
return itemStack;
}
public boolean onClick(Player whoClicked) {
if (clickHandler != null) {
return clickHandler.onClick(whoClicked);
}
return closeOnClick;
}
}

View File

@ -1,106 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.api;
import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder;
import com.gmail.filoghost.chestcommands.util.ItemUtils;
import com.gmail.filoghost.chestcommands.util.Utils;
import com.gmail.filoghost.chestcommands.util.Validate;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import java.util.Arrays;
/*
* MEMO: Raw slot numbers
*
* | 0| 1| 2| 3| 4| 5| 6| 7| 8|
* | 9|10|11|12|13|14|15|16|17|
* ...
*
*/
public class IconMenu {
protected final String title;
protected final Icon[] icons;
public IconMenu(String title, int rows) {
this.title = title;
icons = new Icon[rows * 9];
}
public void setIcon(int x, int y, Icon icon) {
int slot = Utils.makePositive(y - 1) * 9 + Utils.makePositive(x - 1);
if (slot >= 0 && slot < icons.length) {
icons[slot] = icon;
}
}
public void setIconRaw(int slot, Icon icon) {
if (slot >= 0 && slot < icons.length) {
icons[slot] = icon;
}
}
public Icon getIcon(int x, int y) {
int slot = Utils.makePositive(y - 1) * 9 + Utils.makePositive(x - 1);
if (slot >= 0 && slot < icons.length) {
return icons[slot];
}
return null;
}
public Icon getIconRaw(int slot) {
if (slot >= 0 && slot < icons.length) {
return icons[slot];
}
return null;
}
public int getRows() {
return icons.length / 9;
}
public int getSize() {
return icons.length;
}
public String getTitle() {
return title;
}
public void open(Player player) {
Validate.notNull(player, "Player cannot be null");
Inventory inventory = Bukkit.createInventory(new MenuInventoryHolder(this), icons.length, title);
for (int i = 0; i < icons.length; i++) {
if (icons[i] != null) {
inventory.setItem(i, ItemUtils.hideAttributes(icons[i].createItemstack(player)));
}
}
player.openInventory(inventory);
}
@Override
public String toString() {
return "IconMenu [title=" + title + ", icons=" + Arrays.toString(icons) + "]";
}
}

View File

@ -1,47 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.bridge;
import me.confuser.barapi.BarAPI;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class BarAPIBridge {
private static BarAPI barAPI;
public static boolean setupPlugin() {
Plugin barPlugin = Bukkit.getPluginManager().getPlugin("BarAPI");
if (barPlugin == null) {
return false;
}
barAPI = (BarAPI) barPlugin;
return true;
}
public static boolean hasValidPlugin() {
return barAPI != null;
}
public static void setMessage(Player player, String message, int seconds) {
if (!hasValidPlugin()) throw new IllegalStateException("BarAPI plugin was not found!");
BarAPI.setMessage(player, message, seconds);
}
}

View File

@ -1,101 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.bridge;
import com.gmail.filoghost.chestcommands.util.MenuUtils;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider;
public class EconomyBridge {
private static Economy economy;
public static boolean setupEconomy() {
if (Bukkit.getPluginManager().getPlugin("Vault") == null) {
return false;
}
RegisteredServiceProvider<Economy> rsp = Bukkit.getServicesManager().getRegistration(Economy.class);
if (rsp == null) {
return false;
}
economy = rsp.getProvider();
return economy != null;
}
public static boolean hasValidEconomy() {
return economy != null;
}
public static Economy getEconomy() {
if (!hasValidEconomy()) throw new IllegalStateException("Economy plugin was not found!");
return economy;
}
public static double getMoney(Player player) {
if (!hasValidEconomy()) throw new IllegalStateException("Economy plugin was not found!");
return economy.getBalance(player.getName(), player.getWorld().getName());
}
public static boolean hasMoney(Player player, double minimum) {
if (!hasValidEconomy()) throw new IllegalStateException("Economy plugin was not found!");
if (minimum < 0.0) throw new IllegalArgumentException("Invalid amount of money: " + minimum);
double balance = economy.getBalance(player.getName(), player.getWorld().getName());
if (balance < minimum) {
return false;
} else {
return true;
}
}
/**
* @return true if the operation was successful.
*/
public static boolean takeMoney(Player player, double amount) {
if (!hasValidEconomy()) throw new IllegalStateException("Economy plugin was not found!");
if (amount < 0.0) throw new IllegalArgumentException("Invalid amount of money: " + amount);
EconomyResponse response = economy.withdrawPlayer(player.getName(), player.getWorld().getName(), amount);
boolean result = response.transactionSuccess();
MenuUtils.refreshMenu(player);
return result;
}
public static boolean giveMoney(Player player, double amount) {
if (!hasValidEconomy()) throw new IllegalStateException("Economy plugin was not found!");
if (amount < 0.0) throw new IllegalArgumentException("Invalid amount of money: " + amount);
EconomyResponse response = economy.depositPlayer(player.getName(), player.getWorld().getName(), amount);
boolean result = response.transactionSuccess();
MenuUtils.refreshMenu(player);
return result;
}
public static String formatMoney(double amount) {
if (hasValidEconomy()) {
return economy.format(amount);
} else {
return Double.toString(amount);
}
}
}

View File

@ -1,44 +0,0 @@
package com.gmail.filoghost.chestcommands.bridge;
import me.clip.placeholderapi.PlaceholderAPI;
import me.clip.placeholderapi.PlaceholderAPIPlugin;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class PlaceholderAPIBridge {
private static PlaceholderAPIPlugin placeholderAPI;
public static boolean setupPlugin() {
Plugin placeholderPlugin = Bukkit.getPluginManager().getPlugin("PlaceholderAPI");
if (placeholderPlugin == null) {
return false;
}
placeholderAPI = (PlaceholderAPIPlugin) placeholderPlugin;
return true;
}
public static boolean hasValidPlugin() {
return placeholderAPI != null;
}
public static boolean hasPlaceholders(String message) {
if (!hasValidPlugin()) {
throw new IllegalStateException("PlaceholderAPI plugin was not found!");
}
return PlaceholderAPI.containsPlaceholders(message);
}
public static String setPlaceholders(String message, Player executor) {
if (!hasValidPlugin()) {
throw new IllegalStateException("PlaceholderAPI plugin was not found!");
}
return PlaceholderAPI.setPlaceholders(executor, message);
}
}

View File

@ -1,53 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.bridge.bungee;
import com.gmail.filoghost.chestcommands.ChestCommands;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
public class BungeeCordUtils {
public static boolean connect(Player player, String server) {
try {
if (server.length() == 0) {
player.sendMessage("§cTarget server was \"\" (empty string) cannot connect to it.");
return false;
}
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(byteArray);
out.writeUTF("Connect");
out.writeUTF(server); // Target Server
player.sendPluginMessage(ChestCommands.getInstance(), "BungeeCord", byteArray.toByteArray());
} catch (Exception ex) {
player.sendMessage(ChatColor.RED + "An unexpected exception has occurred. Please notify the server's staff about this. (They should look at the console).");
ex.printStackTrace();
ChestCommands.getInstance().getLogger().warning("Could not connect \"" + player.getName() + "\" to the server \"" + server + "\".");
return false;
}
return true;
}
}

View File

@ -1,139 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.command;
import com.gmail.filoghost.chestcommands.ChestCommands;
import com.gmail.filoghost.chestcommands.Permissions;
import com.gmail.filoghost.chestcommands.command.framework.CommandFramework;
import com.gmail.filoghost.chestcommands.command.framework.CommandValidate;
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
import com.gmail.filoghost.chestcommands.task.ErrorLoggerTask;
import com.gmail.filoghost.chestcommands.util.ErrorLogger;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
public class CommandHandler extends CommandFramework {
public CommandHandler(String label) {
super(label);
}
@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.getInstance().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")) {
CommandValidate.isTrue(sender.hasPermission(Permissions.COMMAND_BASE + "help"), "You don't have permission.");
sender.sendMessage(ChestCommands.CHAT_PREFIX + " Commands:");
sender.sendMessage(ChatColor.WHITE + "/" + label + " reload" + ChatColor.GRAY + " - Reloads the plugin.");
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("reload")) {
CommandValidate.isTrue(sender.hasPermission(Permissions.COMMAND_BASE + "reload"), "You don't have permission.");
ChestCommands.closeAllMenus();
ErrorLogger errorLogger = new ErrorLogger();
ChestCommands.getInstance().load(errorLogger);
ChestCommands.setLastReloadErrors(errorLogger.getSize());
if (!errorLogger.hasErrors()) {
sender.sendMessage(ChestCommands.CHAT_PREFIX + "Plugin reloaded.");
} else {
new ErrorLoggerTask(errorLogger).run();
sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Plugin reloaded with " + errorLogger.getSize() + " error(s).");
if (!(sender instanceof ConsoleCommandSender)) {
sender.sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "Please check the console.");
}
}
return;
}
if (args[0].equalsIgnoreCase("open")) {
CommandValidate.isTrue(sender.hasPermission(Permissions.COMMAND_BASE + "open"), "You don't have permission.");
CommandValidate.minLength(args, 2, "Usage: /" + label + " open <menu> [player]");
Player target = null;
if (!(sender instanceof Player)) {
CommandValidate.minLength(args, 3, "You must specify a player from the console.");
target = Bukkit.getPlayerExact(args[2]);
} else {
if (args.length > 2) {
CommandValidate.isTrue(sender.hasPermission(Permissions.COMMAND_BASE + "open.others"), "You don't have permission to open menus for others.");
target = Bukkit.getPlayerExact(args[2]);
} else {
target = (Player) sender;
}
}
CommandValidate.notNull(target, "That player is not online.");
String menuName = args[1].toLowerCase().endsWith(".yml") ? args[1] : args[1] + ".yml";
ExtendedIconMenu menu = ChestCommands.getFileNameToMenuMap().get(menuName);
CommandValidate.notNull(menu, "The menu \"" + menuName + "\" was not found.");
if (!sender.hasPermission(menu.getPermission())) {
menu.sendNoPermissionMessage(sender);
return;
}
if (sender.getName().equalsIgnoreCase(target.getName())) {
if (!ChestCommands.getLang().open_menu.isEmpty()) {
sender.sendMessage(ChestCommands.getLang().open_menu.replace("{menu}", menuName));
}
} else {
if (!ChestCommands.getLang().open_menu_others.isEmpty()) {
sender.sendMessage(ChestCommands.getLang().open_menu_others.replace("{menu}", menuName).replace("{player}", target.getName()));
}
}
menu.open(target);
return;
}
if (args[0].equalsIgnoreCase("list")) {
CommandValidate.isTrue(sender.hasPermission(Permissions.COMMAND_BASE + "list"), "You don't have permission.");
sender.sendMessage(ChestCommands.CHAT_PREFIX + " Loaded menus:");
for (String file : ChestCommands.getFileNameToMenuMap().keySet()) {
sender.sendMessage(ChatColor.GRAY + "- " + ChatColor.WHITE + file);
}
return;
}
sender.sendMessage(ChatColor.RED + "Unknown sub-command \"" + args[0] + "\".");
}
}

View File

@ -1,25 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.command.framework;
public class CommandException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CommandException(String msg) {
super(msg);
}
}

View File

@ -1,85 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.command.framework;
public class CommandValidate {
public static void notNull(Object o, String msg) {
if (o == null) {
throw new CommandException(msg);
}
}
public static void isTrue(boolean b, String msg) {
if (!b) {
throw new CommandException(msg);
}
}
public static int getPositiveInteger(String input) {
try {
int i = Integer.parseInt(input);
if (i < 0) {
throw new CommandException("The number must be 0 or positive.");
}
return i;
} catch (NumberFormatException e) {
throw new CommandException("Invalid number \"" + input + "\".");
}
}
public static int getPositiveIntegerNotZero(String input) {
try {
int i = Integer.parseInt(input);
if (i <= 0) {
throw new CommandException("The number must be positive.");
}
return i;
} catch (NumberFormatException e) {
throw new CommandException("Invalid number \"" + input + "\".");
}
}
public static double getPositiveDouble(String input) {
try {
double d = Double.parseDouble(input);
if (d < 0) {
throw new CommandException("The number must be 0 or positive.");
}
return d;
} catch (NumberFormatException e) {
throw new CommandException("Invalid number \"" + input + "\".");
}
}
public static double getPositiveDoubleNotZero(String input) {
try {
double d = Integer.parseInt(input);
if (d <= 0) {
throw new CommandException("The number must be positive.");
}
return d;
} catch (NumberFormatException e) {
throw new CommandException("Invalid number \"" + input + "\".");
}
}
public static void minLength(Object[] array, int minLength, String msg) {
if (array.length < minLength) {
throw new CommandException(msg);
}
}
}

View File

@ -1,115 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.config;
import com.gmail.filoghost.chestcommands.ChestCommands;
import com.gmail.filoghost.chestcommands.util.BukkitUtils;
import com.gmail.filoghost.chestcommands.util.ErrorLogger;
import com.gmail.filoghost.chestcommands.util.FormatUtils;
import com.gmail.filoghost.chestcommands.util.Utils;
import org.apache.commons.lang.StringEscapeUtils;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* This is not a real YAML file ;)
*/
public class AsciiPlaceholders {
private static Map<String, String> placeholders = Utils.newHashMap();
public static void load(ErrorLogger errorLogger) throws IOException, Exception {
placeholders.clear();
File file = new File(ChestCommands.getInstance().getDataFolder(), "placeholders.yml");
if (!file.exists()) {
BukkitUtils.saveResourceSafe(ChestCommands.getInstance(), "placeholders.yml");
}
List<String> lines = Utils.readLines(file);
for (String line : lines) {
// Comment or empty line
if (line.isEmpty() || line.startsWith("#")) {
continue;
}
if (!line.contains(":")) {
errorLogger.addError("Unable to parse a line(" + line + ") from placeholders.yml: it must contain ':' to separate the placeholder and the replacement.");
continue;
}
int indexOf = line.indexOf(':');
String placeholder = unquote(line.substring(0, indexOf).trim());
String replacement = FormatUtils.addColors(StringEscapeUtils.unescapeJava(unquote(line.substring(indexOf + 1, line.length()).trim())));
if (placeholder.length() == 0 || replacement.length() == 0) {
errorLogger.addError("Unable to parse a line(" + line + ") from placeholders.yml: the placeholder and the replacement must have both at least 1 character.");
continue;
}
if (placeholder.length() > 100) {
errorLogger.addError("Unable to parse a line(" + line + ") from placeholders.yml: the placeholder cannot be longer than 100 characters.");
continue;
}
placeholders.put(placeholder, replacement);
}
}
public static List<String> placeholdersToSymbols(List<String> input) {
if (input == null) return null;
for (int i = 0; i < input.size(); i++) {
input.set(i, placeholdersToSymbols(input.get(i)));
}
return input;
}
public static String placeholdersToSymbols(String input) {
if (input == null) return null;
for (Entry<String, String> entry : placeholders.entrySet()) {
input = input.replace(entry.getKey(), entry.getValue());
}
return input;
}
public static String symbolsToPlaceholders(String input) {
if (input == null) return null;
for (Entry<String, String> entry : placeholders.entrySet()) {
input = input.replace(entry.getValue(), entry.getKey());
}
return input;
}
private static String unquote(String input) {
if (input.length() < 2) {
// Cannot be quoted
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;
}
}

View File

@ -1,92 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.config;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
import org.bukkit.configuration.ConfigurationSection;
import com.gmail.filoghost.chestcommands.util.Utils;
public class ConfigUtil {
public static String getAnyString(ConfigurationSection config, String... paths) {
for (String path : paths) {
String value = config.getString(path);
if (value != null) {
return value;
}
}
return null;
}
public static Integer getAnyInt(ConfigurationSection config, String... paths) {
for (String path : paths) {
if (config.isSet(path)) {
return config.getInt(path);
}
}
return null;
}
public static List<String> getStringListOrInlineList(ConfigurationSection config, String separator, String... paths) {
for (String path : paths) {
if (config.isSet(path)) {
if (config.isList(path)) {
return config.getStringList(path);
} else {
return getSeparatedValues(config.getString(path), separator);
}
}
}
return null;
}
public static List<String> getStringListOrSingle(ConfigurationSection config, String... paths) {
for (String path : paths) {
if (config.isSet(path)) {
if (config.isList(path)) {
return config.getStringList(path);
} else {
return Collections.singletonList(config.getString(path));
}
}
}
return null;
}
public static List<String> getSeparatedValues(String input, String separator) {
if (separator == null || separator.length() == 0) {
separator = ";";
}
String[] splitValues = input.split(Pattern.quote(separator));
List<String> values = Utils.newArrayList();
for (String value : splitValues) {
String trimmedValue = value.trim();
if (!trimmedValue.isEmpty()) {
values.add(trimmedValue);
}
}
return values;
}
}

View File

@ -1,35 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.config;
import com.gmail.filoghost.chestcommands.config.yaml.PluginConfig;
import com.gmail.filoghost.chestcommands.config.yaml.SpecialConfig;
public class Lang extends SpecialConfig {
public String no_open_permission = "&cYou don't have permission &e{permission} &cto use this menu.";
public String default_no_icon_permission = "&cYou don't have permission for this icon.";
public String no_required_item = "&cYou must have &e{amount}x {material} &c(data value: {datavalue}) for this.";
public String no_money = "&cYou need {money}$ for this.";
public String no_exp = "&cYou need {levels} XP levels for this.";
public String menu_not_found = "&cMenu not found! Please inform the staff.";
public String open_menu = "&aOpening the menu \"{menu}\".";
public String open_menu_others = "&aOpening the menu \"{menu}\" to {player}.";
public String any = "any"; // Used in no_required_item when data value is not restrictive
public Lang(PluginConfig config) {
super(config);
}
}

View File

@ -1,35 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.config;
import com.gmail.filoghost.chestcommands.config.yaml.PluginConfig;
import com.gmail.filoghost.chestcommands.config.yaml.SpecialConfig;
public class Settings extends SpecialConfig {
public boolean use_console_colors = true;
public String default_color__name = "&f";
public String default_color__lore = "&7";
public String multiple_commands_separator = ";";
public boolean update_notifications = true;
public int anti_click_spam_delay = 200;
public boolean use_only_commands_without_args = true;
public Settings(PluginConfig config) {
super(config);
setHeader("ChestCommands configuration file.\nTutorial: http://dev.bukkit.org/bukkit-plugins/chest-commands\n");
}
}

View File

@ -1,73 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.config.yaml;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import java.io.File;
import java.io.IOException;
/**
* A simple utility class to manage configurations with a file associated to them.
*/
public class PluginConfig extends YamlConfiguration {
private File file;
private Plugin plugin;
public PluginConfig(Plugin plugin, File file) {
super();
this.file = file;
this.plugin = plugin;
}
public PluginConfig(Plugin plugin, String name) {
this(plugin, new File(plugin.getDataFolder(), name));
}
public void load() throws IOException, InvalidConfigurationException {
if (!file.isFile()) {
if (plugin.getResource(file.getName()) != null) {
plugin.saveResource(file.getName(), false);
} else {
if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
}
// To reset all the values when loading
for (String section : this.getKeys(false)) {
set(section, null);
}
load(file);
}
public void save() throws IOException {
this.save(file);
}
public Plugin getPlugin() {
return plugin;
}
public String getFileName() {
return file.getName();
}
}

View File

@ -1,134 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.config.yaml;
import com.gmail.filoghost.chestcommands.util.FormatUtils;
import org.bukkit.configuration.InvalidConfigurationException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* A special configuration wrapper that reads the values using reflection.
* It will also save default values if not set.
*/
public class SpecialConfig {
private transient PluginConfig config;
private transient String header;
private transient Map<String, Object> defaultValuesMap;
public SpecialConfig(PluginConfig config) {
this.config = config;
}
public void setHeader(String header) {
this.header = header;
}
public void load() throws IOException, InvalidConfigurationException, Exception {
// Check if the configuration was initialized
if (defaultValuesMap == null) {
defaultValuesMap = new HashMap<String, Object>();
// Put the values in the default values map
for (Field field : getClass().getDeclaredFields()) {
if (!isValidField(field)) continue;
field.setAccessible(true);
String configKey = formatFieldName(field);
try {
Object defaultValue = field.get(this);
if (defaultValue != null) {
defaultValuesMap.put(configKey, defaultValue);
} else {
config.getPlugin().getLogger().warning("The field " + field.getName() + " was not provided with a default value, please inform the developer.");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
// First of all, try to load the yaml file
config.load();
// Save default values not set
boolean needsSave = false;
for (Entry<String, Object> entry : defaultValuesMap.entrySet()) {
if (!config.isSet(entry.getKey())) {
needsSave = true;
config.set(entry.getKey(), entry.getValue());
}
}
if (needsSave) {
config.options().header(header);
config.save();
}
// Now read change the fields
for (Field field : getClass().getDeclaredFields()) {
if (!isValidField(field)) continue;
field.setAccessible(true);
String configKey = formatFieldName(field);
if (config.isSet(configKey)) {
Class<?> type = field.getType();
if (type == boolean.class || type == Boolean.class) {
field.set(this, config.getBoolean(configKey));
} else if (type == int.class || type == Integer.class) {
field.set(this, config.getInt(configKey));
} else if (type == double.class || type == Double.class) {
field.set(this, config.getDouble(configKey));
} else if (type == String.class) {
field.set(this, FormatUtils.addColors(config.getString(configKey))); // Always add colors
} else {
config.getPlugin().getLogger().warning("Unknown field type: " + field.getType().getName() + " (" + field.getName() + "). Please inform the developer.");
}
} else {
field.set(this, defaultValuesMap.get(configKey));
}
}
}
private boolean isValidField(Field field) {
int modifiers = field.getModifiers();
return !Modifier.isTransient(modifiers) && !Modifier.isStatic(modifiers) && !Modifier.isFinal(modifiers);
}
private String formatFieldName(Field field) {
return field.getName().replace("__", ".").replace("_", "-");
}
}

View File

@ -1,24 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.exception;
public class FormatException extends Exception {
private static final long serialVersionUID = 1L;
public FormatException(String message) {
super(message);
}
}

View File

@ -1,66 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal;
import com.gmail.filoghost.chestcommands.util.ClickType;
import com.gmail.filoghost.chestcommands.util.Validate;
import org.bukkit.Material;
import org.bukkit.event.block.Action;
import org.bukkit.inventory.ItemStack;
public class BoundItem {
private ExtendedIconMenu menu;
private Material material;
private short data;
private ClickType clickType;
public BoundItem(ExtendedIconMenu menu, Material material, ClickType clickType) {
Validate.notNull(material, "Material cannot be null");
Validate.notNull(material, "ClickType cannot be null");
Validate.isTrue(material != Material.AIR, "Material cannot be AIR");
this.menu = menu;
this.material = material;
this.clickType = clickType;
data = -1; // -1 = any
}
public void setRestrictiveData(short data) {
this.data = data;
}
public ExtendedIconMenu getMenu() {
return menu;
}
public boolean isValidTrigger(ItemStack item, Action action) {
if (item == null) {
return false;
}
// First, they must have the same material
if (this.material != item.getType()) {
return false;
}
// Check if the data value is valid (-1 = any data value)
if (this.data != -1 && this.data != item.getDurability()) {
return false;
}
// Finally checks the action
return clickType.isValidInteract(action);
}
}

View File

@ -1,36 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal;
import com.gmail.filoghost.chestcommands.util.BukkitUtils;
public class CachedGetters {
private static long lastOnlinePlayersRefresh;
private static int onlinePlayers;
public static int getOnlinePlayers() {
long now = System.currentTimeMillis();
if (lastOnlinePlayersRefresh == 0 || now - lastOnlinePlayersRefresh > 1000) {
// getOnlinePlayers() could be expensive if called frequently
lastOnlinePlayersRefresh = now;
onlinePlayers = BukkitUtils.getOnlinePlayers().size();
}
return onlinePlayers;
}
}

View File

@ -1,54 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal;
import com.gmail.filoghost.chestcommands.api.ClickHandler;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import com.gmail.filoghost.chestcommands.internal.icon.command.OpenIconCommand;
import org.bukkit.entity.Player;
import java.util.List;
public class CommandsClickHandler implements ClickHandler {
private List<IconCommand> commands;
private boolean closeOnClick;
public CommandsClickHandler(List<IconCommand> commands, boolean closeOnClick) {
this.commands = commands;
this.closeOnClick = closeOnClick;
if (commands != null && commands.size() > 0) {
for (IconCommand command : commands) {
if (command instanceof OpenIconCommand) {
// Fix GUI closing if KEEP-OPEN is not set, and a command should open another GUI
this.closeOnClick = false;
}
}
}
}
@Override
public boolean onClick(Player player) {
if (commands != null && commands.size() > 0) {
for (IconCommand command : commands) {
command.execute(player);
}
}
return closeOnClick;
}
}

View File

@ -1,141 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal;
import com.gmail.filoghost.chestcommands.ChestCommands;
import com.gmail.filoghost.chestcommands.Permissions;
import com.gmail.filoghost.chestcommands.api.IconMenu;
import com.gmail.filoghost.chestcommands.internal.icon.ExtendedIcon;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import com.gmail.filoghost.chestcommands.util.ItemUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.List;
public class ExtendedIconMenu extends IconMenu {
private String fileName;
private String permission;
private List<IconCommand> openActions;
private int refreshTicks;
public ExtendedIconMenu(String title, int rows, String fileName) {
super(title, rows);
this.fileName = fileName;
this.permission = Permissions.OPEN_MENU_BASE + fileName;
}
public List<IconCommand> getOpenActions() {
return openActions;
}
public void setOpenActions(List<IconCommand> openAction) {
this.openActions = openAction;
}
public String getPermission() {
return permission;
}
public String getFileName() {
return fileName;
}
public int getRefreshTicks() {
return refreshTicks;
}
public void setRefreshTicks(int refreshTicks) {
this.refreshTicks = refreshTicks;
}
@Override
public void open(Player player) {
try {
if (openActions != null) {
for (IconCommand openAction : openActions) {
openAction.execute(player);
}
}
Inventory inventory = Bukkit.createInventory(new MenuInventoryHolder(this), icons.length, title);
for (int i = 0; i < icons.length; i++) {
if (icons[i] != null) {
if (icons[i] instanceof ExtendedIcon && !((ExtendedIcon) icons[i]).canViewIcon(player)) {
continue;
}
inventory.setItem(i, ItemUtils.hideAttributes(icons[i].createItemstack(player)));
}
}
player.openInventory(inventory);
} catch (Exception e) {
e.printStackTrace();
player.sendMessage(ChatColor.RED + "An internal error occurred while opening the menu. The staff should check the console for errors.");
}
}
public void refresh(Player player, Inventory inventory) {
try {
for (int i = 0; i < icons.length; i++) {
if (icons[i] != null && icons[i] instanceof ExtendedIcon) {
ExtendedIcon extIcon = (ExtendedIcon) icons[i];
if (extIcon.hasViewPermission() || extIcon.hasVariables()) {
// Then we have to refresh it
if (extIcon.canViewIcon(player)) {
if (inventory.getItem(i) == null) {
ItemStack newItem = ItemUtils.hideAttributes(extIcon.createItemstack(player));
inventory.setItem(i, newItem);
} else {
// Performance, only update name and lore
ItemStack oldItem = ItemUtils.hideAttributes(inventory.getItem(i));
ItemMeta meta = oldItem.getItemMeta();
meta.setDisplayName(extIcon.calculateName(player));
meta.setLore(extIcon.calculateLore(player));
oldItem.setItemMeta(meta);
}
} else {
inventory.setItem(i, null);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
player.sendMessage(ChatColor.RED + "An internal error occurred while refreshing the menu. The staff should check the console for errors.");
}
}
public void sendNoPermissionMessage(CommandSender sender) {
String noPermMessage = ChestCommands.getLang().no_open_permission;
if (noPermMessage != null && !noPermMessage.isEmpty()) {
sender.sendMessage(noPermMessage.replace("{permission}", this.permission));
}
}
}

View File

@ -1,110 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import com.gmail.filoghost.chestcommands.util.ClickType;
import org.bukkit.Material;
import java.util.List;
public class MenuData {
// Required data
private String title;
private int rows;
// Optional data
private String[] commands;
private Material boundMaterial;
private short boundDataValue;
private ClickType clickType;
private List<IconCommand> openActions;
private int refreshTenths;
public MenuData(String title, int rows) {
this.title = title;
this.rows = rows;
boundDataValue = -1; // -1 = any
}
public String getTitle() {
return title;
}
public int getRows() {
return rows;
}
public boolean hasCommands() {
return commands != null && commands.length > 0;
}
public void setCommands(String[] commands) {
this.commands = commands;
}
public String[] getCommands() {
return commands;
}
public boolean hasBoundMaterial() {
return boundMaterial != null;
}
public Material getBoundMaterial() {
return boundMaterial;
}
public void setBoundMaterial(Material boundMaterial) {
this.boundMaterial = boundMaterial;
}
public boolean hasBoundDataValue() {
return boundDataValue > -1;
}
public short getBoundDataValue() {
return boundDataValue;
}
public void setBoundDataValue(short boundDataValue) {
this.boundDataValue = boundDataValue;
}
public ClickType getClickType() {
return clickType;
}
public void setClickType(ClickType clickType) {
this.clickType = clickType;
}
public List<IconCommand> getOpenActions() {
return openActions;
}
public void setOpenActions(List<IconCommand> openAction) {
this.openActions = openAction;
}
public int getRefreshTenths() {
return refreshTenths;
}
public void setRefreshTenths(int refreshTenths) {
this.refreshTenths = refreshTenths;
}
}

View File

@ -1,54 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal;
import com.gmail.filoghost.chestcommands.api.IconMenu;
import com.gmail.filoghost.chestcommands.util.Validate;
import org.bukkit.Bukkit;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
/**
* This class links an IconMenu with an Inventory, via InventoryHolder.
*/
public class MenuInventoryHolder implements InventoryHolder {
private IconMenu iconMenu;
public MenuInventoryHolder(IconMenu iconMenu) {
this.iconMenu = iconMenu;
}
@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, iconMenu.getSize());
}
public IconMenu getIconMenu() {
return iconMenu;
}
public void setIconMenu(IconMenu iconMenu) {
Validate.notNull(iconMenu, "IconMenu cannot be null");
this.iconMenu = iconMenu;
}
}

View File

@ -1,112 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal;
import com.gmail.filoghost.chestcommands.util.Validate;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class RequiredItem {
private Material material;
private int amount;
private short dataValue;
private boolean isDurabilityRestrictive = false;
public RequiredItem(Material material, int amount) {
Validate.notNull(material, "Material cannot be null");
Validate.isTrue(material != Material.AIR, "Material cannot be air");
this.material = material;
this.amount = amount;
}
public ItemStack createItemStack() {
return new ItemStack(material, amount, dataValue);
}
public Material getMaterial() {
return material;
}
public int getAmount() {
return amount;
}
public short getDataValue() {
return dataValue;
}
public void setRestrictiveDataValue(short data) {
Validate.isTrue(data >= 0, "Data value cannot be negative");
this.dataValue = data;
isDurabilityRestrictive = true;
}
public boolean hasRestrictiveDataValue() {
return isDurabilityRestrictive;
}
public boolean isValidDataValue(short data) {
if (!isDurabilityRestrictive) return true;
return data == this.dataValue;
}
public boolean hasItem(Player player) {
int amountFound = 0;
for (ItemStack item : player.getInventory().getContents()) {
if (item != null && item.getType() == material && isValidDataValue(item.getDurability())) {
amountFound += item.getAmount();
}
}
return amountFound >= amount;
}
public boolean takeItem(Player player) {
if (amount <= 0) {
return true;
}
int itemsToTake = amount; //start from amount and decrease
ItemStack[] contents = player.getInventory().getContents();
ItemStack current = null;
for (int i = 0; i < contents.length; i++) {
current = contents[i];
if (current != null && current.getType() == material && isValidDataValue(current.getDurability())) {
if (current.getAmount() > itemsToTake) {
current.setAmount(current.getAmount() - itemsToTake);
return true;
} else {
itemsToTake -= current.getAmount();
player.getInventory().setItem(i, new ItemStack(Material.AIR));
}
}
// The end
if (itemsToTake <= 0) return true;
}
return false;
}
}

View File

@ -1,68 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal;
import com.gmail.filoghost.chestcommands.bridge.EconomyBridge;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public enum Variable {
PLAYER("{player}") {
public String getReplacement(Player executor) {
return executor.getName();
}
},
ONLINE("{online}") {
public String getReplacement(Player executor) {
return String.valueOf(CachedGetters.getOnlinePlayers());
}
},
MAX_PLAYERS("{max_players}") {
public String getReplacement(Player executor) {
return String.valueOf(Bukkit.getMaxPlayers());
}
},
MONEY("{money}") {
public String getReplacement(Player executor) {
if (EconomyBridge.hasValidEconomy()) {
return EconomyBridge.formatMoney(EconomyBridge.getMoney(executor));
} else {
return "[ECONOMY PLUGIN NOT FOUND]";
}
}
},
WORLD("{world}") {
public String getReplacement(Player executor) {
return executor.getWorld().getName();
}
};
private String text;
private Variable(String text) {
this.text = text;
}
public String getText() {
return text;
}
public abstract String getReplacement(Player executor);
}

View File

@ -1,35 +0,0 @@
package com.gmail.filoghost.chestcommands.internal;
import com.gmail.filoghost.chestcommands.bridge.PlaceholderAPIBridge;
import org.bukkit.entity.Player;
public class VariableManager {
public static boolean hasVariables(String message) {
if(message == null) {
return false;
}
for (Variable variable : Variable.values()) {
if (message.contains(variable.getText())) {
return true;
}
}
if (PlaceholderAPIBridge.hasValidPlugin() && PlaceholderAPIBridge.hasPlaceholders(message)) {
return true;
}
return false;
}
public static String setVariables(String message, Player executor) {
for (Variable variable : Variable.values()) {
if (message.contains(variable.getText())) {
message = message.replace(variable.getText(), variable.getReplacement(executor));
}
}
if (PlaceholderAPIBridge.hasValidPlugin()) {
message = PlaceholderAPIBridge.setPlaceholders(message, executor);
}
return message;
}
}

View File

@ -1,235 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal.icon;
import com.gmail.filoghost.chestcommands.ChestCommands;
import com.gmail.filoghost.chestcommands.api.Icon;
import com.gmail.filoghost.chestcommands.bridge.EconomyBridge;
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder;
import com.gmail.filoghost.chestcommands.internal.RequiredItem;
import com.gmail.filoghost.chestcommands.util.MaterialsRegistry;
import com.gmail.filoghost.chestcommands.util.StringUtils;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
import java.util.List;
public class ExtendedIcon extends Icon {
private String permission;
private String permissionMessage;
private String viewPermission;
private boolean permissionNegated;
private boolean viewPermissionNegated;
private double moneyPrice;
private int expLevelsPrice;
private List<RequiredItem> requiredItems;
public ExtendedIcon() {
super();
}
public boolean canClickIcon(Player player) {
if (permission == null) {
return true;
}
if (permissionNegated) {
return !player.hasPermission(permission);
} else {
return player.hasPermission(permission);
}
}
public void setPermission(String permission) {
if (StringUtils.isNullOrEmpty(permission)) {
permission = null;
}
if (permission != null) {
if (permission.startsWith("-")) {
permissionNegated = true;
permission = permission.substring(1, permission.length()).trim();
}
}
this.permission = permission;
}
public String getPermissionMessage() {
return permissionMessage;
}
public void setPermissionMessage(String permissionMessage) {
this.permissionMessage = permissionMessage;
}
public boolean hasViewPermission() {
return viewPermission != null;
}
public boolean canViewIcon(Player player) {
if (viewPermission == null) {
return true;
}
if (viewPermissionNegated) {
return !player.hasPermission(viewPermission);
} else {
return player.hasPermission(viewPermission);
}
}
public void setViewPermission(String viewPermission) {
if (StringUtils.isNullOrEmpty(viewPermission)) {
viewPermission = null;
}
if (viewPermission != null) {
if (viewPermission.startsWith("-")) {
viewPermissionNegated = true;
viewPermission = viewPermission.substring(1, viewPermission.length()).trim();
}
}
this.viewPermission = viewPermission;
}
public double getMoneyPrice() {
return moneyPrice;
}
public void setMoneyPrice(double moneyPrice) {
this.moneyPrice = moneyPrice;
}
public int getExpLevelsPrice() {
return expLevelsPrice;
}
public void setExpLevelsPrice(int expLevelsPrice) {
this.expLevelsPrice = expLevelsPrice;
}
public List<RequiredItem> getRequiredItems() {
return requiredItems;
}
public void setRequiredItems(List<RequiredItem> requiredItems) {
this.requiredItems = requiredItems;
}
public String calculateName(Player pov) {
return super.calculateName(pov);
}
public List<String> calculateLore(Player pov) {
return super.calculateLore(pov);
}
@Override
public boolean onClick(Player player) {
// Check all the requirements
if (!canClickIcon(player)) {
if (permissionMessage != null) {
player.sendMessage(permissionMessage);
} else {
player.sendMessage(ChestCommands.getLang().default_no_icon_permission);
}
return closeOnClick;
}
if (moneyPrice > 0) {
if (!EconomyBridge.hasValidEconomy()) {
player.sendMessage(ChatColor.RED + "This command has a price, but Vault with a compatible economy plugin was not found. For security, the command has been blocked. Please inform the staff.");
return closeOnClick;
}
if (!EconomyBridge.hasMoney(player, moneyPrice)) {
player.sendMessage(ChestCommands.getLang().no_money.replace("{money}", EconomyBridge.formatMoney(moneyPrice)));
return closeOnClick;
}
}
if (expLevelsPrice > 0) {
if (player.getLevel() < expLevelsPrice) {
player.sendMessage(ChestCommands.getLang().no_exp.replace("{levels}", Integer.toString(expLevelsPrice)));
return closeOnClick;
}
}
if (requiredItems != null) {
boolean notHasItem = false;
for (RequiredItem item : requiredItems) {
if (!item.hasItem(player)) {
notHasItem = true;
player.sendMessage(ChestCommands.getLang().no_required_item
.replace("{material}", MaterialsRegistry.formatMaterial(item.getMaterial()))
.replace("{amount}", Integer.toString(item.getAmount()))
.replace("{datavalue}", item.hasRestrictiveDataValue() ? Short.toString(item.getDataValue()) : ChestCommands.getLang().any)
);
}
}
if (notHasItem) {
return closeOnClick;
}
}
// Take the money and the required item
boolean changedVariables = false; // To update the placeholders
if (moneyPrice > 0) {
if (!EconomyBridge.takeMoney(player, moneyPrice)) {
player.sendMessage(ChatColor.RED + "Error: the transaction couldn't be executed. Please inform the staff.");
return closeOnClick;
}
changedVariables = true;
}
if (expLevelsPrice > 0) {
player.setLevel(player.getLevel() - expLevelsPrice);
}
if (requiredItems != null) {
for (RequiredItem item : requiredItems) {
item.takeItem(player);
}
}
if (changedVariables) {
InventoryView view = player.getOpenInventory();
if (view != null) {
Inventory topInventory = view.getTopInventory();
if (topInventory.getHolder() instanceof MenuInventoryHolder) {
MenuInventoryHolder menuHolder = (MenuInventoryHolder) topInventory.getHolder();
if (menuHolder.getIconMenu() instanceof ExtendedIconMenu) {
((ExtendedIconMenu) menuHolder.getIconMenu()).refresh(player, topInventory);
}
}
}
}
return super.onClick(player);
}
}

View File

@ -1,37 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal.icon;
import com.gmail.filoghost.chestcommands.config.AsciiPlaceholders;
import com.gmail.filoghost.chestcommands.internal.VariableManager;
import org.bukkit.entity.Player;
public abstract class IconCommand {
protected String command;
protected boolean hasVariables;
public IconCommand(String command) {
this.command = AsciiPlaceholders.placeholdersToSymbols(command).trim();
this.hasVariables = VariableManager.hasVariables(command);
}
public String getParsedCommand(Player executor) {
return hasVariables ? VariableManager.setVariables(command, executor) : command;
}
public abstract void execute(Player player);
}

View File

@ -1,33 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal.icon.command;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import com.gmail.filoghost.chestcommands.util.FormatUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class BroadcastIconCommand extends IconCommand {
public BroadcastIconCommand(String command) {
super(FormatUtils.addColors(command));
}
@Override
public void execute(Player player) {
Bukkit.broadcastMessage(getParsedCommand(player));
}
}

View File

@ -1,32 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal.icon.command;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class ConsoleIconCommand extends IconCommand {
public ConsoleIconCommand(String command) {
super(command);
}
@Override
public void execute(Player player) {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), getParsedCommand(player));
}
}

View File

@ -1,58 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal.icon.command;
import com.gmail.filoghost.chestcommands.bridge.BarAPIBridge;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import com.gmail.filoghost.chestcommands.util.FormatUtils;
import com.gmail.filoghost.chestcommands.util.Utils;
import org.bukkit.entity.Player;
public class DragonBarIconCommand extends IconCommand {
private String message;
private int seconds;
public DragonBarIconCommand(String command) {
super(command);
if (!hasVariables) {
parseBar(super.command);
}
}
private void parseBar(String command) {
seconds = 1;
message = command;
String[] split = command.split("\\|", 2); // Max of 2 pieces
if (split.length > 1 && Utils.isValidPositiveInteger(split[0].trim())) {
seconds = Integer.parseInt(split[0].trim());
message = split[1].trim();
}
message = FormatUtils.addColors(message);
}
@Override
public void execute(Player player) {
if (hasVariables) {
parseBar(getParsedCommand(player));
}
if (BarAPIBridge.hasValidPlugin()) {
BarAPIBridge.setMessage(player, message, seconds);
}
}
}

View File

@ -1,59 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal.icon.command;
import com.gmail.filoghost.chestcommands.exception.FormatException;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import com.gmail.filoghost.chestcommands.util.ItemStackReader;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class GiveIconCommand extends IconCommand {
private ItemStack itemToGive;
private String errorMessage;
public GiveIconCommand(String command) {
super(command);
if (!hasVariables) {
parseItem(super.command);
}
}
private void parseItem(String command) {
try {
ItemStackReader reader = new ItemStackReader(command, true);
itemToGive = reader.createStack();
errorMessage = null;
} catch (FormatException e) {
errorMessage = ChatColor.RED + "Invalid item to give: " + e.getMessage();
}
}
@Override
public void execute(Player player) {
if (hasVariables) {
parseItem(getParsedCommand(player));
}
if (errorMessage != null) {
player.sendMessage(errorMessage);
return;
}
player.getInventory().addItem(itemToGive.clone());
}
}

View File

@ -1,61 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal.icon.command;
import com.gmail.filoghost.chestcommands.bridge.EconomyBridge;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import com.gmail.filoghost.chestcommands.util.Utils;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class GiveMoneyIconCommand extends IconCommand {
private double moneyToGive;
private String errorMessage;
public GiveMoneyIconCommand(String command) {
super(command);
if (!hasVariables) {
parseMoney(super.command);
}
}
private void parseMoney(String command) {
if (!Utils.isValidPositiveDouble(command)) {
errorMessage = ChatColor.RED + "Invalid money amount: " + command;
return;
}
errorMessage = null;
moneyToGive = Double.parseDouble(command);
}
@Override
public void execute(Player player) {
if (hasVariables) {
parseMoney(getParsedCommand(player));
}
if (errorMessage != null) {
player.sendMessage(errorMessage);
return;
}
if (EconomyBridge.hasValidEconomy()) {
EconomyBridge.giveMoney(player, moneyToGive);
} else {
player.sendMessage(ChatColor.RED + "Vault with a compatible economy plugin not found. Please inform the staff.");
}
}
}

View File

@ -1,39 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal.icon.command;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import org.bukkit.entity.Player;
public class OpIconCommand extends IconCommand {
public OpIconCommand(String command) {
super(command);
}
@Override
public void execute(Player player) {
if (player.isOp()) {
player.chat("/" + getParsedCommand(player));
} else {
player.setOp(true);
player.chat("/" + getParsedCommand(player));
player.setOp(false);
}
}
}

View File

@ -1,55 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal.icon.command;
import com.gmail.filoghost.chestcommands.ChestCommands;
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class OpenIconCommand extends IconCommand {
public OpenIconCommand(String command) {
super(command);
}
@Override
public void execute(final Player player) {
String target = hasVariables ? getParsedCommand(player) : command;
final ExtendedIconMenu menu = ChestCommands.getFileNameToMenuMap().get(target.toLowerCase());
if (menu != null) {
/*
* Delay the task, since this command is executed in ClickInventoryEvent
* and opening another inventory in the same moment is not a good idea.
*/
Bukkit.getScheduler().scheduleSyncDelayedTask(ChestCommands.getInstance(), new Runnable() {
public void run() {
if (player.hasPermission(menu.getPermission())) {
menu.open(player);
} else {
menu.sendNoPermissionMessage(player);
}
}
});
} else {
player.sendMessage(ChatColor.RED + "Menu not found! Please inform the staff.");
}
}
}

View File

@ -1,31 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal.icon.command;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import org.bukkit.entity.Player;
public class PlayerIconCommand extends IconCommand {
public PlayerIconCommand(String command) {
super(command);
}
@Override
public void execute(Player player) {
player.chat('/' + getParsedCommand(player));
}
}

View File

@ -1,32 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal.icon.command;
import com.gmail.filoghost.chestcommands.bridge.bungee.BungeeCordUtils;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import org.bukkit.entity.Player;
public class ServerIconCommand extends IconCommand {
public ServerIconCommand(String command) {
super(command);
}
@Override
public void execute(Player player) {
BungeeCordUtils.connect(player, hasVariables ? getParsedCommand(player) : command);
}
}

View File

@ -1,78 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal.icon.command;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import com.gmail.filoghost.chestcommands.util.BukkitUtils;
import org.bukkit.ChatColor;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
public class SoundIconCommand extends IconCommand {
private Sound sound;
private float pitch;
private float volume;
private String errorMessage;
public SoundIconCommand(String command) {
super(command);
if (!hasVariables) {
parseSound(super.command);
}
}
private void parseSound(String command) {
errorMessage = null;
pitch = 1.0f;
volume = 1.0f;
String[] split = command.split(",");
sound = BukkitUtils.matchSound(split[0]);
if (sound == null) {
errorMessage = ChatColor.RED + "Invalid sound \"" + split[0].trim() + "\".";
return;
}
if (split.length > 1) {
try {
pitch = Float.parseFloat(split[1].trim());
} catch (NumberFormatException e) {
}
}
if (split.length > 2) {
try {
volume = Float.parseFloat(split[2].trim());
} catch (NumberFormatException e) {
}
}
}
@Override
public void execute(Player player) {
if (hasVariables) {
parseSound(getParsedCommand(player));
}
if (errorMessage != null) {
player.sendMessage(errorMessage);
return;
}
player.playSound(player.getLocation(), sound, volume, pitch);
}
}

View File

@ -1,32 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.internal.icon.command;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import com.gmail.filoghost.chestcommands.util.FormatUtils;
import org.bukkit.entity.Player;
public class TellIconCommand extends IconCommand {
public TellIconCommand(String command) {
super(FormatUtils.addColors(command));
}
@Override
public void execute(Player player) {
player.sendMessage(getParsedCommand(player));
}
}

View File

@ -1,54 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.listener;
import com.gmail.filoghost.chestcommands.ChestCommands;
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
import com.gmail.filoghost.chestcommands.util.StringUtils;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
public class CommandListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onCommand(PlayerCommandPreprocessEvent event) {
if (ChestCommands.getSettings().use_only_commands_without_args && event.getMessage().contains(" ")) {
return;
}
// Very fast method compared to split & substring
String command = StringUtils.getCleanCommand(event.getMessage());
if (command.isEmpty()) {
return;
}
ExtendedIconMenu menu = ChestCommands.getCommandToMenuMap().get(command);
if (menu != null) {
event.setCancelled(true);
if (event.getPlayer().hasPermission(menu.getPermission())) {
menu.open(event.getPlayer());
} else {
menu.sendNoPermissionMessage(event.getPlayer());
}
}
}
}

View File

@ -1,95 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.listener;
import com.gmail.filoghost.chestcommands.ChestCommands;
import com.gmail.filoghost.chestcommands.api.Icon;
import com.gmail.filoghost.chestcommands.api.IconMenu;
import com.gmail.filoghost.chestcommands.internal.BoundItem;
import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder;
import com.gmail.filoghost.chestcommands.task.ExecuteCommandsTask;
import com.gmail.filoghost.chestcommands.util.Utils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import java.util.Map;
public class InventoryListener implements Listener {
private static Map<Player, Long> antiClickSpam = Utils.newHashMap();
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false)
public void onInteract(PlayerInteractEvent event) {
if (event.hasItem() && event.getAction() != Action.PHYSICAL) {
for (BoundItem boundItem : ChestCommands.getBoundItems()) {
if (boundItem.isValidTrigger(event.getItem(), event.getAction())) {
if (event.getPlayer().hasPermission(boundItem.getMenu().getPermission())) {
boundItem.getMenu().open(event.getPlayer());
} else {
boundItem.getMenu().sendNoPermissionMessage(event.getPlayer());
}
}
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false)
public void onInventoryClick(InventoryClickEvent event) {
if (event.getInventory().getHolder() instanceof MenuInventoryHolder) {
event.setCancelled(true); // First thing to do, if an exception is thrown at least the player doesn't take the item
IconMenu menu = ((MenuInventoryHolder) event.getInventory().getHolder()).getIconMenu();
int slot = event.getRawSlot();
if (slot >= 0 && slot < menu.getSize()) {
Icon icon = menu.getIconRaw(slot);
if (icon != null && event.getInventory().getItem(slot) != null) {
Player clicker = (Player) event.getWhoClicked();
Long cooldownUntil = antiClickSpam.get(clicker);
long now = System.currentTimeMillis();
int minDelay = ChestCommands.getSettings().anti_click_spam_delay;
if (minDelay > 0) {
if (cooldownUntil != null && cooldownUntil > now) {
return;
} else {
antiClickSpam.put(clicker, now + minDelay);
}
}
// Closes the inventory and executes commands AFTER the event
Bukkit.getScheduler().scheduleSyncDelayedTask(ChestCommands.getInstance(), new ExecuteCommandsTask(clicker, icon));
}
}
}
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
antiClickSpam.remove(event.getPlayer());
}
}

View File

@ -1,39 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.listener;
import com.gmail.filoghost.chestcommands.ChestCommands;
import com.gmail.filoghost.chestcommands.Permissions;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
public class JoinListener implements Listener {
@EventHandler
public void onJoin(PlayerJoinEvent event) {
if (ChestCommands.getLastReloadErrors() > 0 && event.getPlayer().hasPermission(Permissions.SEE_ERRORS)) {
event.getPlayer().sendMessage(ChestCommands.CHAT_PREFIX + ChatColor.RED + "The plugin found " + ChestCommands.getLastReloadErrors() + " error(s) last time it was loaded. You can see them by doing \"/cc reload\" in the console.");
}
if (ChestCommands.hasNewVersion() && ChestCommands.getSettings().update_notifications && event.getPlayer().hasPermission(Permissions.UPDATE_NOTIFICATIONS)) {
event.getPlayer().sendMessage(ChestCommands.CHAT_PREFIX + "Found an update: " + ChestCommands.getNewVersion() + ". Download:");
event.getPlayer().sendMessage(ChatColor.DARK_GREEN + ">> " + ChatColor.GREEN + "http://dev.bukkit.org/bukkit-plugins/chest-commands");
}
}
}

View File

@ -1,89 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.listener;
import com.gmail.filoghost.chestcommands.ChestCommands;
import com.gmail.filoghost.chestcommands.Permissions;
import com.gmail.filoghost.chestcommands.api.IconMenu;
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
import com.gmail.filoghost.chestcommands.util.BukkitUtils;
import org.bukkit.ChatColor;
import org.bukkit.block.Sign;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
public class SignListener implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onInteract(PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.hasBlock() && event.getClickedBlock().getState() instanceof Sign) {
Sign sign = (Sign) event.getClickedBlock().getState();
if (sign.getLine(0).equalsIgnoreCase(ChatColor.DARK_BLUE + "[menu]")) {
sign.getLine(1);
ExtendedIconMenu iconMenu = ChestCommands.getFileNameToMenuMap().get(BukkitUtils.addYamlExtension(sign.getLine(1)));
if (iconMenu != null) {
if (event.getPlayer().hasPermission(iconMenu.getPermission())) {
iconMenu.open(event.getPlayer());
} else {
iconMenu.sendNoPermissionMessage(event.getPlayer());
}
} else {
sign.setLine(0, ChatColor.RED + ChatColor.stripColor(sign.getLine(0)));
event.getPlayer().sendMessage(ChestCommands.getLang().menu_not_found);
}
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onSignChange(SignChangeEvent event) {
if (event.getLine(0).equalsIgnoreCase("[menu]") && event.getPlayer().hasPermission(Permissions.SIGN_CREATE)) {
if (event.getLine(1).isEmpty()) {
event.setLine(0, ChatColor.RED + event.getLine(0));
event.getPlayer().sendMessage(ChatColor.RED + "You must set a valid menu name in the second line.");
return;
}
IconMenu iconMenu = ChestCommands.getFileNameToMenuMap().get(BukkitUtils.addYamlExtension(event.getLine(1)));
if (iconMenu == null) {
event.setLine(0, ChatColor.RED + event.getLine(0));
event.getPlayer().sendMessage(ChatColor.RED + "That menu was not found.");
return;
}
event.setLine(0, ChatColor.DARK_BLUE + event.getLine(0));
event.getPlayer().sendMessage(ChatColor.GREEN + "Successfully created a sign for the menu " + BukkitUtils.addYamlExtension(event.getLine(1)) + ".");
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onSignChangeMonitor(SignChangeEvent event) {
// Prevent players with permissions for creating colored signs from creating menu signs
if (event.getLine(0).equalsIgnoreCase(ChatColor.DARK_BLUE + "[menu]") && !event.getPlayer().hasPermission(Permissions.SIGN_CREATE)) {
event.setLine(0, ChatColor.stripColor(event.getLine(0)));
}
}
}

View File

@ -1,80 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.serializer;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import com.gmail.filoghost.chestcommands.internal.icon.command.*;
import com.gmail.filoghost.chestcommands.util.ErrorLogger;
import com.gmail.filoghost.chestcommands.util.Utils;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CommandSerializer {
private static Map<Pattern, Class<? extends IconCommand>> commandTypesMap = Utils.newHashMap();
static {
commandTypesMap.put(commandPattern("console:"), ConsoleIconCommand.class);
commandTypesMap.put(commandPattern("op:"), OpIconCommand.class);
commandTypesMap.put(commandPattern("(open|menu):"), OpenIconCommand.class);
commandTypesMap.put(commandPattern("server:?"), ServerIconCommand.class); // The colon is optional
commandTypesMap.put(commandPattern("tell:"), TellIconCommand.class);
commandTypesMap.put(commandPattern("broadcast:"), BroadcastIconCommand.class);
commandTypesMap.put(commandPattern("give:"), GiveIconCommand.class);
commandTypesMap.put(commandPattern("give-?money:"), GiveMoneyIconCommand.class);
commandTypesMap.put(commandPattern("sound:"), SoundIconCommand.class);
commandTypesMap.put(commandPattern("dragon-?bar:"), DragonBarIconCommand.class);
}
private static Pattern commandPattern(String regex) {
return Pattern.compile("^(?i)" + regex); // Case insensitive and only at the beginning
}
public static void checkClassConstructors(ErrorLogger errorLogger) {
for (Class<? extends IconCommand> clazz : commandTypesMap.values()) {
try {
clazz.getDeclaredConstructor(String.class).newInstance("");
} catch (Exception ex) {
String className = clazz.getName().replace("Command", "");
className = className.substring(className.lastIndexOf('.') + 1, className.length());
errorLogger.addError("Unable to register the \"" + className + "\" command type(" + ex.getClass().getName() + "), please inform the developer (filoghost). The plugin will still work, but all the \"" + className + "\" commands will be treated as normal commands.");
}
}
}
public static IconCommand matchCommand(String input) {
for (Entry<Pattern, Class<? extends IconCommand>> entry : commandTypesMap.entrySet()) {
Matcher matcher = entry.getKey().matcher(input);
if (matcher.find()) {
// Remove the command prefix and trim the spaces
String cleanCommand = matcher.replaceFirst("").trim();
try {
return entry.getValue().getDeclaredConstructor(String.class).newInstance(cleanCommand);
} catch (Exception e) {
// Checked at startup
}
}
}
return new PlayerIconCommand(input); // Normal command, no match found
}
}

View File

@ -1,120 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.serializer;
import com.gmail.filoghost.chestcommands.util.ErrorLogger;
import com.gmail.filoghost.chestcommands.util.StringUtils;
import org.bukkit.enchantments.Enchantment;
import java.util.HashMap;
import java.util.Map;
public class EnchantmentSerializer {
private static Map<String, Enchantment> enchantmentsMap = new HashMap<String, Enchantment>();
static {
enchantmentsMap.put(formatLowercase("Protection"), Enchantment.PROTECTION_ENVIRONMENTAL);
enchantmentsMap.put(formatLowercase("Fire Protection"), Enchantment.PROTECTION_FIRE);
enchantmentsMap.put(formatLowercase("Feather Falling"), Enchantment.PROTECTION_FALL);
enchantmentsMap.put(formatLowercase("Blast Protection"), Enchantment.PROTECTION_EXPLOSIONS);
enchantmentsMap.put(formatLowercase("Projectile Protection"), Enchantment.PROTECTION_PROJECTILE);
enchantmentsMap.put(formatLowercase("Respiration"), Enchantment.OXYGEN);
enchantmentsMap.put(formatLowercase("Aqua Affinity"), Enchantment.WATER_WORKER);
enchantmentsMap.put(formatLowercase("Thorns"), Enchantment.THORNS);
enchantmentsMap.put(formatLowercase("Sharpness"), Enchantment.DAMAGE_ALL);
enchantmentsMap.put(formatLowercase("Smite"), Enchantment.DAMAGE_UNDEAD);
enchantmentsMap.put(formatLowercase("Bane Of Arthropods"), Enchantment.DAMAGE_ARTHROPODS);
enchantmentsMap.put(formatLowercase("Knockback"), Enchantment.KNOCKBACK);
enchantmentsMap.put(formatLowercase("Fire Aspect"), Enchantment.FIRE_ASPECT);
enchantmentsMap.put(formatLowercase("Looting"), Enchantment.LOOT_BONUS_MOBS);
enchantmentsMap.put(formatLowercase("Efficiency"), Enchantment.DIG_SPEED);
enchantmentsMap.put(formatLowercase("Silk Touch"), Enchantment.SILK_TOUCH);
enchantmentsMap.put(formatLowercase("Unbreaking"), Enchantment.DURABILITY);
enchantmentsMap.put(formatLowercase("Fortune"), Enchantment.LOOT_BONUS_BLOCKS);
enchantmentsMap.put(formatLowercase("Power"), Enchantment.ARROW_DAMAGE);
enchantmentsMap.put(formatLowercase("Punch"), Enchantment.ARROW_KNOCKBACK);
enchantmentsMap.put(formatLowercase("Flame"), Enchantment.ARROW_FIRE);
enchantmentsMap.put(formatLowercase("Infinity"), Enchantment.ARROW_INFINITE);
enchantmentsMap.put(formatLowercase("Lure"), Enchantment.LURE);
enchantmentsMap.put(formatLowercase("Luck Of The Sea"), Enchantment.LUCK);
for (Enchantment enchant : Enchantment.values()) {
if (enchant != null) {
// Accepts the ugly default names too
enchantmentsMap.put(formatLowercase(enchant.getName()), enchant);
}
}
}
private static String formatLowercase(String string) {
return StringUtils.stripChars(string, " _-").toLowerCase();
}
public static EnchantmentDetails parseEnchantment(String input, String iconName, String menuFileName, ErrorLogger errorLogger) {
int level = 1;
if (input.contains(",")) {
String[] levelSplit = input.split(",");
try {
level = Integer.parseInt(levelSplit[1].trim());
} catch (NumberFormatException ex) {
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has an invalid enchantment level: " + levelSplit[1]);
}
input = levelSplit[0];
}
Enchantment ench = matchEnchantment(input);
if (ench == null) {
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has an invalid enchantment: " + input);
} else {
return new EnchantmentDetails(ench, level);
}
return null;
}
public static Enchantment matchEnchantment(String input) {
if (input == null) {
return null;
}
return enchantmentsMap.get(formatLowercase(input));
}
public static class EnchantmentDetails {
private final Enchantment enchantment;
private final int level;
public EnchantmentDetails(Enchantment enchantment, int level) {
this.enchantment = enchantment;
this.level = level;
}
public Enchantment getEnchantment() {
return enchantment;
}
public int getLevel() {
return level;
}
}
}

View File

@ -1,264 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.serializer;
import java.util.List;
import java.util.Map;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.enchantments.Enchantment;
import com.gmail.filoghost.chestcommands.ChestCommands;
import com.gmail.filoghost.chestcommands.api.Icon;
import com.gmail.filoghost.chestcommands.config.AsciiPlaceholders;
import com.gmail.filoghost.chestcommands.config.ConfigUtil;
import com.gmail.filoghost.chestcommands.exception.FormatException;
import com.gmail.filoghost.chestcommands.internal.CommandsClickHandler;
import com.gmail.filoghost.chestcommands.internal.RequiredItem;
import com.gmail.filoghost.chestcommands.internal.icon.ExtendedIcon;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import com.gmail.filoghost.chestcommands.serializer.EnchantmentSerializer.EnchantmentDetails;
import com.gmail.filoghost.chestcommands.util.ErrorLogger;
import com.gmail.filoghost.chestcommands.util.FormatUtils;
import com.gmail.filoghost.chestcommands.util.ItemStackReader;
import com.gmail.filoghost.chestcommands.util.ItemUtils;
import com.gmail.filoghost.chestcommands.util.Utils;
import com.gmail.filoghost.chestcommands.util.Validate;
import com.gmail.filoghost.chestcommands.util.nbt.parser.MojangsonParseException;
import com.gmail.filoghost.chestcommands.util.nbt.parser.MojangsonParser;
public class IconSerializer {
private static class Nodes {
public static final String[] MATERIAL = {"MATERIAL", "ID"};
public static final String AMOUNT = "AMOUNT";
public static final String[] DURABILITY = {"DURABILITY", "DATA-VALUE"};
public static final String[] NBT_DATA = {"NBT-DATA", "NBT"};
public static final String NAME = "NAME";
public static final String LORE = "LORE";
public static final String[] ENCHANTMENTS = {"ENCHANTMENTS", "ENCHANTMENT"};
public static final String COLOR = "COLOR";
public static final String SKULL_OWNER = "SKULL-OWNER";
public static final String BANNER_COLOR = "BANNER-COLOR";
public static final String BANNER_PATTERNS = "BANNER-PATTERNS";
public static final String[] ACTIONS = {"ACTIONS", "COMMAND"};
public static final String PRICE = "PRICE";
public static final String EXP_LEVELS = "LEVELS";
public static final String[] REQUIRED_ITEMS = {"REQUIRED-ITEMS", "REQUIRED-ITEM"};
public static final String PERMISSION = "PERMISSION";
public static final String PERMISSION_MESSAGE = "PERMISSION-MESSAGE";
public static final String VIEW_PERMISSION = "VIEW-PERMISSION";
public static final String KEEP_OPEN = "KEEP-OPEN";
public static final String POSITION_X = "POSITION-X";
public static final String POSITION_Y = "POSITION-Y";
}
public static class Coords {
private Integer x, y;
protected Coords(Integer x, Integer y) {
this.x = x;
this.y = y;
}
public boolean isSetX() {
return x != null;
}
public boolean isSetY() {
return y != null;
}
public Integer getX() {
return x;
}
public Integer getY() {
return y;
}
}
public static Icon loadIconFromSection(ConfigurationSection section, String iconName, String menuFileName, ErrorLogger errorLogger) {
Validate.notNull(section, "ConfigurationSection cannot be null");
// The icon is valid even without a Material
ExtendedIcon icon = new ExtendedIcon();
String material = ConfigUtil.getAnyString(section, Nodes.MATERIAL);
if (material != null) {
try {
ItemStackReader itemReader = new ItemStackReader(material, true);
icon.setMaterial(itemReader.getMaterial());
icon.setDataValue(itemReader.getDataValue());
icon.setAmount(itemReader.getAmount());
} catch (FormatException e) {
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has an invalid ID: " + e.getMessage());
}
}
if (section.isSet(Nodes.AMOUNT)) {
icon.setAmount(section.getInt(Nodes.AMOUNT));
}
Integer durability = ConfigUtil.getAnyInt(section, Nodes.DURABILITY);
if (durability != null) {
icon.setDataValue(durability.shortValue());
}
String nbtData = ConfigUtil.getAnyString(section, Nodes.NBT_DATA);
if (nbtData != null) {
try {
// Check that NBT has valid syntax before applying it to the icon
MojangsonParser.parse(nbtData);
icon.setNBTData(nbtData);
} catch (MojangsonParseException e) {
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has an invalid NBT-DATA: " + e.getMessage());
}
}
icon.setName(AsciiPlaceholders.placeholdersToSymbols(FormatUtils.colorizeName(section.getString(Nodes.NAME))));
icon.setLore(AsciiPlaceholders.placeholdersToSymbols(FormatUtils.colorizeLore(section.getStringList(Nodes.LORE))));
List<String> serializedEnchantments = ConfigUtil.getStringListOrInlineList(section, ";", Nodes.ENCHANTMENTS);
if (serializedEnchantments != null && !serializedEnchantments.isEmpty()) {
Map<Enchantment, Integer> enchantments = Utils.newHashMap();
for (String serializedEnchantment : serializedEnchantments) {
if (serializedEnchantment != null && !serializedEnchantment.isEmpty()) {
EnchantmentDetails enchantment = EnchantmentSerializer.parseEnchantment(serializedEnchantment, iconName, menuFileName, errorLogger);
if (enchantment != null) {
enchantments.put(enchantment.getEnchantment(), enchantment.getLevel());
}
}
}
if (!enchantments.isEmpty()) {
icon.setEnchantments(enchantments);
}
}
if (section.isSet(Nodes.COLOR)) {
try {
icon.setColor(ItemUtils.parseColor(section.getString(Nodes.COLOR)));
} catch (FormatException e) {
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has an invalid COLOR: " + e.getMessage());
}
}
icon.setSkullOwner(section.getString(Nodes.SKULL_OWNER));
String bannerColor = ConfigUtil.getAnyString(section, Nodes.BANNER_COLOR);
if (bannerColor != null) {
try {
icon.setBannerColor(ItemUtils.parseDyeColor(bannerColor));
} catch (FormatException e) {
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has an invalid BANNER-COLOR: " + e.getMessage());
}
}
if (section.isSet(Nodes.BANNER_PATTERNS)) {
try {
icon.setBannerPatterns(ItemUtils.parseBannerPatternList(section.getStringList(Nodes.BANNER_PATTERNS)));
} catch (FormatException e) {
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has an invalid BANNER-PATTERNS: " + e.getMessage());
}
}
icon.setPermission(section.getString(Nodes.PERMISSION));
icon.setPermissionMessage(FormatUtils.addColors(section.getString(Nodes.PERMISSION_MESSAGE)));
icon.setViewPermission(section.getString(Nodes.VIEW_PERMISSION));
boolean closeOnClick = !section.getBoolean(Nodes.KEEP_OPEN);
icon.setCloseOnClick(closeOnClick);
List<String> serializedCommands = ConfigUtil.getStringListOrInlineList(section, ChestCommands.getSettings().multiple_commands_separator, Nodes.ACTIONS);
if (serializedCommands != null && !serializedCommands.isEmpty()) {
List<IconCommand> commands = Utils.newArrayList();
for (String serializedCommand : serializedCommands) {
if (serializedCommand != null && !serializedCommand.isEmpty()) {
commands.add(CommandSerializer.matchCommand(serializedCommand));
}
}
if (!commands.isEmpty()) {
icon.setClickHandler(new CommandsClickHandler(commands, closeOnClick));
}
}
double price = section.getDouble(Nodes.PRICE);
if (price > 0.0) {
icon.setMoneyPrice(price);
} else if (price < 0.0) {
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has a negative PRICE: " + price);
}
int levels = section.getInt(Nodes.EXP_LEVELS);
if (levels > 0) {
icon.setExpLevelsPrice(levels);
} else if (levels < 0) {
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has negative LEVELS: " + levels);
}
List<String> serializedRequiredItems = ConfigUtil.getStringListOrSingle(section, Nodes.REQUIRED_ITEMS);
if (serializedRequiredItems != null && !serializedRequiredItems.isEmpty()) {
List<RequiredItem> requiredItems = Utils.newArrayList();
for (String serializedItem : serializedRequiredItems) {
try {
ItemStackReader itemReader = new ItemStackReader(serializedItem, true);
RequiredItem requiredItem = new RequiredItem(itemReader.getMaterial(), itemReader.getAmount());
if (itemReader.hasExplicitDataValue()) {
requiredItem.setRestrictiveDataValue(itemReader.getDataValue());
}
requiredItems.add(requiredItem);
} catch (FormatException e) {
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has invalid REQUIRED-ITEMS: " + e.getMessage());
}
}
if (!requiredItems.isEmpty()) {
icon.setRequiredItems(requiredItems);
}
}
return icon;
}
public static Coords loadCoordsFromSection(ConfigurationSection section) {
Validate.notNull(section, "ConfigurationSection cannot be null");
Integer x = null;
Integer y = null;
if (section.isInt(Nodes.POSITION_X)) {
x = section.getInt(Nodes.POSITION_X);
}
if (section.isInt(Nodes.POSITION_Y)) {
y = section.getInt(Nodes.POSITION_Y);
}
return new Coords(x, y);
}
}

View File

@ -1,167 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.serializer;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.configuration.ConfigurationSection;
import com.gmail.filoghost.chestcommands.ChestCommands;
import com.gmail.filoghost.chestcommands.api.Icon;
import com.gmail.filoghost.chestcommands.config.ConfigUtil;
import com.gmail.filoghost.chestcommands.config.yaml.PluginConfig;
import com.gmail.filoghost.chestcommands.exception.FormatException;
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
import com.gmail.filoghost.chestcommands.internal.MenuData;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import com.gmail.filoghost.chestcommands.serializer.IconSerializer.Coords;
import com.gmail.filoghost.chestcommands.util.ClickType;
import com.gmail.filoghost.chestcommands.util.ErrorLogger;
import com.gmail.filoghost.chestcommands.util.FormatUtils;
import com.gmail.filoghost.chestcommands.util.ItemStackReader;
import com.gmail.filoghost.chestcommands.util.Utils;
public class MenuSerializer {
private static class Nodes {
public static final String MENU_NAME = "menu-settings.name";
public static final String MENU_ROWS = "menu-settings.rows";
public static final String[] MENU_COMMANDS = {"menu-settings.command", "menu-settings.commands"};
public static final String[] OPEN_ACTIONS = {"menu-settings.open-actions", "menu-settings.open-action"};
public static final String[] OPEN_ITEM_MATERIAL = {"menu-settings.open-with-item.id", "menu-settings.open-with-item.material"};
public static final String OPEN_ITEM_LEFT_CLICK = "menu-settings.open-with-item.left-click";
public static final String OPEN_ITEM_RIGHT_CLICK = "menu-settings.open-with-item.right-click";
public static final String AUTO_REFRESH = "menu-settings.auto-refresh";
}
public static ExtendedIconMenu loadMenu(PluginConfig config, String title, int rows, ErrorLogger errorLogger) {
ExtendedIconMenu iconMenu = new ExtendedIconMenu(title, rows, config.getFileName());
for (String subSectionName : config.getKeys(false)) {
if (subSectionName.equals("menu-settings")) {
continue;
}
ConfigurationSection iconSection = config.getConfigurationSection(subSectionName);
Icon icon = IconSerializer.loadIconFromSection(iconSection, subSectionName, config.getFileName(), errorLogger);
Coords coords = IconSerializer.loadCoordsFromSection(iconSection);
if (!coords.isSetX() || !coords.isSetY()) {
errorLogger.addError("The icon \"" + subSectionName + "\" in the menu \"" + config.getFileName() + " is missing POSITION-X and/or POSITION-Y.");
continue;
}
if (iconMenu.getIcon(coords.getX(), coords.getY()) != null) {
errorLogger.addError("The icon \"" + subSectionName + "\" in the menu \"" + config.getFileName() + " is overriding another icon with the same position.");
}
iconMenu.setIcon(coords.getX(), coords.getY(), icon);
}
return iconMenu;
}
/**
* Reads all the settings of a menu. It will never return a null title, even if not set.
*/
public static MenuData loadMenuData(PluginConfig config, ErrorLogger errorLogger) {
String title = FormatUtils.addColors(config.getString(Nodes.MENU_NAME));
int rows;
if (title == null) {
errorLogger.addError("The menu \"" + config.getFileName() + "\" doesn't have a name set.");
title = ChatColor.DARK_RED + "No title set";
}
if (title.length() > 32) {
title = title.substring(0, 32);
}
if (config.isInt(Nodes.MENU_ROWS)) {
rows = config.getInt(Nodes.MENU_ROWS);
if (rows <= 0) {
rows = 1;
}
} else {
rows = 6; // Defaults to 6 rows
errorLogger.addError("The menu \"" + config.getFileName() + "\" doesn't have a the number of rows set, it will have 6 rows by default.");
}
MenuData menuData = new MenuData(title, rows);
List<String> triggeringCommands = ConfigUtil.getStringListOrInlineList(config, ";", Nodes.MENU_COMMANDS);
if (triggeringCommands != null) {
menuData.setCommands(triggeringCommands.toArray(new String[0]));
}
List<String> serializedOpenCommands = ConfigUtil.getStringListOrInlineList(config, ChestCommands.getSettings().multiple_commands_separator, Nodes.OPEN_ACTIONS);
if (serializedOpenCommands != null && !serializedOpenCommands.isEmpty()) {
List<IconCommand> openCommands = Utils.newArrayList();
for (String serializedCommand : serializedOpenCommands) {
if (serializedCommand != null && !serializedCommand.isEmpty()) {
openCommands.add(CommandSerializer.matchCommand(serializedCommand));
}
}
if (!openCommands.isEmpty()) {
menuData.setOpenActions(openCommands);
}
}
String openItemMaterial = ConfigUtil.getAnyString(config, Nodes.OPEN_ITEM_MATERIAL);
if (openItemMaterial != null) {
try {
ItemStackReader itemReader = new ItemStackReader(openItemMaterial, false);
menuData.setBoundMaterial(itemReader.getMaterial());
if (itemReader.hasExplicitDataValue()) {
menuData.setBoundDataValue(itemReader.getDataValue());
}
} catch (FormatException e) {
errorLogger.addError("The item \"" + openItemMaterial + "\" used to open the menu \"" + config.getFileName() + "\" is invalid: " + e.getMessage());
}
boolean leftClick = config.getBoolean(Nodes.OPEN_ITEM_LEFT_CLICK);
boolean rightClick = config.getBoolean(Nodes.OPEN_ITEM_RIGHT_CLICK);
if (leftClick || rightClick) {
menuData.setClickType(ClickType.fromOptions(leftClick, rightClick));
}
}
if (config.isSet(Nodes.AUTO_REFRESH)) {
int tenthsToRefresh = (int) (config.getDouble(Nodes.AUTO_REFRESH) * 10.0);
if (tenthsToRefresh < 1) {
tenthsToRefresh = 1;
}
menuData.setRefreshTenths(tenthsToRefresh);
}
return menuData;
}
}

View File

@ -1,56 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.task;
import com.gmail.filoghost.chestcommands.ChestCommands;
import com.gmail.filoghost.chestcommands.util.ErrorLogger;
import com.gmail.filoghost.chestcommands.util.StringUtils;
import com.gmail.filoghost.chestcommands.util.Utils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import java.util.List;
public class ErrorLoggerTask implements Runnable {
private ErrorLogger errorLogger;
public ErrorLoggerTask(ErrorLogger errorLogger) {
this.errorLogger = errorLogger;
}
@Override
public void run() {
List<String> lines = Utils.newArrayList();
lines.add(" ");
lines.add(ChatColor.RED + "#------------------- Chest Commands Errors -------------------#");
int count = 1;
for (String error : errorLogger.getErrors()) {
lines.add(ChatColor.GRAY + "" + (count++) + ") " + ChatColor.WHITE + error);
}
lines.add(ChatColor.RED + "#-------------------------------------------------------------#");
String output = StringUtils.join(lines, "\n");
if (ChestCommands.getSettings().use_console_colors) {
Bukkit.getConsoleSender().sendMessage(output);
} else {
System.out.println(ChatColor.stripColor(output));
}
}
}

View File

@ -1,42 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.task;
import com.gmail.filoghost.chestcommands.api.Icon;
import org.bukkit.entity.Player;
public class ExecuteCommandsTask implements Runnable {
private Player player;
private Icon icon;
public ExecuteCommandsTask(Player player, Icon icon) {
this.player = player;
this.icon = icon;
}
@Override
public void run() {
boolean close = icon.onClick(player);
if (close) {
player.closeInventory();
}
}
}

View File

@ -1,57 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.task;
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder;
import com.gmail.filoghost.chestcommands.util.BukkitUtils;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
public class RefreshMenusTask implements Runnable {
private long elapsedTenths;
@Override
public void run() {
for (Player player : BukkitUtils.getOnlinePlayers()) {
InventoryView view = player.getOpenInventory();
if (view == null) {
return;
}
Inventory topInventory = view.getTopInventory();
if (topInventory.getHolder() instanceof MenuInventoryHolder) {
MenuInventoryHolder menuHolder = (MenuInventoryHolder) topInventory.getHolder();
if (menuHolder.getIconMenu() instanceof ExtendedIconMenu) {
ExtendedIconMenu extMenu = (ExtendedIconMenu) menuHolder.getIconMenu();
if (extMenu.getRefreshTicks() > 0) {
if (elapsedTenths % extMenu.getRefreshTicks() == 0) {
extMenu.refresh(player, topInventory);
}
}
}
}
}
elapsedTenths++;
}
}

View File

@ -1,73 +0,0 @@
package com.gmail.filoghost.chestcommands.util;
import com.google.common.collect.ImmutableList;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
public final class BukkitUtils {
private static final Method LEGACY_GET_ONLINE_PLAYERS;
static {
try {
Method method = Bukkit.class.getDeclaredMethod("getOnlinePlayers");
LEGACY_GET_ONLINE_PLAYERS = method.getReturnType() == Player[].class ? method : null;
} catch (NoSuchMethodException e) {
// This should NEVER happen!
throw new IllegalStateException("Missing Bukkit.getOnlinePlayers() method!");
}
}
private BukkitUtils() {
}
public static Collection<? extends Player> getOnlinePlayers() {
try {
if (LEGACY_GET_ONLINE_PLAYERS == null) {
return Bukkit.getOnlinePlayers();
} else {
Player[] playersArray = (Player[]) LEGACY_GET_ONLINE_PLAYERS.invoke(null);
return ImmutableList.copyOf(playersArray);
}
} catch (Exception e) {
e.printStackTrace();
return Collections.emptyList();
}
}
public static String addYamlExtension(String input) {
if (input == null) {
return null;
}
return input.toLowerCase().endsWith(".yml") ? input : input + ".yml";
}
public static void saveResourceSafe(Plugin plugin, String name) {
try {
plugin.saveResource(name, false);
} catch (Exception ignored) {
}
}
public static Sound matchSound(String input) {
if (input == null) {
return null;
}
input = StringUtils.stripChars(input.toLowerCase(), " _-");
for (Sound sound : Sound.values()) {
if (StringUtils.stripChars(sound.toString().toLowerCase(), "_").equals(input)) {
return sound;
}
}
return null;
}
}

View File

@ -1,63 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.util;
import java.util.HashMap;
import java.util.Map;
public class CaseInsensitiveMap<V> extends HashMap<String, V> {
private static final long serialVersionUID = 4712822893326841081L;
public static <K> CaseInsensitiveMap<K> create() {
return new CaseInsensitiveMap<K>();
}
@Override
public V put(String key, V value) {
return super.put(key.toLowerCase(), value);
}
@Override
public V get(Object key) {
return super.get(key.getClass() == String.class ? key.toString().toLowerCase() : key);
}
public String getKey(V value) {
for (java.util.Map.Entry<String, V> entry : entrySet()) {
if (entry.getValue().equals(value)) {
return entry.getKey();
}
}
return null;
}
@Override
public boolean containsKey(Object key) {
return super.containsKey(key.getClass() == String.class ? key.toString().toLowerCase() : key);
}
@Override
public V remove(Object key) {
return super.remove(key.getClass() == String.class ? key.toString().toLowerCase() : key);
}
@Override
public void putAll(Map<? extends String, ? extends V> m) {
throw new UnsupportedOperationException("putAll not supported");
}
}

View File

@ -1,47 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.util;
import org.bukkit.event.block.Action;
public enum ClickType {
LEFT,
RIGHT,
BOTH;
public static ClickType fromOptions(boolean left, boolean right) {
if (left && right) {
return BOTH;
} else if (left && !right) {
return LEFT;
} else if (!left && right) {
return RIGHT;
} else {
return null;
}
}
public boolean isValidInteract(Action action) {
if (action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK) {
return this == LEFT || this == BOTH;
} else if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK) {
return this == RIGHT || this == BOTH;
} else {
return false;
}
}
}

View File

@ -1,43 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.util;
import java.util.ArrayList;
import java.util.List;
/**
* This is a class to collect all the errors found while loading the plugin.
*/
public class ErrorLogger {
private List<String> errors = new ArrayList<String>();
public void addError(String error) {
errors.add(error);
}
public List<String> getErrors() {
return new ArrayList<String>(errors);
}
public boolean hasErrors() {
return errors.size() > 0;
}
public int getSize() {
return errors.size();
}
}

View File

@ -1,57 +0,0 @@
package com.gmail.filoghost.chestcommands.util;
import com.gmail.filoghost.chestcommands.ChestCommands;
import org.bukkit.ChatColor;
import java.text.DecimalFormat;
import java.util.List;
public final class FormatUtils {
private static DecimalFormat decimalFormat = new DecimalFormat("0.##");
public static String decimalFormat(double number) {
return decimalFormat.format(number);
}
public static String addColors(String input) {
if (input == null || input.isEmpty()) return input;
return ChatColor.translateAlternateColorCodes('&', input);
}
public static List<String> addColors(List<String> input) {
if (input == null || input.isEmpty()) return input;
for (int i = 0; i < input.size(); i++) {
input.set(i, addColors(input.get(i)));
}
return input;
}
public static String colorizeName(String input) {
if (input == null || input.isEmpty()) return input;
if (input.charAt(0) != ChatColor.COLOR_CHAR) {
return ChestCommands.getSettings().default_color__name + addColors(input);
} else {
return addColors(input);
}
}
public static List<String> colorizeLore(List<String> input) {
if (input == null || input.isEmpty()) return input;
for (int i = 0; i < input.size(); i++) {
String line = input.get(i);
if (line.isEmpty()) continue;
if (line.charAt(0) != ChatColor.COLOR_CHAR) {
input.set(i, ChestCommands.getSettings().default_color__lore + addColors(line));
} else {
input.set(i, addColors(line));
}
}
return input;
}
}

View File

@ -1,52 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.util;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
public class InventoryUtils {
public static boolean hasInventoryFull(Player player) {
return player.getInventory().firstEmpty() == -1;
}
public static boolean containsAtLeast(Inventory inv, Material material, int minAmount) {
int contained = 0;
for (ItemStack item : inv.getContents()) {
if (item != null && item.getType() == material) {
contained += item.getAmount();
}
}
return contained >= minAmount;
}
public static boolean containsAtLeast(Inventory inv, Material material, int minAmount, short data) {
int contained = 0;
for (ItemStack item : inv.getContents()) {
if (item != null && item.getType() == material && item.getDurability() == data) {
contained += item.getAmount();
}
}
return contained >= minAmount;
}
}

View File

@ -1,108 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.util;
import com.gmail.filoghost.chestcommands.exception.FormatException;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
public class ItemStackReader {
private Material material = Material.STONE; // In the worst case (bad exception handling) we just get stone
private int amount = 1;
private short dataValue = 0;
private boolean explicitDataValue = false;
/**
* Reads item in the format "id:data, amount"
* id can be either the id of the material or its name.
* for example wool:5, 3 is a valid input.
*/
public ItemStackReader(String input, boolean parseAmount) throws FormatException {
Validate.notNull(input, "input cannot be null");
// Remove spaces, they're not needed
input = StringUtils.stripChars(input, " _-");
if (parseAmount) {
// Read the optional amount
String[] splitAmount = input.split(",");
if (splitAmount.length > 1) {
if (!Utils.isValidInteger(splitAmount[1])) {
throw new FormatException("invalid amount \"" + splitAmount[1] + "\"");
}
int amount = Integer.parseInt(splitAmount[1]);
if (amount <= 0) throw new FormatException("invalid amount \"" + splitAmount[1] + "\"");
this.amount = amount;
// Only keep the first part as input
input = splitAmount[0];
}
}
// Read the optional data value
String[] splitByColons = input.split(":");
if (splitByColons.length > 1) {
if (!Utils.isValidShort(splitByColons[1])) {
throw new FormatException("invalid data value \"" + splitByColons[1] + "\"");
}
short dataValue = Short.parseShort(splitByColons[1]);
if (dataValue < 0) {
throw new FormatException("invalid data value \"" + splitByColons[1] + "\"");
}
this.explicitDataValue = true;
this.dataValue = dataValue;
// Only keep the first part as input
input = splitByColons[0];
}
Material material = MaterialsRegistry.matchMaterial(input);
if (material == null || MaterialsRegistry.isAir(material)) {
throw new FormatException("invalid material \"" + input + "\"");
}
this.material = material;
}
public Material getMaterial() {
return material;
}
public int getAmount() {
return amount;
}
public short getDataValue() {
return dataValue;
}
public boolean hasExplicitDataValue() {
return explicitDataValue;
}
public ItemStack createStack() {
return new ItemStack(material, amount, dataValue);
}
}

View File

@ -1,179 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.util;
import com.gmail.filoghost.chestcommands.exception.FormatException;
import org.bukkit.Color;
import org.bukkit.DyeColor;
import org.bukkit.block.banner.Pattern;
import org.bukkit.block.banner.PatternType;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public final class ItemUtils {
private static final boolean USE_ITEM_FLAGS_API;
private static final boolean USE_ITEM_FLAGS_REFLECTION;
// Reflection stuff
private static Class<?> nbtTagCompoundClass;
private static Class<?> nbtTagListClass;
private static Class<?> nmsItemstackClass;
private static Method asNmsCopyMethod;
private static Method asCraftMirrorMethod;
private static Method hasTagMethod;
private static Method getTagMethod;
private static Method setTagMethod;
private static Method nbtSetMethod;
static {
if (Utils.isClassLoaded("org.bukkit.inventory.ItemFlag")) {
// We can use the new Bukkit API (1.8.3+)
USE_ITEM_FLAGS_API = true;
USE_ITEM_FLAGS_REFLECTION = false;
} else {
USE_ITEM_FLAGS_API = false;
// Try to get the NMS methods and classes
boolean success;
try {
nbtTagCompoundClass = NMSUtils.getNMSClass("NBTTagCompound");
nbtTagListClass = NMSUtils.getNMSClass("NBTTagList");
nmsItemstackClass = NMSUtils.getNMSClass("ItemStack");
asNmsCopyMethod = NMSUtils.getCraftBukkitClass("inventory.CraftItemStack").getMethod("asNMSCopy", ItemStack.class);
asCraftMirrorMethod = NMSUtils.getCraftBukkitClass("inventory.CraftItemStack").getMethod("asCraftMirror", nmsItemstackClass);
hasTagMethod = nmsItemstackClass.getMethod("hasTag");
getTagMethod = nmsItemstackClass.getMethod("getTag");
setTagMethod = nmsItemstackClass.getMethod("setTag", nbtTagCompoundClass);
nbtSetMethod = nbtTagCompoundClass.getMethod("set", String.class, NMSUtils.getNMSClass("NBTBase"));
success = true;
} catch (Exception e) {
new IllegalStateException("Could not enable the attribute remover for this version." +
"Attributes will show up on items.", e).printStackTrace();
success = false;
}
USE_ITEM_FLAGS_REFLECTION = success;
}
}
private ItemUtils() {
}
public static ItemStack hideAttributes(ItemStack item) {
if (item == null) {
return null;
}
if (USE_ITEM_FLAGS_API) {
ItemMeta meta = item.getItemMeta();
if (Utils.isNullOrEmpty(meta.getItemFlags())) {
// Add them only if necessary
meta.addItemFlags(ItemFlag.values());
item.setItemMeta(meta);
}
return item;
} else if (USE_ITEM_FLAGS_REFLECTION) {
try {
Object nmsItemstack = asNmsCopyMethod.invoke(null, item);
if (nmsItemstack == null) {
return item;
}
Object nbtCompound;
if ((Boolean) hasTagMethod.invoke(nmsItemstack)) {
nbtCompound = getTagMethod.invoke(nmsItemstack);
} else {
nbtCompound = nbtTagCompoundClass.newInstance();
setTagMethod.invoke(nmsItemstack, nbtCompound);
}
if (nbtCompound == null) {
return item;
}
Object nbtList = nbtTagListClass.newInstance();
nbtSetMethod.invoke(nbtCompound, "AttributeModifiers", nbtList);
return (ItemStack) asCraftMirrorMethod.invoke(null, nmsItemstack);
} catch (Throwable t) {
// Ignore
}
}
// On failure just return the item
return item;
}
public static Color parseColor(String input) throws FormatException {
String[] split = StringUtils.stripChars(input, " ").split(",");
if (split.length != 3) {
throw new FormatException("it must be in the format \"red, green, blue\".");
}
int red, green, blue;
try {
red = Integer.parseInt(split[0]);
green = Integer.parseInt(split[1]);
blue = Integer.parseInt(split[2]);
} catch (NumberFormatException ex) {
throw new FormatException("it contains invalid numbers.");
}
if (red < 0 || red > 255 || green < 0 || green > 255 || blue < 0 || blue > 255) {
throw new FormatException("it should only contain numbers between 0 and 255.");
}
return Color.fromRGB(red, green, blue);
}
public static DyeColor parseDyeColor(String input) throws FormatException {
DyeColor color;
try {
color = DyeColor.valueOf(input.toUpperCase());
} catch (IllegalArgumentException e) {
throw new FormatException("it must be a valid color.");
}
return color;
}
public static List<Pattern> parseBannerPatternList(List<String> input) throws FormatException {
List<Pattern> patterns = new ArrayList<Pattern>();
for (String str : input) {
String[] split = str.split(":");
if (split.length != 2) {
throw new FormatException("it must be in the format \"pattern:color\".");
}
try {
patterns.add(new Pattern(parseDyeColor(split[1]), PatternType.valueOf(split[0].toUpperCase())));
} catch (IllegalArgumentException e) {
throw new FormatException("it must be a valid pattern type.");
}
}
return patterns;
}
}

View File

@ -1,152 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.util;
import org.bukkit.Material;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
@SuppressWarnings("deprecation")
public final class MaterialsRegistry {
// Material names have been changed in 1.13, when dolphins were added
private static final boolean USE_NEW_MATERIAL_NAMES = Utils.isClassLoaded("org.bukkit.entity.Dolphin");
// Characters to ignore when searching materials by name
private static final char[] IGNORE_CHARS = {'-', '_', ' '};
// Default material names are ugly
private static final Map<String, Material> MATERIALS_BY_ALIAS = new HashMap<String, Material>();
// Materials that are considered air (with 1.13+ compatibility)
private static final Collection<Material> AIR_MATERIALS = getExistingMaterials("AIR", "CAVE_AIR", "VOID_AIR");
private MaterialsRegistry() {
}
private static void addMaterialAlias(String name, Material material) {
MATERIALS_BY_ALIAS.put(StringUtils.stripChars(name, IGNORE_CHARS).toLowerCase(), material);
}
private static void tryAddMaterialAlias(String name, String materialEnumName) {
try {
addMaterialAlias(name, Material.valueOf(materialEnumName));
} catch (IllegalArgumentException e) {
// Ignore, do not add a new alias
}
}
public static Material matchMaterial(String alias) {
if (alias == null) {
return null;
}
return MATERIALS_BY_ALIAS.get(StringUtils.stripChars(alias, IGNORE_CHARS).toLowerCase());
}
public static String formatMaterial(Material material) {
return StringUtils.capitalizeFully(material.toString().replace("_", " "));
}
public static Collection<Material> getExistingMaterials(String... materialEnumNames) {
Collection<Material> existingMaterials = new HashSet<Material>();
for (String materialEnumName : materialEnumNames) {
try {
existingMaterials.add(Material.valueOf(materialEnumName));
} catch (IllegalArgumentException e) {
// Ignore, not existing
}
}
return existingMaterials;
}
public static boolean isAir(Material material) {
return AIR_MATERIALS.contains(material);
}
public static boolean useNewMaterialNames() {
return USE_NEW_MATERIAL_NAMES;
}
static {
for (Material material : Material.values()) {
addMaterialAlias(material.toString(), material);
if (!useNewMaterialNames()) {
// Add numerical IDs in versions before 1.13
addMaterialAlias(String.valueOf(material.getId()), material);
}
}
// Add some default useful aliases (when present)
tryAddMaterialAlias("iron bar", "IRON_FENCE");
tryAddMaterialAlias("iron bars", "IRON_FENCE");
tryAddMaterialAlias("glass pane", "THIN_GLASS");
tryAddMaterialAlias("nether wart", "NETHER_STALK");
tryAddMaterialAlias("nether warts", "NETHER_STALK");
tryAddMaterialAlias("slab", "STEP");
tryAddMaterialAlias("double slab", "DOUBLE_STEP");
tryAddMaterialAlias("stone brick", "SMOOTH_BRICK");
tryAddMaterialAlias("stone bricks", "SMOOTH_BRICK");
tryAddMaterialAlias("stone stair", "SMOOTH_STAIRS");
tryAddMaterialAlias("stone stairs", "SMOOTH_STAIRS");
tryAddMaterialAlias("potato", "POTATO_ITEM");
tryAddMaterialAlias("carrot", "CARROT_ITEM");
tryAddMaterialAlias("brewing stand", "BREWING_STAND_ITEM");
tryAddMaterialAlias("cauldron", "CAULDRON_ITEM");
tryAddMaterialAlias("carrot on stick", "CARROT_STICK");
tryAddMaterialAlias("carrot on a stick", "CARROT_STICK");
tryAddMaterialAlias("cobblestone wall", "COBBLE_WALL");
tryAddMaterialAlias("acacia wood stairs", "ACACIA_STAIRS");
tryAddMaterialAlias("dark oak wood stairs", "DARK_OAK_STAIRS");
tryAddMaterialAlias("wood slab", "WOOD_STEP");
tryAddMaterialAlias("double wood slab", "WOOD_DOUBLE_STEP");
tryAddMaterialAlias("repeater", "DIODE");
tryAddMaterialAlias("piston", "PISTON_BASE");
tryAddMaterialAlias("sticky piston", "PISTON_STICKY_BASE");
tryAddMaterialAlias("flower pot", "FLOWER_POT_ITEM");
tryAddMaterialAlias("wood showel", "WOOD_SPADE");
tryAddMaterialAlias("stone showel", "STONE_SPADE");
tryAddMaterialAlias("gold showel", "GOLD_SPADE");
tryAddMaterialAlias("iron showel", "IRON_SPADE");
tryAddMaterialAlias("diamond showel", "DIAMOND_SPADE");
tryAddMaterialAlias("steak", "COOKED_BEEF");
tryAddMaterialAlias("cooked porkchop", "GRILLED_PORK");
tryAddMaterialAlias("raw porkchop", "PORK");
tryAddMaterialAlias("hardened clay", "HARD_CLAY");
tryAddMaterialAlias("huge brown mushroom", "HUGE_MUSHROOM_1");
tryAddMaterialAlias("huge red mushroom", "HUGE_MUSHROOM_2");
tryAddMaterialAlias("mycelium", "MYCEL");
tryAddMaterialAlias("poppy", "RED_ROSE");
tryAddMaterialAlias("comparator", "REDSTONE_COMPARATOR");
tryAddMaterialAlias("skull", "SKULL_ITEM");
tryAddMaterialAlias("head", "SKULL_ITEM");
tryAddMaterialAlias("redstone torch", "REDSTONE_TORCH_ON");
tryAddMaterialAlias("redstone lamp", "REDSTONE_LAMP_OFF");
tryAddMaterialAlias("glistering melon", "SPECKLED_MELON");
tryAddMaterialAlias("acacia leaves", "LEAVES_2");
tryAddMaterialAlias("acacia log", "LOG_2");
tryAddMaterialAlias("gunpowder", "SULPHUR");
tryAddMaterialAlias("lilypad", "WATER_LILY");
tryAddMaterialAlias("command block", "COMMAND");
tryAddMaterialAlias("dye", "INK_SACK");
}
}

View File

@ -1,27 +0,0 @@
package com.gmail.filoghost.chestcommands.util;
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
public final class MenuUtils {
private MenuUtils() {
}
public static void refreshMenu(Player player) {
InventoryView view = player.getOpenInventory();
if (view != null) {
Inventory topInventory = view.getTopInventory();
if (topInventory.getHolder() instanceof MenuInventoryHolder) {
MenuInventoryHolder menuHolder = (MenuInventoryHolder) topInventory.getHolder();
if (menuHolder.getIconMenu() instanceof ExtendedIconMenu) {
((ExtendedIconMenu) menuHolder.getIconMenu()).refresh(player, topInventory);
}
}
}
}
}

View File

@ -1,29 +0,0 @@
package com.gmail.filoghost.chestcommands.util;
import org.bukkit.Bukkit;
public final class NMSUtils {
private static final String NMS_VERSION;
static {
String packageName = Bukkit.getServer().getClass().getPackage().getName();
NMS_VERSION = packageName.substring(packageName.lastIndexOf('.') + 1);
}
private NMSUtils() {
}
public static String getNMSVersion() {
return NMS_VERSION;
}
public static Class<?> getNMSClass(String name) throws ClassNotFoundException {
return Class.forName("net.minecraft.server." + NMSUtils.getNMSVersion() + "." + name);
}
public static Class<?> getCraftBukkitClass(String name) throws ClassNotFoundException {
return Class.forName("org.bukkit.craftbukkit." + NMSUtils.getNMSVersion() + "." + name);
}
}

View File

@ -1,126 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.util;
import java.util.Iterator;
public final class StringUtils {
private StringUtils() {
}
public static String stripChars(String input, String removed) {
if (removed == null || removed.isEmpty()) {
return input;
}
return stripChars(input, removed.toCharArray());
}
// Removes the first slash, and returns the all the chars until a space is encontered
public static String getCleanCommand(String message) {
char[] chars = message.toCharArray();
if (chars.length <= 1) {
return "";
}
int pos = 0;
for (int i = 1; i < chars.length; i++) {
if (chars[i] == ' ') {
break;
}
chars[(pos++)] = chars[i];
}
return new String(chars, 0, pos);
}
public static String stripChars(String input, char... removed) {
if (input == null || input.isEmpty() || removed.length == 0) {
return input;
}
char[] chars = input.toCharArray();
int pos = 0;
for (int i = 0; i < chars.length; i++) {
if (!arrayContains(removed, chars[i])) {
chars[(pos++)] = chars[i];
}
}
return new String(chars, 0, pos);
}
private static boolean arrayContains(char[] arr, char match) {
for (char c : arr) {
if (c == match) {
return true;
}
}
return false;
}
public static String capitalizeFully(String input) {
if (input == null) return null;
String s = input.toLowerCase();
int strLen = s.length();
StringBuffer buffer = new StringBuffer(strLen);
boolean capitalizeNext = true;
for (int i = 0; i < strLen; i++) {
char ch = s.charAt(i);
if (Character.isWhitespace(ch)) {
buffer.append(ch);
capitalizeNext = true;
} else if (capitalizeNext) {
buffer.append(Character.toTitleCase(ch));
capitalizeNext = false;
} else {
buffer.append(ch);
}
}
return buffer.toString();
}
public static boolean isNullOrEmpty(String s) {
return s == null || s.isEmpty();
}
public static String join(Iterable<?> iterable, String separator) {
StringBuilder builder = new StringBuilder();
Iterator<?> iter = iterable.iterator();
boolean first = true;
while (iter.hasNext()) {
if (first) {
first = false;
} else {
builder.append(separator);
}
builder.append(iter.next());
}
return builder.toString();
}
}

View File

@ -1,117 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.util;
import java.io.*;
import java.util.*;
public final class Utils {
private Utils() {
}
public static int makePositive(int i) {
return i < 0 ? 0 : i;
}
public static boolean isValidInteger(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException ex) {
return false;
}
}
public static boolean isValidPositiveInteger(String input) {
try {
return Integer.parseInt(input) > 0;
} catch (NumberFormatException ex) {
return false;
}
}
public static boolean isValidShort(String input) {
try {
Short.parseShort(input);
return true;
} catch (NumberFormatException ex) {
return false;
}
}
public static boolean isValidPositiveDouble(String input) {
try {
return Double.parseDouble(input) > 0.0;
} catch (NumberFormatException ex) {
return false;
}
}
public static List<String> readLines(File file) throws IOException, Exception {
BufferedReader br = null;
try {
List<String> lines = newArrayList();
if (!file.exists()) {
throw new FileNotFoundException();
}
br = new BufferedReader(new FileReader(file));
String line = br.readLine();
while (line != null) {
lines.add(line);
line = br.readLine();
}
return lines;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
}
}
}
}
public static <T> Set<T> newHashSet() {
return new HashSet<T>();
}
public static <T, V> Map<T, V> newHashMap() {
return new HashMap<T, V>();
}
public static <T> List<T> newArrayList() {
return new ArrayList<T>();
}
public static boolean isClassLoaded(String name) {
try {
Class.forName(name);
return true;
} catch (Throwable t) {
return false;
}
}
public static boolean isNullOrEmpty(Collection<?> collection) {
return collection == null || collection.isEmpty();
}
}

View File

@ -1,40 +0,0 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.util;
public final class Validate {
private Validate() {
}
public static void notNull(Object object, String error) {
if (object == null) {
throw new NullPointerException(error);
}
}
public static void isTrue(boolean statement, String error) {
if (!statement) {
throw new IllegalArgumentException(error);
}
}
public static void isFalse(boolean statement, String error) {
if (statement) {
throw new IllegalArgumentException(error);
}
}
}

View File

@ -1,21 +0,0 @@
#
# This is the configuration file for static placeholders.
# Dynamic placeholders are {online}, {max_players}, ...
# Static placeholders are symbols.
#
# List of unicode symbols: http://www.fileformat.info/info/unicode/index.htm
#
<3: \u2764
[*]: \u2605
[**]: \u2739
[p]: \u2022
[v]: \u2714
[+]: \u25C6
[++]: \u2726
[x]: \u2588
[/]: \u258C
[cross]: \u2720
[arrow_right]: \u27A1
[arrow_left]: \u2B05
[arrow_up]: \u2B06
[arrow_down]:\u2B07

View File

@ -1,6 +1,6 @@
ChestCommands
===================
Bukkit Page: http://dev.bukkit.org/bukkit-plugins/chest-commands
Bukkit Page: http://dev.bukkit.org/projects/chest-commands
Chest Commands is free software/open source, and is distributed under the [GPL 3.0 License](https://opensource.org/licenses/GPL-3.0). It contains third-party code, see the included THIRD-PARTY.txt file for the license information on third-party code.

View File

@ -1,9 +1,17 @@
Chest Commands contains code from the following third party projects, listed with their license information.
Chest Commands contains code from the following third-party open source
projects, listed with their license information.
[bStats Metrics]
URL: https://github.com/Bastian/bStats-Metrics
License: GNU Lesser General Public License v3.0
bStats Metrics
URL: https://github.com/Bastian/bStats-Metrics
License name: GNU Lesser General Public License v3.0
License file: /licenses/LICENSE-bStats.txt
[EisenNBT]
URL: https://github.com/Eisenwave/eisen-nbt
License: MIT License
EisenNBT
URL: https://github.com/Eisenwave/eisen-nbt
License name: MIT License
License file: /licenses/LICENSE-EisenNBT.txt
Update Checker
URL: https://github.com/filoghost/UpdateChecker
License name: MIT License
License file: /licenses/LICENSE-UpdateChecker.txt

28
api/pom.xml Normal file
View File

@ -0,0 +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>
<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>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>chestcommands-commons</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,56 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.chestcommands.api;
import me.filoghost.chestcommands.api.internal.BackendAPI;
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);
}
/**
* 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

@ -0,0 +1,19 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.chestcommands.api;
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);
}

View File

@ -0,0 +1,13 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.chestcommands.api;
public enum ClickResult {
KEEP_OPEN,
CLOSE
}

View File

@ -0,0 +1,25 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.chestcommands.api;
import org.bukkit.entity.Player;
public interface ClickableIcon extends Icon {
void setClickHandler(ClickHandler clickHandler);
ClickHandler getClickHandler();
@Override
default ClickResult onClick(MenuView menuView, Player clicker) {
if (getClickHandler() != null) {
return getClickHandler().onClick(menuView, clicker);
} else {
return ClickResult.KEEP_OPEN;
}
}
}

View File

@ -0,0 +1,78 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.chestcommands.api;
import me.filoghost.chestcommands.api.internal.BackendAPI;
import org.bukkit.Color;
import org.bukkit.DyeColor;
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);
Material getMaterial();
void setAmount(int amount);
int getAmount();
void setDurability(short durability);
short getDurability();
void setNBTData(String nbtData);
String getNBTData();
void setName(String name);
String getName();
void setLore(String... lore);
void setLore(List<String> lore);
List<String> getLore();
void setEnchantments(Map<Enchantment, Integer> enchantments);
Map<Enchantment, Integer> getEnchantments();
void addEnchantment(Enchantment enchantment);
void addEnchantment(Enchantment enchantment, Integer level);
void removeEnchantment(Enchantment enchantment);
Color getLeatherColor();
void setLeatherColor(Color leatherColor);
String getSkullOwner();
void setSkullOwner(String skullOwner);
DyeColor getBannerColor();
void setBannerColor(DyeColor bannerColor);
List<Pattern> getBannerPatterns();
void setBannerPatterns(List<Pattern> bannerPatterns);
void setPlaceholdersEnabled(boolean enabled);
}

View File

@ -0,0 +1,17 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.chestcommands.api;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public interface Icon {
ItemStack render(Player viewer);
ClickResult onClick(MenuView menuView, Player clicker);
}

View File

@ -0,0 +1,38 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.chestcommands.api;
import me.filoghost.chestcommands.api.internal.BackendAPI;
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);
Icon getIcon(int row, int column);
String getTitle();
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

@ -0,0 +1,18 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.chestcommands.api;
import org.bukkit.entity.Player;
public interface MenuView {
void refresh();
Player getViewer();
Menu getMenu();
}

View File

@ -0,0 +1,14 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.chestcommands.api;
import org.bukkit.entity.Player;
public interface PlaceholderReplacer {
String getReplacement(Player player, String argument);
}

View File

@ -0,0 +1,21 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.chestcommands.api;
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);
}
ItemStack getItemStack();
void setItemStack(ItemStack itemStack);
}

View File

@ -0,0 +1,47 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.chestcommands.api.internal;
import me.filoghost.chestcommands.api.ConfigurableIcon;
import me.filoghost.chestcommands.api.Menu;
import me.filoghost.chestcommands.api.PlaceholderReplacer;
import me.filoghost.chestcommands.api.StaticIcon;
import me.filoghost.commons.Preconditions;
import org.bukkit.Material;
import org.bukkit.entity.Player;
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");
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 Menu createMenu(Plugin owner, String title, int rows);
public abstract ConfigurableIcon createConfigurableIcon(Material material);
public abstract StaticIcon createStaticIcon(ItemStack itemStack);
public abstract void registerPlaceholder(Plugin plugin, String identifier, PlaceholderReplacer placeholderReplacer);
}

22
commons/pom.xml Normal file
View File

@ -0,0 +1,22 @@
<?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>
<parent>
<groupId>me.filoghost.chestcommands</groupId>
<artifactId>chestcommands-parent</artifactId>
<version>4.0.0-SNAPSHOT</version>
</parent>
<artifactId>chestcommands-commons</artifactId>
<name>ChestCommands Commons</name>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,88 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.commons;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.List;
public abstract class BaseJavaPlugin extends JavaPlugin {
@Override
public final void onEnable() {
try {
// checkPackageRelocation(); TODO enable later
onCheckedEnable();
} catch (PluginEnableException e) {
criticalShutdown(e.getMessage(), null);
} catch (Throwable t) {
criticalShutdown(null, t);
}
}
private void checkPackageRelocation() {
// Prevent Maven's Relocate from changing strings too
final String defaultPackage = new String(
new byte[]{'m', 'e', '.', 'f', 'i', 'l', 'o', 'g', 'h', 'o', 's', 't', '.', 'c', 'o', 'm', 'm', 'o', 'n', 's'});
// Make sure package has been relocated
if (BaseJavaPlugin.class.getPackage().getName().equals(defaultPackage)) {
throw new IllegalStateException("not relocated correctly");
}
}
protected abstract void onCheckedEnable() throws PluginEnableException;
private void criticalShutdown(String errorMessage, Throwable throwable) {
Bukkit.getConsoleSender().sendMessage(getErrorMessage(errorMessage, throwable));
Bukkit.getScheduler().runTaskLater(this, () -> {
Bukkit.getConsoleSender().sendMessage(
getFatalErrorPrefix() + "Fatal error while enabling the plugin. Check previous logs for more information.");
}, 10);
setEnabled(false);
}
protected String getErrorMessage(String errorMessage, Throwable throwable) {
List<String> output = new ArrayList<>();
if (throwable != null) {
output.add(getFatalErrorPrefix() + "Fatal unexpected error while enabling plugin:");
} else {
output.add(getFatalErrorPrefix() + "Fatal error while enabling plugin:");
}
if (throwable != null) {
output.add(" ");
output.add(CommonsUtil.getStackTraceString(throwable));
}
output.add(" ");
if (errorMessage != null) {
output.add(errorMessage);
}
output.add("The plugin has been disabled.");
output.add(" ");
return String.join("\n", output);
}
private String getFatalErrorPrefix() {
return ChatColor.DARK_RED + "[" + getDescription().getName() + "] " + ChatColor.RED;
}
public static class PluginEnableException extends Exception {
public PluginEnableException(String message) {
super(message);
}
}
}

View File

@ -0,0 +1,19 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.commons;
import org.bukkit.ChatColor;
public final class Colors {
public static String addColors(String input) {
if (Strings.isEmpty(input)) {
return input;
}
return ChatColor.translateAlternateColorCodes('&', input);
}
}

View File

@ -0,0 +1,28 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.commons;
import java.io.PrintWriter;
import java.io.StringWriter;
public class CommonsUtil {
public static boolean isClassLoaded(String name) {
try {
Class.forName(name);
return true;
} catch (Throwable t) {
return false;
}
}
public static String getStackTraceString(Throwable throwable) {
StringWriter stringWriter = new StringWriter();
throwable.printStackTrace(new PrintWriter(stringWriter));
return stringWriter.toString();
}
}

View File

@ -0,0 +1,113 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.commons;
import me.filoghost.commons.collection.Registry;
import org.bukkit.Material;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;
public final class MaterialsHelper {
// Registry of materials by numerical ID (before 1.13), name and aliases
private static final Registry<Material> MATERIALS_REGISTRY = initMaterialsRegistry();
// Materials that are considered air (with 1.13+ compatibility)
private static final Collection<Material> AIR_MATERIALS = getExistingMaterials("AIR", "CAVE_AIR", "VOID_AIR");
@SuppressWarnings("deprecation")
private static Registry<Material> initMaterialsRegistry() {
Registry<Material> materialsRegistry = Registry.fromEnumValues(Material.class);
// Add numerical IDs in legacy versions (the Tag class was added in 1.13)
if (!CommonsUtil.isClassLoaded("org.bukkit.Tag")) {
for (Material material : Material.values()) {
materialsRegistry.put(Integer.toString(material.getId()), material);
}
}
// Add some default useful aliases (when present)
materialsRegistry.putIfEnumExists("iron bar", "IRON_FENCE");
materialsRegistry.putIfEnumExists("iron bars", "IRON_FENCE");
materialsRegistry.putIfEnumExists("glass pane", "THIN_GLASS");
materialsRegistry.putIfEnumExists("nether wart", "NETHER_STALK");
materialsRegistry.putIfEnumExists("nether warts", "NETHER_STALK");
materialsRegistry.putIfEnumExists("slab", "STEP");
materialsRegistry.putIfEnumExists("double slab", "DOUBLE_STEP");
materialsRegistry.putIfEnumExists("stone brick", "SMOOTH_BRICK");
materialsRegistry.putIfEnumExists("stone bricks", "SMOOTH_BRICK");
materialsRegistry.putIfEnumExists("stone stair", "SMOOTH_STAIRS");
materialsRegistry.putIfEnumExists("stone stairs", "SMOOTH_STAIRS");
materialsRegistry.putIfEnumExists("potato", "POTATO_ITEM");
materialsRegistry.putIfEnumExists("carrot", "CARROT_ITEM");
materialsRegistry.putIfEnumExists("brewing stand", "BREWING_STAND_ITEM");
materialsRegistry.putIfEnumExists("cauldron", "CAULDRON_ITEM");
materialsRegistry.putIfEnumExists("carrot on stick", "CARROT_STICK");
materialsRegistry.putIfEnumExists("carrot on a stick", "CARROT_STICK");
materialsRegistry.putIfEnumExists("cobblestone wall", "COBBLE_WALL");
materialsRegistry.putIfEnumExists("acacia wood stairs", "ACACIA_STAIRS");
materialsRegistry.putIfEnumExists("dark oak wood stairs", "DARK_OAK_STAIRS");
materialsRegistry.putIfEnumExists("wood slab", "WOOD_STEP");
materialsRegistry.putIfEnumExists("double wood slab", "WOOD_DOUBLE_STEP");
materialsRegistry.putIfEnumExists("repeater", "DIODE");
materialsRegistry.putIfEnumExists("piston", "PISTON_BASE");
materialsRegistry.putIfEnumExists("sticky piston", "PISTON_STICKY_BASE");
materialsRegistry.putIfEnumExists("flower pot", "FLOWER_POT_ITEM");
materialsRegistry.putIfEnumExists("wood showel", "WOOD_SPADE");
materialsRegistry.putIfEnumExists("stone showel", "STONE_SPADE");
materialsRegistry.putIfEnumExists("gold showel", "GOLD_SPADE");
materialsRegistry.putIfEnumExists("iron showel", "IRON_SPADE");
materialsRegistry.putIfEnumExists("diamond showel", "DIAMOND_SPADE");
materialsRegistry.putIfEnumExists("steak", "COOKED_BEEF");
materialsRegistry.putIfEnumExists("cooked porkchop", "GRILLED_PORK");
materialsRegistry.putIfEnumExists("raw porkchop", "PORK");
materialsRegistry.putIfEnumExists("hardened clay", "HARD_CLAY");
materialsRegistry.putIfEnumExists("huge brown mushroom", "HUGE_MUSHROOM_1");
materialsRegistry.putIfEnumExists("huge red mushroom", "HUGE_MUSHROOM_2");
materialsRegistry.putIfEnumExists("mycelium", "MYCEL");
materialsRegistry.putIfEnumExists("poppy", "RED_ROSE");
materialsRegistry.putIfEnumExists("comparator", "REDSTONE_COMPARATOR");
materialsRegistry.putIfEnumExists("skull", "SKULL_ITEM");
materialsRegistry.putIfEnumExists("head", "SKULL_ITEM");
materialsRegistry.putIfEnumExists("redstone torch", "REDSTONE_TORCH_ON");
materialsRegistry.putIfEnumExists("redstone lamp", "REDSTONE_LAMP_OFF");
materialsRegistry.putIfEnumExists("glistering melon", "SPECKLED_MELON");
materialsRegistry.putIfEnumExists("acacia leaves", "LEAVES_2");
materialsRegistry.putIfEnumExists("acacia log", "LOG_2");
materialsRegistry.putIfEnumExists("gunpowder", "SULPHUR");
materialsRegistry.putIfEnumExists("lilypad", "WATER_LILY");
materialsRegistry.putIfEnumExists("command block", "COMMAND");
materialsRegistry.putIfEnumExists("dye", "INK_SACK");
return materialsRegistry;
}
public static Optional<Material> matchMaterial(String materialName) {
return MATERIALS_REGISTRY.find(materialName);
}
private static Collection<Material> getExistingMaterials(String... materialEnumNames) {
Collection<Material> existingMaterials = new HashSet<>();
for (String materialEnumName : materialEnumNames) {
try {
existingMaterials.add(Material.valueOf(materialEnumName));
} catch (IllegalArgumentException e) {
// Ignore, not existing
}
}
return existingMaterials;
}
public static boolean isAir(Material material) {
return AIR_MATERIALS.contains(material);
}
}

View File

@ -0,0 +1,49 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.commons;
import org.bukkit.Material;
public final class Preconditions {
public static void notNull(Object object, String objectName) {
if (object == null) {
throw new NullPointerException(objectName + " cannot be null");
}
}
public static void checkArgument(boolean expression, String errorMessage) {
if (!expression) {
throw new IllegalArgumentException(errorMessage);
}
}
public static void checkState(boolean expression, String errorMessage) {
if (!expression) {
throw new IllegalStateException(errorMessage);
}
}
public static void checkIndex(int index, int size, String objectName) {
checkArgument(size >= 0, "size cannot be negative");
if (index < 0) {
throw new IndexOutOfBoundsException(objectName + " (" + index + ") cannot be negative");
}
if (index >= size) {
throw new IndexOutOfBoundsException(objectName + " (" + index + ") must be less than size (" + size + ")");
}
}
public static void checkArgumentNotAir(Material material, String objectName) {
notNull(material, objectName);
if (MaterialsHelper.isAir(material)) {
throw new IllegalArgumentException(objectName + " cannot be " + material);
}
}
}

View File

@ -0,0 +1,89 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.commons;
public final class Strings {
public static String[] trimmedSplit(String string, String pattern) {
return trimmedSplit(string, pattern, 0);
}
public static String[] trimmedSplit(String string, String pattern, int limit) {
String[] output = string.split(pattern, limit);
for (int i = 0; i < output.length; i++) {
output[i] = output[i].trim();
}
return output;
}
public static String stripChars(String string, char... charsToRemove) {
if (isEmpty(string) || charsToRemove.length == 0) {
return string;
}
StringBuilder result = new StringBuilder(string.length());
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (!arrayContains(charsToRemove, c)) {
result.append(c);
}
}
return result.toString();
}
private static boolean arrayContains(char[] array, char valueToFind) {
for (char c : array) {
if (c == valueToFind) {
return true;
}
}
return false;
}
public static String capitalizeFully(String string) {
if (isEmpty(string)) {
return string;
}
string = string.toLowerCase();
int length = string.length();
StringBuilder result = new StringBuilder(length);
boolean capitalizeNext = true;
for (int i = 0; i < length; i++) {
char c = string.charAt(i);
if (Character.isWhitespace(c)) {
result.append(c);
capitalizeNext = true;
} else if (capitalizeNext) {
result.append(Character.toTitleCase(c));
capitalizeNext = false;
} else {
result.append(c);
}
}
return result.toString();
}
public static String capitalizeFirst(String string) {
if (isEmpty(string)) {
return string;
}
return Character.toTitleCase(string.charAt(0)) + string.substring(1);
}
public static boolean isEmpty(String string) {
return string == null || string.isEmpty();
}
}

View File

@ -0,0 +1,90 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.commons.collection;
import me.filoghost.commons.Preconditions;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class CaseInsensitiveMap<V> implements Map<String, V> {
private final Map<String, V> delegate;
public CaseInsensitiveMap() {
this.delegate = new HashMap<>();
}
@Override
public V put(String key, V value) {
return delegate.put(getLowercaseKey(key), value);
}
@Override
public V get(Object key) {
return delegate.get(getLowercaseKey(key));
}
@Override
public boolean containsKey(Object key) {
return delegate.containsKey(getLowercaseKey(key));
}
@Override
public V remove(Object key) {
return delegate.remove(getLowercaseKey(key));
}
@Override
public int size() {
return delegate.size();
}
@Override
public boolean isEmpty() {
return delegate.isEmpty();
}
@Override
public boolean containsValue(Object value) {
return delegate.containsValue(value);
}
@Override
public void putAll(Map<? extends String, ? extends V> map) {
map.forEach(this::put);
}
@Override
public void clear() {
delegate.clear();
}
@Override
public Set<String> keySet() {
return Collections.unmodifiableSet(delegate.keySet());
}
@Override
public Collection<V> values() {
return Collections.unmodifiableCollection(delegate.values());
}
@Override
public Set<Entry<String, V>> entrySet() {
return Collections.unmodifiableSet(delegate.entrySet());
}
private String getLowercaseKey(Object key) {
Preconditions.notNull(key, "key");
Preconditions.checkArgument(key instanceof String, "key must be a string");
return ((String) key).toLowerCase();
}
}

View File

@ -0,0 +1,68 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.commons.collection;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
public final class CollectionUtils {
public static <E> List<E> copy(List<E> list) {
if (list != null) {
return new ArrayList<>(list);
} else {
return null;
}
}
public static <K, V> Map<K, V> copy(Map<K, V> map) {
if (map != null) {
return new HashMap<>(map);
} else {
return null;
}
}
public static <E> ImmutableList<E> immutableCopy(List<E> list) {
if (list != null) {
return ImmutableList.copyOf(list);
} else {
return null;
}
}
public static <A, B> List<B> transform(List<A> list, Function<A, B> transformFunction) {
if (list == null) {
return null;
}
List<B> result = new ArrayList<>(list.size());
for (A element : list) {
result.add(transformFunction.apply(element));
}
return result;
}
public static <A, B> ImmutableList<B> transformImmutable(List<A> list, Function<A, B> transformFunction) {
if (list == null) {
return null;
}
ImmutableList.Builder<B> builder = ImmutableList.builder();
for (A element : list) {
builder.add(transformFunction.apply(element));
}
return builder.build();
}
public static <E> List<E> replaceNulls(List<E> list, E replacement) {
return transform(list, element -> element != null ? element : replacement);
}
}

View File

@ -0,0 +1,83 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.commons.collection;
import me.filoghost.commons.Preconditions;
import me.filoghost.commons.Strings;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
public class Registry<T> {
// Characters to ignore when searching enums by name
private static final char[] KEY_IGNORE_CHARS = {'-', '_', ' '};
private final Class<T> valuesType;
private final Map<String, T> valuesMap;
public static <T extends Enum<T>> Registry<T> fromEnumValues(Class<T> enumClass) {
Registry<T> registry = new Registry<>(enumClass);
registry.putAll(enumClass.getEnumConstants(), Enum::name);
return registry;
}
public static <T> Registry<T> fromValues(T[] values, Function<T, String> toKeyFunction) {
Registry<T> registry = new Registry<>(null);
registry.putAll(values, toKeyFunction);
return registry;
}
private Registry(Class<T> valuesType) {
this.valuesType = valuesType;
this.valuesMap = new HashMap<>();
}
public Optional<T> find(String key) {
if (key == null) {
return Optional.empty();
}
return Optional.ofNullable(valuesMap.get(toKeyFormat(key)));
}
public void putIfEnumExists(String key, String enumValueName) {
Preconditions.checkState(valuesType.isEnum(), "value type is not an enum");
try {
@SuppressWarnings({ "unchecked", "rawtypes" })
T enumValue = (T) Enum.valueOf((Class<Enum>) valuesType, enumValueName);
put(key, enumValue);
} catch (IllegalArgumentException e) {
// Ignore, enum value doesn't exist
}
}
private void putAll(T[] enumValues, Function<T, String> toKeyFunction) {
for (T enumValue : enumValues) {
valuesMap.put(toKeyFormat(toKeyFunction.apply(enumValue)), enumValue);
}
}
public void put(String key, T enumValue) {
valuesMap.put(toKeyFormat(key), enumValue);
}
private String toKeyFormat(String enumValueName) {
return Strings.stripChars(enumValueName, KEY_IGNORE_CHARS).toLowerCase();
}
@Override
public String toString() {
return "Registry [type=" + valuesType + ", values=" + valuesMap + "]";
}
}

View File

@ -0,0 +1,16 @@
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.commons.command;
public class CommandException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CommandException(String msg) {
super(msg);
}
}

View File

@ -1,73 +1,64 @@
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.gmail.filoghost.chestcommands.command.framework;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.plugin.java.JavaPlugin;
/**
* Wrapper for the default command executor.
*/
public abstract class CommandFramework implements CommandExecutor {
private String label;
public CommandFramework(String label) {
this.label = label;
}
public abstract void execute(CommandSender sender, String label, String[] args);
/**
* Default implementation of Bukkit's command executor.
*/
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
try {
execute(sender, label, args);
} catch (CommandException ex) {
if (ex.getMessage() != null && !ex.getMessage().isEmpty()) {
// Use RED by default
sender.sendMessage(ChatColor.RED + ex.getMessage());
}
}
return true;
}
/**
* Register a command through the framework.
*/
public static boolean register(JavaPlugin plugin, CommandFramework command) {
PluginCommand pluginCommand = plugin.getCommand(command.label);
if (pluginCommand == null) {
return false;
}
pluginCommand.setExecutor(command);
return true;
}
}
/*
* Copyright (C) filoghost and contributors
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package me.filoghost.commons.command;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.plugin.java.JavaPlugin;
/**
* Wrapper for the default command executor.
*/
public abstract class CommandFramework implements CommandExecutor {
private final String label;
public CommandFramework(String label) {
this.label = label;
}
public abstract void execute(CommandSender sender, String label, String[] args);
/**
* Default implementation of Bukkit's command executor.
*/
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
try {
execute(sender, label, args);
} catch (CommandException ex) {
if (ex.getMessage() != null && !ex.getMessage().isEmpty()) {
// Use RED by default
sender.sendMessage(ChatColor.RED + ex.getMessage());
}
}
return true;
}
/**
* Register a command through the framework.
*/
public static boolean register(JavaPlugin plugin, CommandFramework command) {
PluginCommand pluginCommand = plugin.getCommand(command.label);
if (pluginCommand == null) {
return false;
}
pluginCommand.setExecutor(command);
return true;
}
}

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