Utils cleanup

This commit is contained in:
Gabriele C 2019-04-24 12:54:16 +02:00
parent 8e5bef5fd9
commit e8878d21e0
26 changed files with 307 additions and 336 deletions

View File

@ -19,9 +19,9 @@ import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import com.gmail.filoghost.chestcommands.bridge.PlaceholderAPIBridge;
import com.gmail.filoghost.chestcommands.util.BukkitUtils;
import org.bstats.bukkit.MetricsLite;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
@ -46,7 +46,6 @@ 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.util.AttributeRemover;
import com.gmail.filoghost.chestcommands.serializer.CommandSerializer;
import com.gmail.filoghost.chestcommands.serializer.MenuSerializer;
import com.gmail.filoghost.chestcommands.task.ErrorLoggerTask;
@ -54,7 +53,6 @@ import com.gmail.filoghost.chestcommands.task.RefreshMenusTask;
import com.gmail.filoghost.chestcommands.util.CaseInsensitiveMap;
import com.gmail.filoghost.chestcommands.util.ErrorLogger;
import com.gmail.filoghost.chestcommands.util.Utils;
import com.gmail.filoghost.chestcommands.util.VersionUtils;
public class ChestCommands extends JavaPlugin {
@ -198,7 +196,7 @@ public class ChestCommands extends JavaPlugin {
if (!menusFolder.isDirectory()) {
// Create the directory with the default menu
menusFolder.mkdirs();
Utils.saveResourceSafe(this, "menu" + File.separator + "example.yml");
BukkitUtils.saveResourceSafe(this, "menu" + File.separator + "example.yml");
}
List<PluginConfig> menusList = loadMenus(menusFolder);
@ -254,9 +252,9 @@ public class ChestCommands extends JavaPlugin {
Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
}
}
/**
* Loads all the configuration files recursively into a list.
*/
@ -273,11 +271,11 @@ public class ChestCommands extends JavaPlugin {
}
return list;
}
public static void closeAllMenus() {
for (Player player : VersionUtils.getOnlinePlayers()) {
for (Player player : Bukkit.getOnlinePlayers()) {
if (player.getOpenInventory() != null) {
if (player.getOpenInventory().getTopInventory().getHolder() instanceof MenuInventoryHolder || player.getOpenInventory().getBottomInventory().getHolder() instanceof MenuInventoryHolder) {
player.closeInventory();
@ -285,9 +283,9 @@ public class ChestCommands extends JavaPlugin {
}
}
}
public static ChestCommands getInstance() {
return instance;
}

View File

@ -21,7 +21,7 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder;
import com.gmail.filoghost.chestcommands.util.AttributeRemover;
import com.gmail.filoghost.chestcommands.util.ItemUtils;
import com.gmail.filoghost.chestcommands.util.Utils;
import com.gmail.filoghost.chestcommands.util.Validate;
@ -93,7 +93,7 @@ public class IconMenu {
for (int i = 0; i < icons.length; i++) {
if (icons[i] != null) {
inventory.setItem(i, AttributeRemover.hideAttributes(icons[i].createItemstack(player)));
inventory.setItem(i, ItemUtils.hideAttributes(icons[i].createItemstack(player)));
}
}

View File

@ -14,6 +14,7 @@
*/
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;
@ -21,8 +22,6 @@ import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider;
import com.gmail.filoghost.chestcommands.util.Utils;
public class EconomyBridge {
private static Economy economy;
@ -76,7 +75,7 @@ public class EconomyBridge {
EconomyResponse response = economy.withdrawPlayer(player.getName(), player.getWorld().getName(), amount);
boolean result = response.transactionSuccess();
Utils.refreshMenu(player);
MenuUtils.refreshMenu(player);
return result;
}
@ -88,7 +87,7 @@ public class EconomyBridge {
EconomyResponse response = economy.depositPlayer(player.getName(), player.getWorld().getName(), amount);
boolean result = response.transactionSuccess();
Utils.refreshMenu(player);
MenuUtils.refreshMenu(player);
return result;
}

View File

@ -20,6 +20,8 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.gmail.filoghost.chestcommands.util.BukkitUtils;
import com.gmail.filoghost.chestcommands.util.FormatUtils;
import org.apache.commons.lang.StringEscapeUtils;
import com.gmail.filoghost.chestcommands.ChestCommands;
@ -40,7 +42,7 @@ public class AsciiPlaceholders {
File file = new File(ChestCommands.getInstance().getDataFolder(), "placeholders.yml");
if (!file.exists()) {
Utils.saveResourceSafe(ChestCommands.getInstance(), "placeholders.yml");
BukkitUtils.saveResourceSafe(ChestCommands.getInstance(), "placeholders.yml");
}
List<String> lines = Utils.readLines(file);
@ -58,7 +60,7 @@ public class AsciiPlaceholders {
int indexOf = line.indexOf(':');
String placeholder = unquote(line.substring(0, indexOf).trim());
String replacement = Utils.addColors(StringEscapeUtils.unescapeJava(unquote(line.substring(indexOf + 1, line.length()).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.");

View File

@ -21,10 +21,9 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.gmail.filoghost.chestcommands.util.FormatUtils;
import org.bukkit.configuration.InvalidConfigurationException;
import com.gmail.filoghost.chestcommands.util.Utils;
/**
* A special configuration wrapper that reads the values using reflection.
* It will also save default values if not set.
@ -110,7 +109,7 @@ public class SpecialConfig {
field.set(this, config.getDouble(configKey));
} else if (type == String.class) {
field.set(this, Utils.addColors(config.getString(configKey))); // Always add colors
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.");

View File

@ -14,7 +14,7 @@
*/
package com.gmail.filoghost.chestcommands.internal;
import com.gmail.filoghost.chestcommands.util.VersionUtils;
import org.bukkit.Bukkit;
public class CachedGetters {
@ -27,7 +27,7 @@ public class CachedGetters {
if (lastOnlinePlayersRefresh == 0 || now - lastOnlinePlayersRefresh > 1000) {
// getOnlinePlayers() could be expensive if called frequently
lastOnlinePlayersRefresh = now;
onlinePlayers = VersionUtils.getOnlinePlayers().size();
onlinePlayers = Bukkit.getOnlinePlayers().size();
}
return onlinePlayers;

View File

@ -29,7 +29,7 @@ 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.AttributeRemover;
import com.gmail.filoghost.chestcommands.util.ItemUtils;
public class ExtendedIconMenu extends IconMenu {
@ -87,7 +87,7 @@ public class ExtendedIconMenu extends IconMenu {
continue;
}
inventory.setItem(i, AttributeRemover.hideAttributes(icons[i].createItemstack(player)));
inventory.setItem(i, ItemUtils.hideAttributes(icons[i].createItemstack(player)));
}
}
@ -109,11 +109,11 @@ public class ExtendedIconMenu extends IconMenu {
if (extIcon.canViewIcon(player)) {
if (inventory.getItem(i) == null) {
ItemStack newItem = AttributeRemover.hideAttributes(extIcon.createItemstack(player));
ItemStack newItem = ItemUtils.hideAttributes(extIcon.createItemstack(player));
inventory.setItem(i, newItem);
} else {
// Performance, only update name and lore
ItemStack oldItem = AttributeRemover.hideAttributes(inventory.getItem(i));
ItemStack oldItem = ItemUtils.hideAttributes(inventory.getItem(i));
ItemMeta meta = oldItem.getItemMeta();
meta.setDisplayName(extIcon.calculateName(player));
meta.setLore(extIcon.calculateLore(player));

View File

@ -14,16 +14,16 @@
*/
package com.gmail.filoghost.chestcommands.internal.icon.command;
import com.gmail.filoghost.chestcommands.util.FormatUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import com.gmail.filoghost.chestcommands.util.Utils;
public class BroadcastIconCommand extends IconCommand {
public BroadcastIconCommand(String command) {
super(Utils.addColors(command));
super(FormatUtils.addColors(command));
}
@Override

View File

@ -14,6 +14,7 @@
*/
package com.gmail.filoghost.chestcommands.internal.icon.command;
import com.gmail.filoghost.chestcommands.util.FormatUtils;
import org.bukkit.entity.Player;
import com.gmail.filoghost.chestcommands.bridge.BarAPIBridge;
@ -42,7 +43,7 @@ public class DragonBarIconCommand extends IconCommand {
message = split[1].trim();
}
message = Utils.addColors(message);
message = FormatUtils.addColors(message);
}
@Override

View File

@ -14,12 +14,12 @@
*/
package com.gmail.filoghost.chestcommands.internal.icon.command;
import com.gmail.filoghost.chestcommands.util.BukkitUtils;
import org.bukkit.ChatColor;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import com.gmail.filoghost.chestcommands.util.Utils;
public class SoundIconCommand extends IconCommand {
@ -42,7 +42,7 @@ public class SoundIconCommand extends IconCommand {
String[] split = command.split(",");
sound = Utils.matchSound(split[0]);
sound = BukkitUtils.matchSound(split[0]);
if (sound == null) {
errorMessage = ChatColor.RED + "Invalid sound \"" + split[0].trim() + "\".";
return;

View File

@ -14,15 +14,15 @@
*/
package com.gmail.filoghost.chestcommands.internal.icon.command;
import com.gmail.filoghost.chestcommands.util.FormatUtils;
import org.bukkit.entity.Player;
import com.gmail.filoghost.chestcommands.internal.icon.IconCommand;
import com.gmail.filoghost.chestcommands.util.Utils;
public class TellIconCommand extends IconCommand {
public TellIconCommand(String command) {
super(Utils.addColors(command));
super(FormatUtils.addColors(command));
}
@Override

View File

@ -14,6 +14,7 @@
*/
package com.gmail.filoghost.chestcommands.listener;
import com.gmail.filoghost.chestcommands.util.BukkitUtils;
import org.bukkit.ChatColor;
import org.bukkit.block.Sign;
import org.bukkit.event.EventHandler;
@ -28,7 +29,6 @@ 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.MaterialsRegistry;
import com.gmail.filoghost.chestcommands.util.Utils;
public class SignListener implements Listener {
@ -41,7 +41,7 @@ public class SignListener implements Listener {
if (sign.getLine(0).equalsIgnoreCase(ChatColor.DARK_BLUE + "[menu]")) {
sign.getLine(1);
ExtendedIconMenu iconMenu = ChestCommands.getFileNameToMenuMap().get(Utils.addYamlExtension(sign.getLine(1)));
ExtendedIconMenu iconMenu = ChestCommands.getFileNameToMenuMap().get(BukkitUtils.addYamlExtension(sign.getLine(1)));
if (iconMenu != null) {
if (event.getPlayer().hasPermission(iconMenu.getPermission())) {
@ -68,7 +68,7 @@ public class SignListener implements Listener {
return;
}
IconMenu iconMenu = ChestCommands.getFileNameToMenuMap().get(Utils.addYamlExtension(event.getLine(1)));
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.");
@ -76,7 +76,7 @@ public class SignListener implements Listener {
}
event.setLine(0, ChatColor.DARK_BLUE + event.getLine(0));
event.getPlayer().sendMessage(ChatColor.GREEN + "Successfully created a sign for the menu " + Utils.addYamlExtension(event.getLine(1)) + ".");
event.getPlayer().sendMessage(ChatColor.GREEN + "Successfully created a sign for the menu " + BukkitUtils.addYamlExtension(event.getLine(1)) + ".");
}
}

View File

@ -16,6 +16,7 @@ package com.gmail.filoghost.chestcommands.serializer;
import java.util.List;
import com.gmail.filoghost.chestcommands.util.*;
import org.bukkit.configuration.ConfigurationSection;
import com.gmail.filoghost.chestcommands.api.Icon;
@ -25,10 +26,6 @@ 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.util.ErrorLogger;
import com.gmail.filoghost.chestcommands.util.ItemStackReader;
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;
@ -126,8 +123,8 @@ public class IconSerializer {
}
}
icon.setName(AsciiPlaceholders.placeholdersToSymbols(Utils.colorizeName(section.getString(Nodes.NAME))));
icon.setLore(AsciiPlaceholders.placeholdersToSymbols(Utils.colorizeLore(section.getStringList(Nodes.LORE))));
icon.setName(AsciiPlaceholders.placeholdersToSymbols(FormatUtils.colorizeName(section.getString(Nodes.NAME))));
icon.setLore(AsciiPlaceholders.placeholdersToSymbols(FormatUtils.colorizeLore(section.getStringList(Nodes.LORE))));
if (section.isSet(Nodes.ENCHANT)) {
icon.setEnchantments(EnchantmentSerializer.loadEnchantments(section.getString(Nodes.ENCHANT), iconName, menuFileName, errorLogger));
@ -135,7 +132,7 @@ public class IconSerializer {
if (section.isSet(Nodes.COLOR)) {
try {
icon.setColor(Utils.parseColor(section.getString(Nodes.COLOR)));
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());
}
@ -145,7 +142,7 @@ public class IconSerializer {
if (section.isSet(Nodes.BANNER_COLOR)) {
try {
icon.setBannerColor(Utils.parseDyeColor(section.getString(Nodes.BANNER_COLOR)));
icon.setBannerColor(ItemUtils.parseDyeColor(section.getString(Nodes.BANNER_COLOR)));
} catch (FormatException e) {
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has an invalid BASE-COLOUR: " + e.getMessage());
}
@ -153,14 +150,14 @@ public class IconSerializer {
if (section.isSet(Nodes.BANNER_PATTERNS)) {
try {
icon.setBannerPatterns(Utils.parseBannerPatternList(section.getStringList(Nodes.BANNER_PATTERNS)));
icon.setBannerPatterns(ItemUtils.parseBannerPatternList(section.getStringList(Nodes.BANNER_PATTERNS)));
} catch (FormatException e) {
errorLogger.addError("The icon \"" + iconName + "\" in the menu \"" + menuFileName + "\" has an invalid PATTERN-LIST: " + e.getMessage());
}
}
icon.setPermission(section.getString(Nodes.PERMISSION));
icon.setPermissionMessage(Utils.addColors(section.getString(Nodes.PERMISSION_MESSAGE)));
icon.setPermissionMessage(FormatUtils.addColors(section.getString(Nodes.PERMISSION_MESSAGE)));
icon.setViewPermission(section.getString(Nodes.VIEW_PERMISSION));
boolean closeOnClick = !section.getBoolean(Nodes.KEEP_OPEN);

View File

@ -14,6 +14,7 @@
*/
package com.gmail.filoghost.chestcommands.serializer;
import com.gmail.filoghost.chestcommands.util.*;
import org.bukkit.ChatColor;
import org.bukkit.configuration.ConfigurationSection;
@ -23,10 +24,6 @@ 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.serializer.IconSerializer.Coords;
import com.gmail.filoghost.chestcommands.util.ClickType;
import com.gmail.filoghost.chestcommands.util.ErrorLogger;
import com.gmail.filoghost.chestcommands.util.ItemStackReader;
import com.gmail.filoghost.chestcommands.util.Utils;
public class MenuSerializer {
@ -79,7 +76,7 @@ public class MenuSerializer {
*/
public static MenuData loadMenuData(PluginConfig config, ErrorLogger errorLogger) {
String title = Utils.addColors(config.getString(Nodes.MENU_NAME));
String title = FormatUtils.addColors(config.getString(Nodes.MENU_NAME));
int rows;
if (title == null) {

View File

@ -16,6 +16,7 @@ package com.gmail.filoghost.chestcommands.task;
import java.util.List;
import com.gmail.filoghost.chestcommands.util.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
@ -44,7 +45,7 @@ public class ErrorLoggerTask implements Runnable {
}
lines.add(ChatColor.RED + "#-------------------------------------------------------------#");
String output = Utils.join(lines, "\n");
String output = StringUtils.join(lines, "\n");
if (ChestCommands.getSettings().use_console_colors) {
Bukkit.getConsoleSender().sendMessage(output);

View File

@ -14,13 +14,13 @@
*/
package com.gmail.filoghost.chestcommands.task;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder;
import com.gmail.filoghost.chestcommands.util.VersionUtils;
public class RefreshMenusTask implements Runnable {
@ -29,7 +29,7 @@ public class RefreshMenusTask implements Runnable {
@Override
public void run() {
for (Player player : VersionUtils.getOnlinePlayers()) {
for (Player player : Bukkit.getOnlinePlayers()) {
InventoryView view = player.getOpenInventory();
if (view == null) {

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.util;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
public class AttributeRemover {
public static ItemStack hideAttributes(ItemStack item) {
if (item == null) {
return null;
}
ItemMeta meta = item.getItemMeta();
if (Utils.isNullOrEmpty(meta.getItemFlags())) {
// Add them only if necessary
meta.addItemFlags(ItemFlag.values());
item.setItemMeta(meta);
}
return item;
}
}

View File

@ -0,0 +1,35 @@
package com.gmail.filoghost.chestcommands.util;
import org.bukkit.Sound;
import org.bukkit.plugin.Plugin;
public final class BukkitUtils {
private BukkitUtils() {
}
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 ex) {
// Ignore
}
}
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

@ -0,0 +1,57 @@
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

@ -0,0 +1,97 @@
/*
* 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.util.ArrayList;
import java.util.List;
public final class ItemUtils {
private ItemUtils() {
}
public static ItemStack hideAttributes(ItemStack item) {
if (item == null) {
return null;
}
ItemMeta meta = item.getItemMeta();
if (Utils.isNullOrEmpty(meta.getItemFlags())) {
// Add them only if necessary
meta.addItemFlags(ItemFlag.values());
item.setItemMeta(meta);
}
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 colour.");
}
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:colour\".");
}
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

@ -22,7 +22,7 @@ import java.util.Map;
import org.bukkit.Material;
@SuppressWarnings("deprecation")
public class MaterialsRegistry {
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");
@ -38,7 +38,9 @@ public class MaterialsRegistry {
// Materials that have a "Sign" block state (with 1.13+ compatibility)
private static final Collection<Material> SIGN_MATERIALS = getExistingMaterials("SIGN", "SIGN_POST", "WALL_SIGN");
private MaterialsRegistry() {
}
private static void addMaterialAlias(String name, Material material) {
MATERIALS_BY_ALIAS.put(StringUtils.stripChars(name, IGNORE_CHARS).toLowerCase(), material);

View File

@ -0,0 +1,27 @@
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

@ -14,7 +14,12 @@
*/
package com.gmail.filoghost.chestcommands.util;
public class StringUtils {
import java.util.Iterator;
public final class StringUtils {
private StringUtils() {
}
public static String stripChars(String input, String removed) {
if (removed == null || removed.isEmpty()) {
@ -98,5 +103,24 @@ public class StringUtils {
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

@ -19,112 +19,13 @@ import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;
import org.bukkit.*;
import org.bukkit.block.banner.Pattern;
import org.bukkit.block.banner.PatternType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
import org.bukkit.plugin.Plugin;
public final class Utils {
import com.gmail.filoghost.chestcommands.ChestCommands;
import com.gmail.filoghost.chestcommands.exception.FormatException;
import com.gmail.filoghost.chestcommands.internal.ExtendedIconMenu;
import com.gmail.filoghost.chestcommands.internal.MenuInventoryHolder;
public class Utils {
private static String nmsVersion;
private static DecimalFormat decimalFormat = new DecimalFormat("0.##");
public static String getNMSVersion() {
if (nmsVersion == null) {
String packageName = Bukkit.getServer().getClass().getPackage().getName();
nmsVersion = packageName.substring(packageName.lastIndexOf('.') + 1);
}
return nmsVersion;
private Utils() {
}
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;
}
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);
}
}
}
}
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 addYamlExtension(String input) {
if (input == null) return null;
return input.toLowerCase().endsWith(".yml") ? input : input + ".yml";
}
public static String decimalFormat(double number) {
return decimalFormat.format(number);
}
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;
}
public static int makePositive(int i) {
return i < 0 ? 0 : i;
}
@ -191,65 +92,7 @@ public class Utils {
}
}
}
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 colour.");
}
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:colour\".");
}
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;
}
public static void saveResourceSafe(Plugin plugin, String name) {
try {
plugin.saveResource(name, false);
} catch (Exception ex) {
// Ignore
}
}
public static <T> Set<T> newHashSet() {
return new HashSet<T>();
}
@ -261,26 +104,7 @@ public class Utils {
public static <T> List<T> newArrayList() {
return new ArrayList<T>();
}
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();
}
public static boolean isClassLoaded(String name) {
try {
Class.forName(name);

View File

@ -14,7 +14,10 @@
*/
package com.gmail.filoghost.chestcommands.util;
public class Validate {
public final class Validate {
private Validate() {
}
public static void notNull(Object object, String error) {
if (object == null) {

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.util;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import com.google.common.collect.ImmutableList;
public class VersionUtils {
private static boolean setup;
private static Method oldGetOnlinePlayersMethod;
private static boolean useReflection;
public static Collection<? extends Player> getOnlinePlayers() {
try {
if (!setup) {
oldGetOnlinePlayersMethod = Bukkit.class.getDeclaredMethod("getOnlinePlayers");
if (oldGetOnlinePlayersMethod.getReturnType() == Player[].class) {
useReflection = true;
}
setup = true;
}
if (!useReflection) {
return Bukkit.getOnlinePlayers();
} else {
Player[] playersArray = (Player[]) oldGetOnlinePlayersMethod.invoke(null);
return ImmutableList.copyOf(playersArray);
}
} catch (Exception e) {
e.printStackTrace();
return Collections.emptyList();
}
}
}