1.18.2 Version Fix

Cleaned up some Code
Fixed 1.13 Issue
Essentials Economy Bug Fix
This commit is contained in:
LikeWhat 2022-04-23 01:13:48 +02:00
parent f0dc4ab106
commit 6dc3d8a829
49 changed files with 1026 additions and 927 deletions

View File

@ -10,8 +10,8 @@ import de.likewhat.customheads.command.CustomHeadsCommand;
import de.likewhat.customheads.command.CustomHeadsTabCompleter;
import de.likewhat.customheads.economy.EconomyHandler;
import de.likewhat.customheads.economy.EconomyManager;
import de.likewhat.customheads.economy.errors.InvalidEconomyHandlerException;
import de.likewhat.customheads.headwriter.HeadFontType;
import de.likewhat.customheads.listener.CategoryEditorListener;
import de.likewhat.customheads.listener.InventoryListener;
import de.likewhat.customheads.listener.OtherListeners;
import de.likewhat.customheads.loader.Language;
@ -37,7 +37,9 @@ import org.bukkit.scheduler.BukkitRunnable;
import java.io.File;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import static de.likewhat.customheads.utils.Utils.hasPermission;
@ -50,12 +52,12 @@ import static de.likewhat.customheads.utils.Utils.hasPermission;
@Getter
public class CustomHeads extends JavaPlugin {
private static final boolean DEV_BUILD = false;
private static final boolean DEV_BUILD = true;
public static final HashMap<String, String> uuidCache = new HashMap<>();
public static final String chPrefix = "§7[§eCustomHeads§7] ";
public static final String chError = chPrefix + "§cError §7: §c";
public static final String chWarning = chPrefix + "§eWarning §7: §e";
public static final HashMap<String, String> UUID_CACHE = new HashMap<>();
public static final String PREFIX_GENERAL = "§7[§eCustomHeads§7] ";
public static final String PREFIX_ERROR = PREFIX_GENERAL + "§cError §7: §c";
public static final String PREFIX_WARNING = PREFIX_GENERAL + "§eWarning §7: §e";
public static int hisOverflow = 18;
@Getter private static Configs updateFile;
@Getter private static Configs headsConfig;
@ -68,12 +70,8 @@ public class CustomHeads extends JavaPlugin {
@Getter private static SpigetResourceFetcher spigetFetcher;
@Getter private static EconomyManager economyManager;
@Getter private static CategoryManager categoryManager;
private static List<String> versions = Arrays.asList("v1_8_R1", "v1_8_R2", "v1_8_R3", "v1_9_R1", "v1_9_R2", "v1_10_R1", "v1_11_R1", "v1_12_R1", "v1_13_R1", "v1_13_R2", "v1_14_R1", "v1_15_R1", "v1_16_R1", "v1_17_R1","v1_18_R1");
private static String packet = Bukkit.getServer().getClass().getPackage().getName();
public static String version = packet.substring(packet.lastIndexOf('.') + 1);
@Getter private static int getCommandPrice = 0;
public static final boolean USE_TEXTURES = versions.contains(version);
private static boolean keepCategoryPermissions = false;
private static boolean categoriesBuyable = false;
private static boolean headsPermanentBuy = false;
@ -85,6 +83,11 @@ public class CustomHeads extends JavaPlugin {
private boolean isInit = false;
private String bukkitVersion;
@Getter private static Logger pluginLogger;
// List of Callables that gets processed after the Server finishes loading
private final List<Callable<Void>> delayedTasks = new ArrayList<>();
// Search/Get History Loader
public static void reloadHistoryData() {
historyEnabled = headsConfig.get().getBoolean("history.enabled");
@ -104,15 +107,32 @@ public class CustomHeads extends JavaPlugin {
public static void reloadEconomy() {
hasEconomy = false;
economyManager = null;
boolean skipMessages = false;
if (headsConfig.get().getBoolean("economy.enable")) {
Bukkit.getLogger().info("Loading Economy Handler...");
economyManager = new EconomyManager();
EconomyHandler handler = economyManager.getActiveEconomyHandler();
hasEconomy = handler != null && handler.isValid();
if (hasEconomy) {
Bukkit.getLogger().info("Successfully loaded Economy Handler: " + handler.getName());
} else {
Bukkit.getLogger().warning("Failed to load Economy Handler");
CustomHeads.getPluginLogger().info("Loading Economy Handler...");
try {
economyManager = new EconomyManager();
} catch(InvalidEconomyHandlerException e) {
if(CustomHeads.getInstance().isInit()) {
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to load Economy Handler.", e);
} else {
CustomHeads.getInstance().delayedTasks.add(() -> {
reloadEconomy();
return null;
});
CustomHeads.getPluginLogger().warning("Failed to load Economy Handler. Trying again after Server finishes loading.");
skipMessages = true;
}
}
// Skip Messages when the Handler gets reloaded after Server init to avoid confusion
if(!skipMessages) {
EconomyHandler handler = economyManager.getActiveEconomyHandler();
hasEconomy = handler != null && handler.isValid();
if (hasEconomy) {
CustomHeads.getPluginLogger().info("Successfully loaded Economy Handler: " + handler.getName());
} else {
CustomHeads.getPluginLogger().info("Failed to load Economy. If present see Error above");
}
}
}
}
@ -150,8 +170,13 @@ public class CustomHeads extends JavaPlugin {
}
public static boolean reload(CommandSender sender) {
boolean console = sender instanceof ConsoleCommandSender;
sender.sendMessage((console ? chPrefix : "") + languageManager.RELOAD_CONFIG);
boolean useSender = sender != null;
boolean console = false;
if(useSender) {
console = sender instanceof ConsoleCommandSender;
sender.sendMessage((console ? PREFIX_GENERAL : "") + languageManager.RELOAD_CONFIG);
}
headsConfig.reload();
reducedDebug = headsConfig.get().getBoolean("reducedDebug");
categoriesBuyable = headsConfig.get().getBoolean("economy.category.buyable");
@ -159,34 +184,20 @@ public class CustomHeads extends JavaPlugin {
headsPermanentBuy = headsConfig.get().getBoolean("economy.heads.permanentBuy");
keepCategoryPermissions = headsConfig.get().getBoolean("economy.category.keepPermissions");
reloadEconomy();
sender.sendMessage((console ? chPrefix : "") + languageManager.RELOAD_HISTORY);
if(useSender)
sender.sendMessage((console ? PREFIX_GENERAL : "") + languageManager.RELOAD_HISTORY);
reloadHistoryData();
sender.sendMessage((console ? chPrefix : "") + languageManager.RELOAD_LANGUAGE);
PlayerWrapper.clearCache();
if (!reloadTranslations(headsConfig.get().getString("langFile"))) {
sender.sendMessage((console ? chPrefix : "") + languageManager.RELOAD_FAILED);
return false;
}
ScrollableInventory.sortName = new ArrayList<>(Arrays.asList("invalid", languageManager.CYCLE_ARRANGEMENT_DEFAULT, languageManager.CYCLE_ARRANGEMENT_ALPHABETICAL, languageManager.CYCLE_ARRANGEMENT_COLOR));
sender.sendMessage((console ? chPrefix : "") + languageManager.RELOAD_SUCCESSFUL);
return true;
}
public static boolean silentReload() {
headsConfig.reload();
reducedDebug = headsConfig.get().getBoolean("reducedDebug");
categoriesBuyable = headsConfig.get().getBoolean("economy.category.buyable");
headsBuyable = headsConfig.get().getBoolean("economy.heads.buyable");
headsPermanentBuy = headsConfig.get().getBoolean("economy.heads.permanentBuy");
keepCategoryPermissions = headsConfig.get().getBoolean("economy.category.keepPermissions");
reloadHistoryData();
reloadEconomy();
if(useSender)
sender.sendMessage((console ? PREFIX_GENERAL : "") + languageManager.RELOAD_LANGUAGE);
PlayerWrapper.clearCache();
if (!reloadTranslations(headsConfig.get().getString("langFile"))) {
if(useSender)
sender.sendMessage((console ? PREFIX_GENERAL : "") + languageManager.RELOAD_FAILED);
return false;
}
ScrollableInventory.sortName = new ArrayList<>(Arrays.asList("invalid", languageManager.CYCLE_ARRANGEMENT_DEFAULT, languageManager.CYCLE_ARRANGEMENT_ALPHABETICAL, languageManager.CYCLE_ARRANGEMENT_COLOR));
if(useSender)
sender.sendMessage((console ? PREFIX_GENERAL : "") + languageManager.RELOAD_SUCCESSFUL);
return true;
}
@ -215,9 +226,9 @@ public class CustomHeads extends JavaPlugin {
playerDataFile.saveJson();
headsConfig.get().set("heads", null);
headsConfig.save();
getServer().getConsoleSender().sendMessage(chPrefix + "Successfully converted old Head Data");
getServer().getConsoleSender().sendMessage(PREFIX_GENERAL + "Successfully converted old Head Data");
} catch (Exception e) {
getLogger().log(Level.WARNING, "Failed to convert old Head Data...", e);
getPluginLogger().log(Level.WARNING, "Failed to convert old Head Data...", e);
}
}
@ -228,18 +239,16 @@ public class CustomHeads extends JavaPlugin {
public void onEnable() {
instance = this;
pluginLogger = instance.getLogger();
if(DEV_BUILD) {
getServer().getConsoleSender().sendMessage("[CustomHeads]\n§e=============================================================================================\nThis is a Dev Version of the Plugin! Please update update as soon as a new Version gets released\n=============================================================================================");
}
try {
} catch(Exception e) {
bukkitVersion = Bukkit.getVersion().substring(Bukkit.getVersion().lastIndexOf("("));
}
bukkitVersion = Bukkit.getVersion().substring(Bukkit.getVersion().lastIndexOf("("));
Version current = Version.getCurrentVersion();
getLogger().info("Using " + current.name() + " as Version Handler");
getPluginLogger().info("Using " + current.name() + " as Version Handler");
if (current == Version.LATEST) {
getServer().getConsoleSender().sendMessage(chWarning + "Hrm. Seems like CustomHeads wasn't tested on this Minecraft Version (" + CustomHeads.version + ") yet...");
getServer().getConsoleSender().sendMessage(chWarning + "Feel free to join my Discord to know when it gets updated");
getServer().getConsoleSender().sendMessage(PREFIX_WARNING + "Hrm. Seems like CustomHeads wasn't tested on this Minecraft Version (" + Version.getRawVersion() + ") yet...");
getServer().getConsoleSender().sendMessage(PREFIX_WARNING + "Feel free to join my Discord to know when it gets updated");
}
File oldHeadFile;
if ((oldHeadFile = new File("plugins/CustomHeads", "heads.yml")).exists()) {
@ -257,14 +266,14 @@ public class CustomHeads extends JavaPlugin {
// Check if Language File exists
String selectedLanguage = headsConfig.get().getString("langFile");
if (!new File("plugins/CustomHeads/language/" + selectedLanguage).exists()) {
getServer().getConsoleSender().sendMessage(chWarning + "Could not find language/" + selectedLanguage + ". Looking up available Languages...");
getServer().getConsoleSender().sendMessage(PREFIX_WARNING + "Could not find language/" + selectedLanguage + ". Looking up available Languages...");
Utils.getAvailableLanguages(new FetchResult<List<String>>() {
public void success(List<String> strings) {
if(strings.contains(selectedLanguage + ".zip")) {
getServer().getConsoleSender().sendMessage(chPrefix + "§7Downloading " + selectedLanguage + "...");
getServer().getConsoleSender().sendMessage(PREFIX_GENERAL + "§7Downloading " + selectedLanguage + "...");
GitHubDownloader gitHubDownloader = new GitHubDownloader("IHasName", "CustomHeads").enableAutoUnzipping();
gitHubDownloader.download(getDescription().getVersion(), selectedLanguage + ".zip", new File(getDataFolder(), "language"), () -> {
getServer().getConsoleSender().sendMessage(chPrefix + "§7Done downloading! Have fun with the Plugin =D");
getServer().getConsoleSender().sendMessage(PREFIX_GENERAL + "§7Done downloading! Have fun with the Plugin =D");
Utils.runSynced(new BukkitRunnable() {
public void run() {
loadRest();
@ -272,7 +281,7 @@ public class CustomHeads extends JavaPlugin {
});
});
} else {
getLogger().log(Level.WARNING, "Couldn't find selected Language. Using default instead");
getPluginLogger().log(Level.WARNING, "Couldn't find selected Language. Using default instead");
downloadDefaultLanguage();
}
}
@ -280,12 +289,12 @@ public class CustomHeads extends JavaPlugin {
public void error(Exception exception) {
if(exception instanceof GitHubDownloader.RateLimitExceededException) {
GitHubDownloader.RateLimitExceededException rateLimitException = (GitHubDownloader.RateLimitExceededException)exception;
getLogger().log(Level.WARNING, "GitHub Rate-Limited the Plugins Requests. Please try again later. (Time until Reset: " + rateLimitException.getTimeUntilReset() + ")");
getLogger().log(Level.WARNING, "If this Error continues to occur try downloading it manually from Github (https://github.com/IHasName/CustomHeads/releases/download/" + instance.getDescription().getVersion() + "/en_EN.zip)");
getLogger().log(Level.INFO, "A Tutorial on how to do that can be found on the Wiki");
getPluginLogger().log(Level.WARNING, "GitHub Rate-Limited the Plugins Requests. Please try again later. (Time until Reset: " + rateLimitException.getTimeUntilReset() + ")");
getPluginLogger().log(Level.WARNING, "If this Error continues to occur try downloading it manually from Github (https://github.com/IHasName/CustomHeads/releases/download/" + instance.getDescription().getVersion() + "/en_EN.zip)");
getPluginLogger().log(Level.INFO, "A Tutorial on how to do that can be found on the Wiki");
Bukkit.getPluginManager().disablePlugin(instance);
} else {
getLogger().log(Level.WARNING, "Failed to lookup Languages trying to use default instead");
getPluginLogger().log(Level.WARNING, "Failed to lookup Languages trying to use default instead");
downloadDefaultLanguage();
}
}
@ -307,11 +316,11 @@ public class CustomHeads extends JavaPlugin {
file.delete();
}
}
getServer().getConsoleSender().sendMessage(chWarning + "I wasn't able to find the Default Language File on your Server...");
getServer().getConsoleSender().sendMessage(chPrefix + "§7Downloading necessary Files...");
getServer().getConsoleSender().sendMessage(PREFIX_WARNING + "I wasn't able to find the Default Language File on your Server...");
getServer().getConsoleSender().sendMessage(PREFIX_GENERAL + "§7Downloading necessary Files...");
GitHubDownloader gitHubDownloader = new GitHubDownloader("IHasName", "CustomHeads").enableAutoUnzipping();
gitHubDownloader.download(getDescription().getVersion(), "en_EN.zip", new File(getDataFolder(), "language"), () -> {
getServer().getConsoleSender().sendMessage(chPrefix + "§7Done downloading! Have fun with the Plugin =D");
getServer().getConsoleSender().sendMessage(PREFIX_GENERAL + "§7Done downloading! Have fun with the Plugin =D");
Utils.runSynced(new BukkitRunnable() {
public void run() {
loadRest();
@ -341,7 +350,7 @@ public class CustomHeads extends JavaPlugin {
// Convert old Head-Data if present
playerDataFile = new JsonFile("playerData.json");
if (headsConfig.get().contains("heads")) {
Bukkit.getConsoleSender().sendMessage(chPrefix + "Found old Head Data! Trying to convert...");
Bukkit.getConsoleSender().sendMessage(PREFIX_GENERAL + "Found old Head Data! Trying to convert...");
convertOldHeadData();
}
@ -349,7 +358,7 @@ public class CustomHeads extends JavaPlugin {
// Load Language
if (!reloadTranslations(headsConfig.get().getString("langFile"))) {
getServer().getConsoleSender().sendMessage(chError + "Unable to load Language from language/" + headsConfig.get().getString("langFile"));
getServer().getConsoleSender().sendMessage(PREFIX_ERROR + "Unable to load Language from language/" + headsConfig.get().getString("langFile"));
Bukkit.getServer().getPluginManager().disablePlugin(instance);
return;
}
@ -359,7 +368,7 @@ public class CustomHeads extends JavaPlugin {
// Register Listeners
manager.registerEvents(new InventoryListener(), instance);
manager.registerEvents(new OtherListeners(), instance);
manager.registerEvents(new CategoryEditorListener(), instance);
// manager.registerEvents(new CategoryEditorListener(), instance);
// Reload Configs
reloadHistoryData();
@ -378,7 +387,7 @@ public class CustomHeads extends JavaPlugin {
spigetFetcher.fetchUpdates(new SpigetResourceFetcher.FetchResult() {
public void updateAvailable(SpigetResourceFetcher.ResourceRelease release, SpigetResourceFetcher.ResourceUpdate update) {
if (headsConfig.get().getBoolean("update-notifications.console")) {
getServer().getConsoleSender().sendMessage(chPrefix + "§bNew Update for CustomHeads found! v" + release.getReleaseName() + " (Running on v" + getDescription().getVersion() + ") - You can Download it here https://www.spigotmc.org/resources/29057");
getServer().getConsoleSender().sendMessage(PREFIX_GENERAL + "§bNew Update for CustomHeads found! v" + release.getReleaseName() + " (Running on v" + getDescription().getVersion() + ") - You can Download it here https://www.spigotmc.org/resources/29057");
}
}
@ -392,11 +401,34 @@ public class CustomHeads extends JavaPlugin {
initMetrics();
}
// -- Timers
Utils.runAsync(new BukkitRunnable() {
public void run() {
doDelayedTasks();
}
});
initAsyncTimers();
isInit = true;
}
private void doDelayedTasks() {
if(!delayedTasks.isEmpty()) {
CustomHeads.getPluginLogger().info("Running delayed Tasks...");
delayedTasks.forEach(task -> {
try {
task.call();
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
private void initAsyncTimers() {
// Clear Cache every 30 Minutes
Utils.runAsyncTimer(new BukkitRunnable() {
public void run() {
uuidCache.clear();
UUID_CACHE.clear();
HeadFontType.clearCache();
GitHubDownloader.clearCache();
GameProfileBuilder.cache.clear();
@ -406,48 +438,44 @@ public class CustomHeads extends JavaPlugin {
}, 36000, 36000);
// Animation Timer
Utils.runAsyncTimer(
new BukkitRunnable() {
public void run() {
getServer().getOnlinePlayers().stream().filter(player -> player.getOpenInventory() != null && player.getOpenInventory().getType() == InventoryType.CHEST && CustomHeads.getLooks().getMenuTitles().contains(player.getOpenInventory().getTitle())).collect(Collectors.toList()).forEach(player -> {
Inventory targetInventory = player.getOpenInventory().getTopInventory();
ItemStack[] inventoryContent = targetInventory.getContents();
for (int i = 0; i < inventoryContent.length; i++) {
if (inventoryContent[i] == null) continue;
ItemStack contentItem = inventoryContent[i];
if (CustomHeads.getTagEditor().getTags(contentItem).contains("openCategory") && CustomHeads.getTagEditor().getTags(contentItem).contains("icon-loop")) {
String[] categoryArgs = CustomHeads.getTagEditor().getTags(contentItem).get(CustomHeads.getTagEditor().indexOf(contentItem, "openCategory") + 1).split("#>");
if (categoryArgs[0].equals("category")) {
CustomHeadsPlayer customHeadsPlayer = api.wrapPlayer(player);
Category category = CustomHeads.getCategoryManager().getCategory(categoryArgs[1]);
ItemStack nextIcon = category.nextIcon();
boolean bought = customHeadsPlayer.getUnlockedCategories(true).contains(category);
nextIcon = new ItemEditor(nextIcon)
.setDisplayName(customHeadsPlayer.getUnlockedCategories(CustomHeads.hasEconomy() && !CustomHeads.keepCategoryPermissions()).contains(category) ? "§a" + nextIcon.getItemMeta().getDisplayName() : "§7" + ChatColor.stripColor(nextIcon.getItemMeta().getDisplayName()) + " " + CustomHeads.getLanguageManager().LOCKED)
.addLoreLine(CustomHeads.hasEconomy() && CustomHeads.categoriesBuyable() ? bought ? CustomHeads.getLanguageManager().ECONOMY_BOUGHT : Utils.getCategoryPriceFormatted(category, true) + "\n" + CustomHeads.getLanguageManager().ECONOMY_BUY_PROMPT : null)
.addLoreLines(hasPermission(player, "heads.view.permissions") ? Arrays.asList(" ", "§7§oPermission: " + category.getPermission()) : null)
.getItem();
if (CustomHeads.hasEconomy() && !CustomHeads.keepCategoryPermissions()) {
if (!bought) {
nextIcon = CustomHeads.getTagEditor().addTags(nextIcon, "buyCategory", category.getId());
}
Utils.runAsyncTimer(new BukkitRunnable() {
public void run() {
getServer().getOnlinePlayers().stream().filter(player -> player.getOpenInventory() != null && player.getOpenInventory().getType() == InventoryType.CHEST && CustomHeads.getLooks().getMenuTitles().contains(player.getOpenInventory().getTitle())).collect(Collectors.toList()).forEach(player -> {
Inventory targetInventory = player.getOpenInventory().getTopInventory();
ItemStack[] inventoryContent = targetInventory.getContents();
for (int i = 0; i < inventoryContent.length; i++) {
if (inventoryContent[i] == null) continue;
ItemStack contentItem = inventoryContent[i];
if (CustomHeads.getTagEditor().getTags(contentItem).contains("openCategory") && CustomHeads.getTagEditor().getTags(contentItem).contains("icon-loop")) {
String[] categoryArgs = CustomHeads.getTagEditor().getTags(contentItem).get(CustomHeads.getTagEditor().indexOf(contentItem, "openCategory") + 1).split("#>");
if (categoryArgs[0].equals("category")) {
CustomHeadsPlayer customHeadsPlayer = api.wrapPlayer(player);
Category category = CustomHeads.getCategoryManager().getCategory(categoryArgs[1]);
ItemStack nextIcon = category.nextIcon();
boolean bought = customHeadsPlayer.getUnlockedCategories(true).contains(category);
nextIcon = new ItemEditor(nextIcon)
.setDisplayName(customHeadsPlayer.getUnlockedCategories(CustomHeads.hasEconomy() && !CustomHeads.keepCategoryPermissions()).contains(category) ? "§a" + nextIcon.getItemMeta().getDisplayName() : "§7" + ChatColor.stripColor(nextIcon.getItemMeta().getDisplayName()) + " " + CustomHeads.getLanguageManager().LOCKED)
.addLoreLine(CustomHeads.hasEconomy() && CustomHeads.categoriesBuyable() ? bought ? CustomHeads.getLanguageManager().ECONOMY_BOUGHT : Utils.getCategoryPriceFormatted(category, true) + "\n" + CustomHeads.getLanguageManager().ECONOMY_BUY_PROMPT : null)
.addLoreLines(hasPermission(player, "heads.view.permissions") ? Arrays.asList(" ", "§7§oPermission: " + category.getPermission()) : null)
.getItem();
if (CustomHeads.hasEconomy() && !CustomHeads.keepCategoryPermissions()) {
if (!bought) {
nextIcon = CustomHeads.getTagEditor().addTags(nextIcon, "buyCategory", category.getId());
}
contentItem = nextIcon;
}
}
if (tagEditor.hasMyTags(contentItem)) {
contentItem = CustomHeads.getTagEditor().addTags(contentItem, "menuID", CustomHeads.getLooks().getIDbyTitle(player.getOpenInventory().getTitle()));
}
if(!contentItem.equals(inventoryContent[i])) {
targetInventory.setItem(i, contentItem);
contentItem = nextIcon;
}
}
});
}
if (tagEditor.hasMyTags(contentItem)) {
contentItem = CustomHeads.getTagEditor().addTags(contentItem, "menuID", CustomHeads.getLooks().getIDbyTitle(player.getOpenInventory().getTitle()));
}
if(!contentItem.equals(inventoryContent[i])) {
targetInventory.setItem(i, contentItem);
}
}
});
}
}, 0, 20);
isInit = true;
}
}

View File

@ -7,16 +7,12 @@ import de.likewhat.customheads.utils.JsonToItem;
import de.likewhat.customheads.utils.Utils;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;
/*
@ -45,7 +41,7 @@ public class Category extends BaseCategory {
super(String.valueOf(id), name, permission);
this.price = price;
categoryIcon = icon;
this.icons = Arrays.asList(icon);
this.icons = Collections.singletonList(icon);
iterator = icons.iterator();
}
@ -81,11 +77,15 @@ public class Category extends BaseCategory {
return !heads.isEmpty();
}
public Category setSubCategories(List<SubCategory> subCategories) {
Category setSubCategories(List<SubCategory> subCategories) {
this.subCategories = subCategories;
return this;
}
public boolean removeSubCategory(SubCategory subCategory) {
return this.subCategories.remove(subCategory);
}
public boolean isUsed() {
return CustomHeads.getLooks().getUsedCategories().contains(this);
}
@ -126,7 +126,7 @@ public class Category extends BaseCategory {
if (heads.stream().map(CustomHead::getId).collect(Collectors.toList()).contains(id)) {
int newID = nextID();
if(!CustomHeads.hasReducedDebug())
Bukkit.getLogger().warning("Duplicate or duplicate ID: " + id + ". Replacing with " + newID);
CustomHeads.getPluginLogger().warning("Duplicate or duplicate ID: " + id + ". Replacing with " + newID);
return newID;
}
return id;

View File

@ -11,6 +11,7 @@ import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@ -27,15 +28,15 @@ public class CategoryManager {
@Getter
private static boolean loaded;
private HashMap<String, SubCategory> subCategories = new HashMap<>();
private HashMap<String, Category> categories = new HashMap<>();
private HashMap<Category, File> sourceFiles = new HashMap<>();
private File langRootDir;
private final HashMap<String, SubCategory> subCategories = new HashMap<>();
private final HashMap<String, Category> categories = new HashMap<>();
private final HashMap<Category, File> sourceFiles = new HashMap<>();
private final File langRootDir;
private String language;
private final String language;
private int defaultCategoryPrice;
private int defaultHeadPrice;
private final int defaultCategoryPrice;
private final int defaultHeadPrice;
public CategoryManager(String language) {
loaded = false;
@ -44,8 +45,6 @@ public class CategoryManager {
defaultCategoryPrice = CustomHeads.getHeadsConfig().get().getInt("economy.category.default-price");
defaultHeadPrice = CustomHeads.getHeadsConfig().get().getInt("economy.heads.default-price");
loaded = false;
}
public void load() {
@ -58,17 +57,16 @@ public class CategoryManager {
File[] files = langRootDir.listFiles((dir, name) -> name.endsWith(".json") && !CustomHeads.getHeadsConfig().get().getList("disabledCategories").contains(name.substring(0, name.lastIndexOf("."))));
if(files == null || Arrays.asList(files).isEmpty()) {
CustomHeads.getInstance().getServer().getConsoleSender().sendMessage(CustomHeads.chWarning + "No Categories found in language/" + language + "/categories");
CustomHeads.getInstance().getServer().getConsoleSender().sendMessage(CustomHeads.PREFIX_WARNING + "No Categories found in language/" + language + "/categories");
loaded = true;
return;
}
List<File> fileList = Arrays.asList(files);
if (!CustomHeads.hasReducedDebug())
CustomHeads.getInstance().getServer().getConsoleSender().sendMessage(CustomHeads.chPrefix + "Loading " + fileList.size() + " Categories from " + language + "/categories...");
CustomHeads.getInstance().getServer().getConsoleSender().sendMessage(CustomHeads.PREFIX_GENERAL + "Loading " + fileList.size() + " Categories from " + language + "/categories...");
long timestamp = System.currentTimeMillis();
CustomHeads.getHeadsConfig().reload();
for (File file : fileList) {
JsonFile jsf = new JsonFile(file);
categoriesIgnored = CustomHeads.getHeadsConfig().get().getList("disabledCategories").size();
@ -76,10 +74,10 @@ public class CategoryManager {
Category category = Category.getConverter().fromJson(jsf.getJson(), Category.class);
if (category == null) {
categoriesInvalid++;
Bukkit.getServer().getConsoleSender().sendMessage(CustomHeads.chWarning + " Invalid Category in " + file.getName());
Bukkit.getServer().getConsoleSender().sendMessage(CustomHeads.PREFIX_WARNING + " Invalid Category in " + file.getName());
} else {
if (categories.containsKey(category.getId())) {
CustomHeads.getInstance().getServer().getConsoleSender().sendMessage(CustomHeads.chWarning + file.getName() + ": §cAn Category with ID " + category.getId() + " (" + categories.get(category.getId()).getName() + ") already exists.");
CustomHeads.getInstance().getServer().getConsoleSender().sendMessage(CustomHeads.PREFIX_WARNING + file.getName() + ": §cAn Category with ID " + category.getId() + " (" + categories.get(category.getId()).getName() + ") already exists.");
categoriesInvalid++;
continue;
}
@ -89,7 +87,7 @@ public class CategoryManager {
if (category.hasSubCategories()) {
for (SubCategory subCategory : category.getSubCategories()) {
if (subCategories.containsKey(subCategory.getId())) {
CustomHeads.getInstance().getServer().getConsoleSender().sendMessage(CustomHeads.chWarning + file.getName() + ": §cAn Subcategory with ID " + subCategory.getId() + " (" + subCategories.get(subCategory.getId()).getName() + ") already exists.");
CustomHeads.getInstance().getServer().getConsoleSender().sendMessage(CustomHeads.PREFIX_WARNING + file.getName() + ": §cAn Subcategory with ID " + subCategory.getId() + " (" + subCategories.get(subCategory.getId()).getName() + ") already exists.");
continue;
}
subCategories.put(subCategory.getId(), subCategory);
@ -97,13 +95,13 @@ public class CategoryManager {
}
}
} catch (Exception e) {
CustomHeads.getInstance().getLogger().log(Level.WARNING, "Something went wrong while loading Category File " + file.getName(), e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Something went wrong while loading Category File " + file.getName(), e);
return;
}
}
if (!CustomHeads.hasReducedDebug())
CustomHeads.getInstance().getServer().getConsoleSender().sendMessage(CustomHeads.chPrefix + "Successfully loaded " + categoriesLoaded + " Categories and " + getAllHeads().size() + " Heads from " + language + "/categories in " + (System.currentTimeMillis() - timestamp) + "ms (" + (categoriesIgnored + categoriesInvalid) + " " + ((categoriesIgnored + categoriesInvalid) == 1 ? "Category was" : "Categories were") + " ignored - " + categoriesIgnored + " not loaded or not found, " + (categoriesInvalid > 0 ? "§c" : "") + categoriesInvalid + " invalid§7)");
CustomHeads.getInstance().getServer().getConsoleSender().sendMessage(CustomHeads.PREFIX_GENERAL + "Successfully loaded " + categoriesLoaded + " Categories and " + getAllHeads().size() + " Heads from " + language + "/categories in " + (System.currentTimeMillis() - timestamp) + "ms (" + (categoriesIgnored + categoriesInvalid) + " " + ((categoriesIgnored + categoriesInvalid) == 1 ? "Category was" : "Categories were") + " ignored - " + categoriesIgnored + " not loaded or not found, " + (categoriesInvalid > 0 ? "§c" : "") + categoriesInvalid + " invalid§7)");
loaded = true;
}
@ -111,7 +109,7 @@ public class CategoryManager {
File categoryFile;
if (!(categoryFile = new File(CustomHeads.getInstance().getDataFolder() + "/language/" + forLanguage)).exists())
throw new IllegalArgumentException("Language " + forLanguage + " does not exist");
try (OutputStreamWriter outputStream = new OutputStreamWriter(new FileOutputStream(new File(categoryFile + "/categories", category.getName() + ".json")), StandardCharsets.UTF_8)) {
try (OutputStreamWriter outputStream = new OutputStreamWriter(Files.newOutputStream(new File(categoryFile + "/categories", category.getName() + ".json").toPath()), StandardCharsets.UTF_8)) {
outputStream.write(category.toString());
outputStream.flush();
} catch (Exception e) {
@ -145,7 +143,7 @@ public class CategoryManager {
CustomHeads.getHeadsConfig().save();
}
} catch (Exception e) {
CustomHeads.getInstance().getLogger().log(Level.WARNING, "Something went wrong while loading Category File " + file.getName(), e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Something went wrong while loading Category File " + file.getName(), e);
return 4;
}
return 0;

View File

@ -142,7 +142,7 @@ public class CategorySetup {
category.setPrice(price);
category.setIcons(Arrays.asList(new ItemEditor(icon).setDisplayName(name).setLore(description).getItem()));
CustomHeads.getCategoryManager().updateCategory(category, CustomHeads.getLanguageManager().getCurrentLanguage());
CustomHeads.silentReload();
CustomHeads.reload(null);
player.closeInventory();
player.sendMessage("Successfully created Category");
}

View File

@ -17,9 +17,9 @@ import org.bukkit.inventory.ItemStack;
@Getter
public class CustomHead extends ItemStack {
private Category originCategory;
private int price;
private int id;
private final Category originCategory;
private final int price;
private final int id;
public CustomHead(ItemStack itemStack, Category originCategory, int id, int price) {
super(CustomHeads.getTagEditor().addTags(itemStack, "headID", originCategory.getId() + ":" + id, "price", String.valueOf(price)));

View File

@ -18,11 +18,9 @@ import java.util.List;
@Getter
public class SubCategory extends BaseCategory {
private Category originCategory;
private ItemStack categoryIcon;
private List<CustomHead> heads;
private final Category originCategory;
private final ItemStack categoryIcon;
private final List<CustomHead> heads;
SubCategory(String id, String name, ItemStack categoryIcon, Category originCategory, List<CustomHead> heads) {
super(id, name, "");

View File

@ -40,15 +40,17 @@ import static de.likewhat.customheads.utils.Utils.*;
public class CustomHeadsCommand implements CommandExecutor {
private static final Comparator<Category> categoryComparator = Comparator.comparing(category -> Integer.parseInt(category.getId()));
public HashMap<Player, String[]> haltedCommands = new HashMap<>();
private String[] rdmAns = {"CustomHeads says: Hmm", "CustomHeads says: Does the Console have an Inventory?", "CustomHeads says: That tickels!", "CustomHeads says: No", "CustomHeads says: Im lost", "CustomHeads says: I don't think this is what you are searching for", "CustomHeads says: Hold on... Nevermind", "CustomHeads says: Sorry", "CustomHeads says: Spoilers... There will be a new Command soon =]"};
private FireworkEffect.Type[] fxTypes = {FireworkEffect.Type.BALL, FireworkEffect.Type.BALL_LARGE, FireworkEffect.Type.BURST, FireworkEffect.Type.STAR};
private BlockFace[] faces = {BlockFace.NORTH, BlockFace.NORTH_EAST, BlockFace.NORTH_NORTH_EAST};
private Random ran = new Random();
private List<Player> active_fireworks = new ArrayList<>();
public static final List<Location> CACHED_FIREWORKS = new ArrayList<>();
private static final Comparator<Category> CATEGORY_COMPARER = Comparator.comparing(category -> Integer.parseInt(category.getId()));
private static final List<Player> ACTIVE_FIREWORKS = new ArrayList<>();
private static final String[] RANDOM_ANSWERS = {"CustomHeads says: Hmm", "CustomHeads says: Does the Console have an Inventory?", "CustomHeads says: That tickels!", "CustomHeads says: No", "CustomHeads says: Im lost", "CustomHeads says: I don't think this is what you are searching for", "CustomHeads says: Hold on... Nevermind", "CustomHeads says: Sorry", "CustomHeads says: Spoilers... There will be a new Command soon =]"};
private static final Random RANDOM = new Random();
private final HashMap<Player, String[]> haltedCommands = new HashMap<>();
private final FireworkEffect.Type[] fxTypes = {FireworkEffect.Type.BALL, FireworkEffect.Type.BALL_LARGE, FireworkEffect.Type.BURST, FireworkEffect.Type.STAR};
private final BlockFace[] faces = {BlockFace.NORTH, BlockFace.NORTH_EAST, BlockFace.NORTH_NORTH_EAST};
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (!(sender instanceof Player)) {
if (args.length > 0) {
@ -74,7 +76,7 @@ public class CustomHeadsCommand implements CommandExecutor {
// }
}
Random rdm = new Random();
sender.sendMessage(rdmAns[rdm.nextInt(rdmAns.length)]);
sender.sendMessage(RANDOM_ANSWERS[rdm.nextInt(RANDOM_ANSWERS.length)]);
return true;
}
Player player = (Player) sender;
@ -129,7 +131,7 @@ public class CustomHeadsCommand implements CommandExecutor {
try {
success = CustomHeads.reloadTranslations(args[2]);
} catch(NullPointerException e) {
Bukkit.getLogger().log(Level.WARNING, "Failed to load Language", e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to load Language", e);
}
if (success) {
headsConfig.get().set("langFile", args[2]);
@ -184,6 +186,10 @@ public class CustomHeadsCommand implements CommandExecutor {
if (args[0].equalsIgnoreCase("test")) {
try {
Configs tempcon = new Configs(CustomHeads.getInstance(), "test.yml", false, "testing");
if(args[1].equalsIgnoreCase("nbt")) {
Object result = ItemNBTUtils.getTagFromItem(player.getItemInHand(), true);
player.sendMessage(result == null ? "null" : result.toString());
}
if (args[1].equalsIgnoreCase("gettags")) {
player.sendMessage("[Tags] " + CustomHeads.getTagEditor().getTags(player.getItemInHand()));
}
@ -208,7 +214,7 @@ public class CustomHeadsCommand implements CommandExecutor {
player.sendMessage(CustomHeads.getLanguageManager().CATEGORIES_BASECOMMAND_HEADER);
List<Category> categories = CustomHeads.getCategoryManager().getCategoryList();
categories.sort(categoryComparator);
categories.sort(CATEGORY_COMPARER);
for (int i = 0; i < categories.size(); i++) {
Category cCategory = categories.get(i);
@ -225,13 +231,13 @@ public class CustomHeadsCommand implements CommandExecutor {
for (int j = 0; j < cCategory.getSubCategories().size(); j++) {
SubCategory cSubCategory = cCategory.getSubCategories().get(j);
String hoverInfoSubCategoryBuilder = "{\"text\":\"";
StringBuilder hoverInfoSubCategoryBuilder = new StringBuilder("{\"text\":\"");
for (String hoverInfoSubCategory : CustomHeads.getLanguageManager().CATEGORIES_BASECOMMAND_HOVERINFO_SUBCATEGORY) {
hoverInfoSubCategoryBuilder += hoverInfoSubCategory + "\n";
hoverInfoSubCategoryBuilder.append(hoverInfoSubCategory).append("\n");
}
hoverInfoSubCategoryBuilder = hoverInfoSubCategoryBuilder.replace("{ID}", "" + cCategory.getId()).replace("{CATEGORY}", cCategory.getName()).replace("{USED}", cSubCategory.isUsed() ? CustomHeads.getLanguageManager().YES : CustomHeads.getLanguageManager().NO);
hoverInfoSubCategoryBuilder = hoverInfoSubCategoryBuilder.substring(0, hoverInfoSubCategoryBuilder.length() - 1);
hoverInfoSubCategoryBuilder += "\"}";
hoverInfoSubCategoryBuilder = new StringBuilder(hoverInfoSubCategoryBuilder.toString().replace("{ID}", "" + cCategory.getId()).replace("{CATEGORY}", cCategory.getName()).replace("{USED}", cSubCategory.isUsed() ? CustomHeads.getLanguageManager().YES : CustomHeads.getLanguageManager().NO));
hoverInfoSubCategoryBuilder = new StringBuilder(hoverInfoSubCategoryBuilder.substring(0, hoverInfoSubCategoryBuilder.length() - 1));
hoverInfoSubCategoryBuilder.append("\"}");
Utils.sendJSONMessage("[\"\",{\"text\":\" §e" + (i == (categories.size() - 1) ? " " : "") + " " + (j == (cCategory.getSubCategories().size() - 1) ? "┗╸" : "┣╸") + " \"},{\"text\":\"" + (cCategory.isUsed() ? "§a" : "§7") + ChatColor.stripColor(cSubCategory.getName()) + "\"" +/*(CustomHeads.hasCategoryEditor() ? ",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/cedit " + cSubCategory.getId() + "\"}" : "") +*/",\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[" + hoverInfoSubCategoryBuilder +/*",{\"text\":\"\n" + (CustomHeads.hasCategoryEditor() ? "§eClick to open in Editor" : "§eGet CategoryCreator to\n§eopen an Editor") + "\"}" +*/"]}}}]", player);
}
@ -443,20 +449,20 @@ public class CustomHeadsCommand implements CommandExecutor {
player.sendMessage(CustomHeads.getLanguageManager().CANNOT_PLACE_IN_AIR);
return true;
}
if (active_fireworks.contains(player)) {
if (ACTIVE_FIREWORKS.contains(player)) {
player.sendMessage(CustomHeads.getLanguageManager().ALREADY_IN_USE);
return true;
}
player.sendMessage(CustomHeads.getLanguageManager().STARTING);
active_fireworks.add(player);
ACTIVE_FIREWORKS.add(player);
Location startLocation = player.getLocation().getBlock().getLocation().add(.5, .5, .5);
CACHED_FIREWORKS.add(startLocation);
CustomHeads.getApi().createFireworkBattery(startLocation, 10, 20, new FireworksBatteryHandler() {
Location location = startLocation.clone();
Random random = new Random();
final Location location = startLocation.clone();
final Random random = new Random();
public void onStart() {
CustomHeads.getApi().setSkull(location.getBlock(), "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOGEzZDVkNWIyY2YzMzEyOTllNjNkNzYxOGExNDI2NmU4Y2NjNjE1OGU5ZTMxZmNiMGJkOTExZTEyZmY3NzM2In19fQ==", faces[ran.nextInt(faces.length)]);
CustomHeads.getApi().setSkull(location.getBlock(), "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOGEzZDVkNWIyY2YzMzEyOTllNjNkNzYxOGExNDI2NmU4Y2NjNjE1OGU5ZTMxZmNiMGJkOTExZTEyZmY3NzM2In19fQ==", faces[RANDOM.nextInt(faces.length)]);
}
public void onNext() {
@ -648,10 +654,10 @@ public class CustomHeadsCommand implements CommandExecutor {
return true;
}
// Edit {FONTNAME}
HashMap<Character, ItemStack> characters = font.getCharacters();
HashMap<Character, ItemStack> characters = font.getCharacterItems();
List<ItemStack> characterList = new ArrayList<>();
characterList.sort(Comparator.comparing(itemStack -> itemStack.getItemMeta().getDisplayName()));
characters.forEach((character, customHead) -> characterList.add(CustomHeads.getTagEditor().addTags(new ItemEditor(customHead).setDisplayName("§b" + (character.equals(' ') ? "BLANK" : character)).getItem(), "fontName", font.getFontName(), "character", "" + character, "editFont", "select")));
characterList.sort(Comparator.comparing(itemStack -> itemStack.getItemMeta().getDisplayName()));
ScrollableInventory editFont = new ScrollableInventory(CustomHeads.getLanguageManager().FONTS_EDIT_TITLE.replace("{FONT}", font.getFontName()), characterList);
editFont.setExtraTags("fontName", font.getFontName());
/* |-|-|0|1|2|3|4|-|-|
@ -673,22 +679,17 @@ public class CustomHeadsCommand implements CommandExecutor {
}
if(args[0].equalsIgnoreCase("random")) {
List<CustomHead> heads = CustomHeads.getCategoryManager().getAllHeads();
CustomHead randomHead = heads.get(RANDOM.nextInt(heads.size()));
CustomHead randomHead = heads.get(Utils.RANDOM.nextInt(heads.size()));
if(randomHead.isFree()) {
player.getInventory().addItem(randomHead);
} else {
// Category category = randomHead.getOriginCategory();
Utils.showInteractiveDialog(player, CustomHeads.getLanguageManager().ECONOMY_BUY_CONFIRM.replace("{ITEM}", ChatColor.stripColor(randomHead.getItemMeta().getDisplayName())).replace("{PRICE}", getHeadPriceFormatted(randomHead, false)), new SimpleCallback<Boolean>() {
CustomHead head = randomHead;
CustomHeadsPlayer p = CustomHeads.getApi().wrapPlayer(player);
public void call(Boolean buySuccessful) {
if(buySuccessful) {
CustomHeads.getEconomyManager().buyHead(p, head.getOriginCategory(), head.getId(), CustomHeads.headsPermanentBuy());
p.unwrap().getInventory().addItem(head.getPlainItem());
} else {
p.unwrap().closeInventory();
}
Utils.showInteractiveDialog(player, CustomHeads.getLanguageManager().ECONOMY_BUY_CONFIRM.replace("{ITEM}", ChatColor.stripColor(randomHead.getItemMeta().getDisplayName())).replace("{PRICE}", getHeadPriceFormatted(randomHead, false)), success -> {
CustomHeadsPlayer customHeadsPlayer = CustomHeads.getApi().wrapPlayer(player);
if(success) {
CustomHeads.getEconomyManager().buyHead(customHeadsPlayer, randomHead.getOriginCategory(), randomHead.getId(), CustomHeads.headsPermanentBuy());
customHeadsPlayer.unwrap().getInventory().addItem(randomHead.getPlainItem());
} else {
customHeadsPlayer.unwrap().closeInventory();
}
}, null, null, randomHead.getPlainItem());
}
@ -709,7 +710,7 @@ public class CustomHeadsCommand implements CommandExecutor {
player.sendMessage(CustomHeads.getLanguageManager().SAVE_OWN_SUCCESSFUL.replace("{NAME}", format(args[1])));
} catch (Exception e) {
sender.sendMessage(CustomHeads.getLanguageManager().SAVE_OWN_FAILED);
Bukkit.getLogger().log(Level.WARNING, "Failed to get Playertexture", e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to get Playertexture", e);
}
});
return true;
@ -796,7 +797,7 @@ public class CustomHeadsCommand implements CommandExecutor {
}
if (builder.length() != 0)
builder.setLength(builder.length() - 2);
player.sendMessage(CustomHeads.getLanguageManager().COMMAND_USAGE.replace("{COMMAND}", "/heads " + (builder.length() == 0 ? "" : "<" + builder.toString() + ">")));
player.sendMessage(CustomHeads.getLanguageManager().COMMAND_USAGE.replace("{COMMAND}", "/heads " + (builder.length() == 0 ? "" : "<" + builder + ">")));
return true;
}
StringBuilder builder = new StringBuilder();
@ -807,7 +808,7 @@ public class CustomHeadsCommand implements CommandExecutor {
}
if (builder.length() != 0)
builder.setLength(builder.length() - 2);
player.sendMessage(CustomHeads.getLanguageManager().COMMAND_USAGE.replace("{COMMAND}", "/heads " + (builder.length() == 0 ? "" : "<" + builder.toString() + ">")));
player.sendMessage(CustomHeads.getLanguageManager().COMMAND_USAGE.replace("{COMMAND}", "/heads " + (builder.length() == 0 ? "" : "<" + builder + ">")));
return true;
}
player.sendMessage(CustomHeads.getLanguageManager().NO_PERMISSION);

View File

@ -13,7 +13,7 @@ public interface EconomyHandler {
EconomyCallback handleWithdraw(Player player, double amount);
/**
* Whether or not the Plugin/Handler is currently able to handle incoming Economy Requests
* Whether the Plugin/Handler is currently able to handle incoming Economy Requests
* Example: {@link de.likewhat.customheads.economy.handlers.Vault}
* @return true/false
*/

View File

@ -6,12 +6,12 @@ import de.likewhat.customheads.category.Category;
import de.likewhat.customheads.category.CustomHead;
import de.likewhat.customheads.economy.errors.InvalidEconomyHandlerException;
import de.likewhat.customheads.economy.handlers.Vault;
import de.likewhat.customheads.utils.SimpleCallback;
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.function.Consumer;
import static de.likewhat.customheads.utils.Utils.openCategory;
@ -26,13 +26,9 @@ public class EconomyManager {
private final HashMap<String, EconomyHandler> registeredHandlers = new HashMap<>();
private EconomyHandler activeEconomyHandler;
public EconomyManager() {
public EconomyManager() throws InvalidEconomyHandlerException {
if (Bukkit.getPluginManager().isPluginEnabled("Vault")) {
try {
registerAndSetActiveHandler(new Vault());
} catch(InvalidEconomyHandlerException e) {
e.printStackTrace();
}
registerAndSetActiveHandler(new Vault());
}
}
@ -48,7 +44,7 @@ public class EconomyManager {
public boolean registerHandler(String handlerName, EconomyHandler handler) throws InvalidEconomyHandlerException {
if(!handler.isValid()) {
throw new InvalidEconomyHandlerException("Invalid Handler passed as Argument");
throw new InvalidEconomyHandlerException("Cannot register invalid Economy Handler (" + handler.getName() + ")");
}
return registeredHandlers.putIfAbsent(handlerName, handler) == null;
}
@ -72,7 +68,6 @@ public class EconomyManager {
public void buyCategory(CustomHeadsPlayer customHeadsPlayer, Category category, String prevMenu) {
checkValidHandler();
//EconomyResponse economyResponse = economyPlugin.withdrawPlayer(customHeadsPlayer.unwrap(), category.getPrice());
EconomyCallback callback = activeEconomyHandler.handleWithdraw(customHeadsPlayer.unwrap(), category.getPrice());
if (callback.wasSuccess()) {
customHeadsPlayer.unlockCategory(category);
@ -87,11 +82,10 @@ public class EconomyManager {
checkValidHandler();
CustomHead customHead = CustomHeads.getApi().getHead(category, id);
if (customHead == null) {
CustomHeads.getInstance().getLogger().warning("Received invalid Head ID while buying (" + category.getId() + ":" + id + ")");
CustomHeads.getPluginLogger().warning("Received invalid Head ID while buying (" + category.getId() + ":" + id + ")");
return;
}
EconomyCallback callback = activeEconomyHandler.handleWithdraw(customHeadsPlayer.unwrap(), customHead.getPrice());
//EconomyResponse economyResponse = economyPlugin.withdrawPlayer(customHeadsPlayer.unwrap(), customHead.getPrice());
if (callback.wasSuccess()) {
if (permanent) {
customHeadsPlayer.unlockHead(category, id);
@ -104,16 +98,15 @@ public class EconomyManager {
}
}
public void buyItem(Player player, int price, String itemName, SimpleCallback<Boolean> successCallback) {
public void buyItem(Player player, int price, String itemName, Consumer<Boolean> successCallback) {
checkValidHandler();
// EconomyResponse economyResponse = economyPlugin.withdrawPlayer(player, price);
EconomyCallback callback = activeEconomyHandler.handleWithdraw(player, price);
if (callback.wasSuccess()) {
player.sendMessage(CustomHeads.getLanguageManager().ECONOMY_BUY_SUCCESSFUL.replace("{ITEM}", itemName));
successCallback.call(true);
successCallback.accept(true);
} else {
player.sendMessage(CustomHeads.getLanguageManager().ECONOMY_BUY_FAILED.replace("{REASON}", callback.getResponseMessage()).replace("{ITEM}", itemName));
successCallback.call(false);
successCallback.accept(false);
}
}

View File

@ -29,7 +29,7 @@ public class Vault implements EconomyHandler {
}
public String getName() {
return "Vault";
return "Vault" + (economyPlugin == null ? "" : (" using " + economyPlugin.getName()));
}
public String currencyNameSingular() {

View File

@ -23,17 +23,17 @@ import java.util.List;
@Getter
public class HeadFontType {
private char[] availableCharacters = "abcdefghijklmnopqrstuvwxyz0123456789!?#$%&@_'\"()[]{}<>+-/=:,;\\ ".toCharArray();
private static final char[] AVAILABLE_CHARACTERS = "abcdefghijklmnopqrstuvwxyz0123456789!?#$%&@_'\"()[]{}<>+-/=:,;\\ ".toCharArray();
private static HashMap<String, HeadFontType> cache = new HashMap<>();
private HashMap<Character, ItemStack> characters = new HashMap<>();
private static final HashMap<String, HeadFontType> FONT_CACHE = new HashMap<>();
private final HashMap<Character, ItemStack> characterItems = new HashMap<>();
@Getter(AccessLevel.NONE)
private Configs fontFile;
private final Configs fontFile;
private boolean cached = false;
private String fontName;
private final String fontName;
private String cacheID;
private long cacheTime;
@ -44,34 +44,34 @@ public class HeadFontType {
if (exists()) {
if (fontFile.get().isConfigurationSection("characters")) {
for (String key : fontFile.get().getConfigurationSection("characters").getKeys(false)) {
if (!Utils.charArrayContains(availableCharacters, key.charAt(0))) {
if (!Utils.charArrayContains(AVAILABLE_CHARACTERS, key.charAt(0))) {
throw new UnsupportedOperationException("Unsupported Character: '" + key.charAt(0) + "'");
}
characters.put(key.charAt(0), new ItemEditor(Material.SKULL_ITEM, 3).setTexture(fontFile.get().getString("characters." + key)).getItem());
characterItems.put(key.charAt(0), new ItemEditor(Material.SKULL_ITEM, 3).setTexture(fontFile.get().getString("characters." + key)).getItem());
}
}
}
}
public static HeadFontType getCachedFont(String cacheID) {
return cache.get(cacheID);
return FONT_CACHE.get(cacheID);
}
public static void clearCache() {
cache.values().removeIf(font -> System.currentTimeMillis() - font.cacheTime > 600000);
FONT_CACHE.values().removeIf(font -> System.currentTimeMillis() - font.cacheTime > 600000);
}
public boolean addCharacter(char character, String texture, boolean forceReplace) {
if (Utils.charArrayContains(availableCharacters, character) && (!characters.containsKey(character) || forceReplace)) {
characters.put(character, new ItemEditor(Material.SKULL_ITEM, 3).setTexture(texture).getItem());
if (Utils.charArrayContains(AVAILABLE_CHARACTERS, character) && (!characterItems.containsKey(character) || forceReplace)) {
characterItems.put(character, new ItemEditor(Material.SKULL_ITEM, 3).setTexture(texture).getItem());
return true;
}
return false;
}
public boolean removeCharacter(char character) {
if (characters.containsKey(character)) {
characters.remove(character);
if (characterItems.containsKey(character)) {
characterItems.remove(character);
return true;
}
return false;
@ -81,25 +81,25 @@ public class HeadFontType {
cached = true;
cacheTime = System.currentTimeMillis();
cacheID = Utils.randomAlphabetic(6);
cache.put(cacheID, this);
FONT_CACHE.put(cacheID, this);
return this;
}
public HashMap<Character, ItemStack> getCharacters() {
return characters;
public HashMap<Character, ItemStack> getCharacterItems() {
return characterItems;
}
public ItemStack getCharacter(char character) {
return characters.get(character);
return characterItems.get(character);
}
public void save() {
fontFile.get().set("characters", null);
if (!this.characters.isEmpty()) {
List<Character> characters = new ArrayList<>(this.characters.keySet());
if (!this.characterItems.isEmpty()) {
List<Character> characters = new ArrayList<>(this.characterItems.keySet());
Collections.sort(characters);
for (char key : characters) {
fontFile.get().set("characters." + key, new ItemEditor(this.characters.get(key)).getTexture());
fontFile.get().set("characters." + key, new ItemEditor(this.characterItems.get(key)).getTexture());
}
}
fontFile.save();

View File

@ -20,15 +20,13 @@ public class HeadWriter {
private static final BlockFace[] AXIS_SHIFTED = {BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST, BlockFace.SOUTH};
private static final BlockFace[] AXIS = {BlockFace.NORTH, BlockFace.WEST, BlockFace.SOUTH, BlockFace.EAST};
private static final HashMap<Player, String> UNDO_LIST = new HashMap<>();
private static HashMap<Player, String> undoList = new HashMap<>();
private HeadFontType fontType;
private final HeadFontType fontType;
private final String text;
private Player player;
private String text;
public HeadWriter(HeadFontType fontType, String text) {
this.fontType = fontType;
this.text = text;
@ -43,18 +41,18 @@ public class HeadWriter {
public static void undoWriting(Player player, int times, Player sendTo) {
int timesSuccessful = 0;
for (int i = 0; i < times; i++) {
if (undoList.containsKey(player)) {
if (undoList.containsKey(player)) {
String[] history = undoList.get(player).split("/#/");
if (UNDO_LIST.containsKey(player)) {
if (UNDO_LIST.containsKey(player)) {
String[] history = UNDO_LIST.get(player).split("/#/");
String[] h = history[history.length - 1].split(",");
for (String a : h) {
String[] data = a.split(":");
Bukkit.getWorld(data[2]).getBlockAt(Integer.parseInt(data[3]), Integer.parseInt(data[4]), Integer.parseInt(data[5])).setTypeIdAndData(Integer.parseInt(data[0]), Byte.parseByte(data[1]), false);
}
if (undoList.get(player).lastIndexOf("/#/") < 0) {
undoList.remove(player);
if (UNDO_LIST.get(player).lastIndexOf("/#/") < 0) {
UNDO_LIST.remove(player);
} else {
undoList.put(player, undoList.get(player).substring(0, undoList.get(player).lastIndexOf("/#/")));
UNDO_LIST.put(player, UNDO_LIST.get(player).substring(0, UNDO_LIST.get(player).lastIndexOf("/#/")));
}
timesSuccessful++;
}
@ -83,7 +81,7 @@ public class HeadWriter {
loc = loc.getBlock().getLocation().add(face.getModX(), face.getModY(), face.getModZ());
if (recHis) {
repBlock.append(undoList.containsKey(player) ? undoList.get(player) + "/#/" : "");
repBlock.append(UNDO_LIST.containsKey(player) ? UNDO_LIST.get(player) + "/#/" : "");
}
for (int i = 0; i < text.length(); i++) {
if (recHis) {
@ -100,7 +98,7 @@ public class HeadWriter {
if (recHis) {
player.sendMessage("§cUnsupported Character at collum " + (i + 1) + ": " + text.charAt(i));
} else {
CustomHeads.getInstance().getLogger().log(Level.WARNING, "Could not write Text: Unsupported Character '" + text.charAt(i) + "'");
CustomHeads.getPluginLogger().log(Level.WARNING, "Could not write Text: Unsupported Character '" + text.charAt(i) + "'");
}
}
@ -108,14 +106,14 @@ public class HeadWriter {
loc = loc.getBlock().getLocation().add(bFace.getModX(), bFace.getModY(), bFace.getModZ());
}
if (recHis) {
undoList.put(player, repBlock.toString());
if (undoList.get(player).split("/#/").length > (CustomHeads.getHeadsConfig().get().getInt("maxUndoHistory") == 0 ? 6 : CustomHeads.getHeadsConfig().get().getInt("maxUndoHistory"))) {
String[] str = undoList.get(player).split("/#/");
UNDO_LIST.put(player, repBlock.toString());
if (UNDO_LIST.get(player).split("/#/").length > (CustomHeads.getHeadsConfig().get().getInt("maxUndoHistory") == 0 ? 6 : CustomHeads.getHeadsConfig().get().getInt("maxUndoHistory"))) {
String[] str = UNDO_LIST.get(player).split("/#/");
StringBuilder undoString = new StringBuilder();
for (int i = 1; i < str.length; i++) {
undoString.append(i + 1 < str.length ? str[i] + "/#/" : str[i]);
}
undoList.put(player, undoString.toString());
UNDO_LIST.put(player, undoString.toString());
}
}
}

View File

@ -16,7 +16,6 @@ import de.likewhat.customheads.utils.CategoryEditor;
import de.likewhat.customheads.utils.ItemEditor;
import de.likewhat.customheads.utils.Utils;
import de.likewhat.customheads.utils.reflection.AnvilGUI;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
@ -220,7 +219,7 @@ public class CategoryEditorListener implements Listener {
writer.write(category.toString());
writer.flush();
} catch (Exception e) {
Bukkit.getLogger().log(Level.SEVERE, "Failed to rewrite " + category.getName(), e);
CustomHeads.getPluginLogger().log(Level.SEVERE, "Failed to rewrite " + category.getName(), e);
}
player.sendMessage("§eCEdit: §7Successfully renamed Category to §a" + newCategoryName);
}
@ -256,7 +255,7 @@ public class CategoryEditorListener implements Listener {
subCategory.setName(newCategoryName);
subCategory.setPermission(anvilClickEvent.getName().toLowerCase().replace(" ", "_"));
subCategories.set(index, subCategory);
originCategory.setSubCategories(subCategories);
// originCategory.setSubCategories(subCategories);
// Rewrite Category File
File categoryFile = CustomHeads.getCategoryManager().getSourceFile(originCategory);
@ -264,7 +263,7 @@ public class CategoryEditorListener implements Listener {
writer.write(originCategory.toString());
writer.flush();
} catch (Exception e) {
Bukkit.getLogger().log(Level.SEVERE, "Failed to rewrite " + originCategory.getName(), e);
CustomHeads.getPluginLogger().log(Level.SEVERE, "Failed to rewrite " + originCategory.getName(), e);
}
player.sendMessage("§eCedit: §7Successfully renamed Subcategory to §a" + newCategoryName);
}

View File

@ -40,12 +40,12 @@ import static de.likewhat.customheads.utils.Utils.*;
public class InventoryListener implements Listener {
private static HashMap<UUID, String> lastActiveMenu = new HashMap<>();
private static final HashMap<UUID, String> LAST_ACTIVE_MENU = new HashMap<>();
public static String getLastMenu(UUID uuid, boolean remove) {
String last = lastActiveMenu.get(uuid);
String last = LAST_ACTIVE_MENU.get(uuid);
if (remove) {
lastActiveMenu.remove(uuid);
LAST_ACTIVE_MENU.remove(uuid);
}
return last;
}
@ -193,7 +193,7 @@ public class InventoryListener implements Listener {
if (itemTags.contains("menuID")) {
menuID = itemTags.get(itemTags.indexOf("menuID") + 1).toLowerCase();
//player.sendMessage("menuID present: " + menuID);
lastActiveMenu.put(player.getUniqueId(), menuID);
LAST_ACTIVE_MENU.put(player.getUniqueId(), menuID);
}
if (itemTags.contains("blockMoving")) {
@ -298,7 +298,7 @@ public class InventoryListener implements Listener {
if (itemTags.contains("openScInv")) {
ScrollableInventory inv = ScrollableInventory.getInventoryByID(itemTags.get(itemTags.indexOf("openScInv") + 1));
List<ItemStack> characterList = new ArrayList<>();
font.getCharacters().forEach((character, customHead) -> characterList.add(CustomHeads.getTagEditor().addTags(new ItemEditor(customHead).setDisplayName("§b" + (character.equals(' ') ? "BLANK" : character)).getItem(), "fontName", font.getFontName(), "character", "" + character, "editFont", "select")));
font.getCharacterItems().forEach((character, customHead) -> characterList.add(CustomHeads.getTagEditor().addTags(new ItemEditor(customHead).setDisplayName("§b" + (character.equals(' ') ? "BLANK" : character)).getItem(), "fontName", font.getFontName(), "character", "" + character, "editFont", "select")));
characterList.sort(Comparator.comparing(itemStack -> itemStack.getItemMeta().getDisplayName()));
inv.setContent(characterList);
inv.refreshCurrentPage();
@ -337,8 +337,8 @@ public class InventoryListener implements Listener {
} else {
if (category.hasSubCategories()) {
openCategory(category, player, new String[] {"openCategory", "subCategory#>" + category.getId()});
} else if (lastActiveMenu.containsKey(player.getUniqueId())){
openCategory(category, player, new String[]{"openMenu", lastActiveMenu.get(player.getUniqueId())});
} else if (LAST_ACTIVE_MENU.containsKey(player.getUniqueId())){
openCategory(category, player, new String[]{"openMenu", LAST_ACTIVE_MENU.get(player.getUniqueId())});
} else {
player.closeInventory();
}
@ -417,7 +417,7 @@ public class InventoryListener implements Listener {
}
String mId = itemTags.get(itemTags.indexOf("openMenu") + 1).toLowerCase();
Inventory menu = CustomHeads.getLooks().getMenu(mId);
lastActiveMenu.put(player.getUniqueId(), mId);
LAST_ACTIVE_MENU.put(player.getUniqueId(), mId);
if (menu != null)
player.openInventory(menu);
}
@ -475,7 +475,7 @@ public class InventoryListener implements Listener {
event.setCancelled(true);
if (!hasPermission(player, "heads.use") || !hasPermission(player, "heads.use.more")) return;
ScrollableInventory savedHeads = new ScrollableInventory(CustomHeads.getLanguageManager().SAVED_HEADS_TITLE.replace("{PLAYER}", player.getName()), customHeadsPlayer.getSavedHeads()).setContentsClonable(true);
lastActiveMenu.put(player.getUniqueId(), menuID);
LAST_ACTIVE_MENU.put(player.getUniqueId(), menuID);
savedHeads.setBarItem(1, getBackButton("openMenu", menuID));
savedHeads.setBarItem(3, CustomHeads.getTagEditor().setTags(new ItemEditor(Material.PAPER).setDisplayName(CustomHeads.getLanguageManager().ITEMS_INFO).setLore(CustomHeads.getLanguageManager().ITEMS_INFO_LORE).getItem(), "dec", "info-item", "blockMoving"));
player.openInventory(savedHeads.getAsInventory());
@ -626,9 +626,9 @@ public class InventoryListener implements Listener {
@EventHandler
public void onEvent(InventoryCloseEvent event) {
Player player = (Player) event.getPlayer();
if(lastActiveMenu.containsKey(player)) {
if(LAST_ACTIVE_MENU.containsKey(player)) {
// player.sendMessage("Clearing Last Menu");
lastActiveMenu.remove(player);
LAST_ACTIVE_MENU.remove(player);
}
}

View File

@ -1,7 +1,6 @@
package de.likewhat.customheads.listener;
import de.likewhat.customheads.CustomHeads;
import de.likewhat.customheads.category.CategorySetup;
import de.likewhat.customheads.command.CustomHeadsCommand;
import de.likewhat.customheads.utils.Utils;
import de.likewhat.customheads.utils.updaters.SpigetResourceFetcher;
@ -9,12 +8,8 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import java.util.HashMap;
import java.util.UUID;
import static de.likewhat.customheads.utils.Utils.sendJSONMessage;
/*
@ -24,10 +19,10 @@ import static de.likewhat.customheads.utils.Utils.sendJSONMessage;
public class OtherListeners implements Listener {
public static final HashMap<UUID, CategorySetup> CACHED_CATEGORYSETUPS = new HashMap<>();
// public static final HashMap<UUID, CategorySetup> CACHED_CATEGORYSETUPS = new HashMap<>();
@EventHandler
public void fireworkbreak(BlockBreakEvent event) {
public void onFireworkBreak(BlockBreakEvent event) {
if (CustomHeadsCommand.CACHED_FIREWORKS.contains(event.getBlock().getLocation().add(.5, .5, .5))) {
event.setCancelled(true);
}
@ -48,6 +43,7 @@ public class OtherListeners implements Listener {
}
}
/*
@EventHandler
public void onAsyncChat(AsyncPlayerChatEvent event) {
Player player = event.getPlayer();
@ -56,5 +52,5 @@ public class OtherListeners implements Listener {
// Not implemented yet
}
}
*/
}

View File

@ -190,9 +190,9 @@ public class Language {
public final String ITEMS_INFO;
public final List<String> ITEMS_INFO_LORE;
public final String DEFINITION;
private Configs languageConfig;
private final Configs languageConfig;
@Getter
private String currentLanguage;
private final String currentLanguage;
public Language(String language) {
loaded = false;
@ -201,195 +201,196 @@ public class Language {
languageConfig.reload();
if (!CustomHeads.hasReducedDebug())
CustomHeads.getInstance().getServer().getConsoleSender().sendMessage(CustomHeads.chPrefix + "Loading Language from language/" + language + "/language.yml...");
CustomHeads.getInstance().getServer().getConsoleSender().sendMessage(CustomHeads.PREFIX_GENERAL + "Loading Language from language/" + language + "/language.yml...");
long timestamp = System.currentTimeMillis();
DEFINITION = ChatColor.stripColor(getFromConfig("DEFINITION"));
DEFINITION = ChatColor.stripColor(getStringFromConfig("DEFINITION"));
NO_PERMISSION = getFromConfig("NO_PERMISSION");
NO_PERMISSION = getStringFromConfig("NO_PERMISSION");
YES = ChatColor.stripColor(getFromConfig("LANG_YES"));
NO = ChatColor.stripColor(getFromConfig("LANG_NO"));
CONFIRM_NOTHINGFOUND = getFromConfig("CONFIRM_NOTHINGFOUND");
COMMAND_USAGE = getFromConfig("COMMAND_USAGE");
YES = ChatColor.stripColor(getStringFromConfig("LANG_YES"));
NO = ChatColor.stripColor(getStringFromConfig("LANG_NO"));
CONFIRM_NOTHINGFOUND = getStringFromConfig("CONFIRM_NOTHINGFOUND");
COMMAND_USAGE = getStringFromConfig("COMMAND_USAGE");
LINK = getFromConfig("LINK");
LINK = getStringFromConfig("LINK");
LANGUAGE_CHANGE_CHANGING = getFromConfig("LANGUAGE.CHANGE_CHANGING");
LANGUAGE_CHANGE_SUCCESSFUL = getFromConfig("LANGUAGE.CHANGE_SUCCESSFUL");
LANGUAGE_CHANGE_ALREADY_USED = getFromConfig("LANGUAGE.CHANGE_ALREADY_USED");
LANGUAGE_CHANGE_FAILED = getFromConfig("LANGUAGE.CHANGE_FAILED");
LANGUAGE_REDOWNLOAD_FAILED_WAIT = getFromConfig("LANGUAGE.REDOWNLOAD_FAILED_WAIT");
LANGUAGE_REDOWNLOAD_BACKING_UP = getFromConfig("LANGUAGE.REDOWNLOAD_BACKING_UP");
LANGUAGE_REDOWNLOAD_BACKUP_FAILED = getFromConfig("LANGUAGE.REDOWNLOAD_BACKUP_FAILED");
LANGUAGE_REDOWNLOAD_DOWNLOADING = getFromConfig("LANGUAGE.REDOWNLOAD_DOWNLOADING");
LANGUAGE_REDOWNLOAD_DONE = getFromConfig("LANGUAGE.REDOWNLOAD_DONE");
LANGUAGE_CHANGE_CHANGING = getStringFromConfig("LANGUAGE.CHANGE_CHANGING");
LANGUAGE_CHANGE_SUCCESSFUL = getStringFromConfig("LANGUAGE.CHANGE_SUCCESSFUL");
LANGUAGE_CHANGE_ALREADY_USED = getStringFromConfig("LANGUAGE.CHANGE_ALREADY_USED");
LANGUAGE_CHANGE_FAILED = getStringFromConfig("LANGUAGE.CHANGE_FAILED");
LANGUAGE_REDOWNLOAD_FAILED_WAIT = getStringFromConfig("LANGUAGE.REDOWNLOAD_FAILED_WAIT");
LANGUAGE_REDOWNLOAD_BACKING_UP = getStringFromConfig("LANGUAGE.REDOWNLOAD_BACKING_UP");
LANGUAGE_REDOWNLOAD_BACKUP_FAILED = getStringFromConfig("LANGUAGE.REDOWNLOAD_BACKUP_FAILED");
LANGUAGE_REDOWNLOAD_DOWNLOADING = getStringFromConfig("LANGUAGE.REDOWNLOAD_DOWNLOADING");
LANGUAGE_REDOWNLOAD_DONE = getStringFromConfig("LANGUAGE.REDOWNLOAD_DONE");
LANGUAGE_DOWNLOAD_FETCHING = getFromConfig("LANGUAGE.DOWNLOAD_FETCHING");
LANGUAGE_DOWNLOAD_FETCHFAILED = getFromConfig("LANGUAGE.DOWNLOAD_FETCHFAILED");
LANGUAGE_DOWNLOAD_SUCCESSFUL = getFromConfig("LANGUAGE.DOWNLOAD_SUCCESSFUL");
LANGUAGE_DOWNLOAD_TITLE = getFromConfig("LANGUAGE.DOWNLOAD_TITLE");
LANGUAGE_DOWNLOAD_FETCHING = getStringFromConfig("LANGUAGE.DOWNLOAD_FETCHING");
LANGUAGE_DOWNLOAD_FETCHFAILED = getStringFromConfig("LANGUAGE.DOWNLOAD_FETCHFAILED");
LANGUAGE_DOWNLOAD_SUCCESSFUL = getStringFromConfig("LANGUAGE.DOWNLOAD_SUCCESSFUL");
LANGUAGE_DOWNLOAD_TITLE = getStringFromConfig("LANGUAGE.DOWNLOAD_TITLE");
RELOAD_CONFIG = getFromConfig("RELOAD.CONFIG");
RELOAD_HISTORY = getFromConfig("RELOAD.HISTORY");
RELOAD_LANGUAGE = getFromConfig("RELOAD.LANGUAGE");
RELOAD_FAILED = getFromConfig("RELOAD.FAILED");
RELOAD_SUCCESSFUL = getFromConfig("RELOAD.SUCCESSFUL");
RELOAD_CONFIG = getStringFromConfig("RELOAD.CONFIG");
RELOAD_HISTORY = getStringFromConfig("RELOAD.HISTORY");
RELOAD_LANGUAGE = getStringFromConfig("RELOAD.LANGUAGE");
RELOAD_FAILED = getStringFromConfig("RELOAD.FAILED");
RELOAD_SUCCESSFUL = getStringFromConfig("RELOAD.SUCCESSFUL");
HELP_GET_COMMAND = getFromConfig("HELP_GET_COMMAND");
SAVED_HEADS_TITLE = getFromConfig("SAVED_HEADS_TITLE");
PUT_ON_HEAD = getFromConfig("PUT_ON_HEAD");
NO_PERMISSION_TO_VIEW = getFromConfig("NO_PERMISSION_TO_VIEW");
HELP_GET_COMMAND = getStringFromConfig("HELP_GET_COMMAND");
SAVED_HEADS_TITLE = getStringFromConfig("SAVED_HEADS_TITLE");
PUT_ON_HEAD = getStringFromConfig("PUT_ON_HEAD");
NO_PERMISSION_TO_VIEW = getListFromConfig("NO_PERMISSION_TO_VIEW");
ECONOMY_PRICE = getFromConfig("ECONOMY.PRICE");
ECONOMY_PRICE_FORMAT = getFromConfig("ECONOMY.PRICE_FORMAT");
ECONOMY_FREE = getFromConfig("ECONOMY.FREE");
ECONOMY_BOUGHT = getFromConfig("ECONOMY.BOUGHT");
ECONOMY_BUY_PROMPT = getFromConfig("ECONOMY.BUY_PROMPT");
ECONOMY_BUY_CONFIRM = getFromConfig("ECONOMY.BUY_CONFIRM");
ECONOMY_BUY_SUCCESSFUL = getFromConfig("ECONOMY.BUY_SUCCESSFUL");
ECONOMY_BUY_FAILED = getFromConfig("ECONOMY.BUY_FAILED");
ECONOMY_PRICE = getStringFromConfig("ECONOMY.PRICE");
ECONOMY_PRICE_FORMAT = getStringFromConfig("ECONOMY.PRICE_FORMAT");
ECONOMY_FREE = getStringFromConfig("ECONOMY.FREE");
ECONOMY_BOUGHT = getStringFromConfig("ECONOMY.BOUGHT");
ECONOMY_BUY_PROMPT = getStringFromConfig("ECONOMY.BUY_PROMPT");
ECONOMY_BUY_CONFIRM = getStringFromConfig("ECONOMY.BUY_CONFIRM");
ECONOMY_BUY_SUCCESSFUL = getStringFromConfig("ECONOMY.BUY_SUCCESSFUL");
ECONOMY_BUY_FAILED = getStringFromConfig("ECONOMY.BUY_FAILED");
HISTORY_DISABLED = getFromConfig("HISTORY_DISABLED");
HISTORY_INVALID_PLAYER = getFromConfig("HISTORY_INVALID_PLAYER");
HISTORY_NO_VIEW_PERMISSION = getFromConfig("HISTORY_NO_VIEW_PERMISSION");
CANNOT_PLACE_IN_BLOCK = getFromConfig("CANNOT_PLACE_IN_BLOCK");
CANNOT_PLACE_IN_AIR = getFromConfig("CANNOT_PLACE_IN_AIR");
ALREADY_IN_USE = getFromConfig("ALREADY_IN_USE");
STARTING = getFromConfig("STARTING");
INVALID_INPUT = getFromConfig("INVALID_INPUT");
CHANGE_SEARCH_STRING = getFromConfig("CHANGE_SEARCH_STRING");
SEARCH_LORE = getFromConfig("SEARCH_LORE");
TO_LONG_INPUT = getFromConfig("TO_LONG_INPUT");
SEARCHING = getFromConfig("SEARCHING");
CYCLE_ARRANGEMENT_PREFIX = getFromConfig("CYCLE_ARRANGEMENT.PREFIX");
CYCLE_ARRANGEMENT_DEFAULT = getFromConfig("CYCLE_ARRANGEMENT.DEFAULT");
CYCLE_ARRANGEMENT_ALPHABETICAL = getFromConfig("CYCLE_ARRANGEMENT.ALPHABETICAL");
CYCLE_ARRANGEMENT_COLOR = getFromConfig("CYCLE_ARRANGEMENT.COLOR");
SEARCH_TITLE = getFromConfig("SEARCH_TITLE");
LOADING = getFromConfig("LOADING");
NO_RESULTS = getFromConfig("NO_RESULTS");
NO_RESULTS_TRY_AGAIN = getFromConfig("NO_RESULTS_TRY_AGAIN");
PAGE_GENERAL_PREFIX = getFromConfig("PAGE_GENERAL_PREFIX");
HISTORY_DISABLED = getStringFromConfig("HISTORY_DISABLED");
HISTORY_INVALID_PLAYER = getStringFromConfig("HISTORY_INVALID_PLAYER");
HISTORY_NO_VIEW_PERMISSION = getStringFromConfig("HISTORY_NO_VIEW_PERMISSION");
CANNOT_PLACE_IN_BLOCK = getStringFromConfig("CANNOT_PLACE_IN_BLOCK");
CANNOT_PLACE_IN_AIR = getStringFromConfig("CANNOT_PLACE_IN_AIR");
ALREADY_IN_USE = getStringFromConfig("ALREADY_IN_USE");
STARTING = getStringFromConfig("STARTING");
INVALID_INPUT = getStringFromConfig("INVALID_INPUT");
CHANGE_SEARCH_STRING = getStringFromConfig("CHANGE_SEARCH_STRING");
SEARCH_LORE = getListFromConfig("SEARCH_LORE");
TO_LONG_INPUT = getStringFromConfig("TO_LONG_INPUT");
SEARCHING = getStringFromConfig("SEARCHING");
CYCLE_ARRANGEMENT_PREFIX = getStringFromConfig("CYCLE_ARRANGEMENT.PREFIX");
CYCLE_ARRANGEMENT_DEFAULT = getStringFromConfig("CYCLE_ARRANGEMENT.DEFAULT");
CYCLE_ARRANGEMENT_ALPHABETICAL = getStringFromConfig("CYCLE_ARRANGEMENT.ALPHABETICAL");
CYCLE_ARRANGEMENT_COLOR = getStringFromConfig("CYCLE_ARRANGEMENT.COLOR");
SEARCH_TITLE = getStringFromConfig("SEARCH_TITLE");
LOADING = getStringFromConfig("LOADING");
NO_RESULTS = getStringFromConfig("NO_RESULTS");
NO_RESULTS_TRY_AGAIN = getStringFromConfig("NO_RESULTS_TRY_AGAIN");
PAGE_GENERAL_PREFIX = getStringFromConfig("PAGE_GENERAL_PREFIX");
CATEGORIES_BASECOMMAND_HEADER = getFromConfig("CATEGORIES.BASE_COMMAND.HEADER");
CATEGORIES_BASECOMMAND_HOVERINFO_CATEGORY = getFromConfig("CATEGORIES.BASE_COMMAND.HOVERINFO_CATEGORY");
CATEGORIES_BASECOMMAND_HOVERINFO_SUBCATEGORY = getFromConfig("CATEGORIES.BASE_COMMAND.HOVERINFO_SUBCATEGORY");
CATEGORIES_BASECOMMAND_HEADER = getStringFromConfig("CATEGORIES.BASE_COMMAND.HEADER");
CATEGORIES_BASECOMMAND_HOVERINFO_CATEGORY = getListFromConfig("CATEGORIES.BASE_COMMAND.HOVERINFO_CATEGORY");
CATEGORIES_BASECOMMAND_HOVERINFO_SUBCATEGORY = getListFromConfig("CATEGORIES.BASE_COMMAND.HOVERINFO_SUBCATEGORY");
CATEGORIES_REMOVE_NOTFOUND = getFromConfig("CATEGORIES.REMOVE.NOTFOUND");
CATEGORIES_REMOVE_INUSE = getFromConfig("CATEGORIES.REMOVE.INUSE");
CATEGORIES_REMOVE_FAILED = getFromConfig("CATEGORIES.REMOVE.FAILED");
CATEGORIES_REMOVE_SUCCESSFUL = getFromConfig("CATEGORIES.REMOVE.SUCCESSFUL");
CATEGORIES_REMOVE_NOTFOUND = getStringFromConfig("CATEGORIES.REMOVE.NOTFOUND");
CATEGORIES_REMOVE_INUSE = getStringFromConfig("CATEGORIES.REMOVE.INUSE");
CATEGORIES_REMOVE_FAILED = getStringFromConfig("CATEGORIES.REMOVE.FAILED");
CATEGORIES_REMOVE_SUCCESSFUL = getStringFromConfig("CATEGORIES.REMOVE.SUCCESSFUL");
CATEGORIES_DELETE_CATEGORY_NOTFOUND = getFromConfig("CATEGORIES.DELETE.CATEGORY.NOTFOUND");
CATEGORIES_DELETE_CATEGORY_INUSE = getFromConfig("CATEGORIES.DELETE.CATEGORY.INUSE");
CATEGORIES_DELETE_CATEGORY_CONFIRM = getFromConfig("CATEGORIES.DELETE.CATEGORY.CONFIRM");
CATEGORIES_DELETE_CATEGORY_FAILED = getFromConfig("CATEGORIES.DELETE.CATEGORY.FAILED");
CATEGORIES_DELETE_CATEGORY_SUCCESSFUL = getFromConfig("CATEGORIES.DELETE.CATEGORY.SUCCESSFUL");
CATEGORIES_DELETE_CATEGORY_NOTFOUND = getStringFromConfig("CATEGORIES.DELETE.CATEGORY.NOTFOUND");
CATEGORIES_DELETE_CATEGORY_INUSE = getStringFromConfig("CATEGORIES.DELETE.CATEGORY.INUSE");
CATEGORIES_DELETE_CATEGORY_CONFIRM = getStringFromConfig("CATEGORIES.DELETE.CATEGORY.CONFIRM");
CATEGORIES_DELETE_CATEGORY_FAILED = getStringFromConfig("CATEGORIES.DELETE.CATEGORY.FAILED");
CATEGORIES_DELETE_CATEGORY_SUCCESSFUL = getStringFromConfig("CATEGORIES.DELETE.CATEGORY.SUCCESSFUL");
CATEGORIES_DELETE_SUBCATEGORY_NOTFOUND = getFromConfig("CATEGORIES.DELETE.SUBCATEGORY.NOTFOUND");
CATEGORIES_DELETE_SUBCATEGORY_INUSE = getFromConfig("CATEGORIES.DELETE.SUBCATEGORY.INUSE");
CATEGORIES_DELETE_SUBCATEGORY_CONFIRM = getFromConfig("CATEGORIES.DELETE.SUBCATEGORY.CONFIRM");
CATEGORIES_DELETE_SUBCATEGORY_FAILED = getFromConfig("CATEGORIES.DELETE.SUBCATEGORY.FAILED");
CATEGORIES_DELETE_SUBCATEGORY_SUCCESSFUL = getFromConfig("CATEGORIES.DELETE.SUBCATEGORY.SUCCESSFUL");
CATEGORIES_DELETE_SUBCATEGORY_NOTFOUND = getStringFromConfig("CATEGORIES.DELETE.SUBCATEGORY.NOTFOUND");
CATEGORIES_DELETE_SUBCATEGORY_INUSE = getStringFromConfig("CATEGORIES.DELETE.SUBCATEGORY.INUSE");
CATEGORIES_DELETE_SUBCATEGORY_CONFIRM = getStringFromConfig("CATEGORIES.DELETE.SUBCATEGORY.CONFIRM");
CATEGORIES_DELETE_SUBCATEGORY_FAILED = getStringFromConfig("CATEGORIES.DELETE.SUBCATEGORY.FAILED");
CATEGORIES_DELETE_SUBCATEGORY_SUCCESSFUL = getStringFromConfig("CATEGORIES.DELETE.SUBCATEGORY.SUCCESSFUL");
CATEGORIES_IMPORT_NOCATEGORYFOLDER = getFromConfig("CATEGORIES.IMPORT.NOCATEGORYFOLDER");
CATEGORIES_IMPORT_BASECOMMAND_NOFILES = getFromConfig("CATEGORIES.IMPORT.BASE_COMMAND.NOFILES");
CATEGORIES_IMPORT_BASECOMMAND_LIST = getFromConfig("CATEGORIES.IMPORT.BASE_COMMAND.LIST");
CATEGORIES_IMPORT_BASECOMMAND_LISTFORMAT = getFromConfig("CATEGORIES.IMPORT.BASE_COMMAND.LIST_FORMAT");
CATEGORIES_IMPORT_BASECOMMAND_CLICKTOIMPORT = getFromConfig("CATEGORIES.IMPORT.BASE_COMMAND.CLICKTOIMPORT");
CATEGORIES_IMPORT_SUCCESSFUL = getFromConfig("CATEGORIES.IMPORT.SUCCESSFUL");
CATEGORIES_IMPORT_DUBLICATE_CATEGORY = getFromConfig("CATEGORIES.IMPORT.DUBLICATE_CATEGORY");
CATEGORIES_IMPORT_DUBLICATE_SUBCATEGORY = getFromConfig("CATEGORIES.IMPORT.DUBLICATE_SUBCATEGORY");
CATEGORIES_IMPORT_ERROR = getFromConfig("CATEGORIES.IMPORT.ERROR");
CATEGORIES_IMPORT_INVALIDFILE = getFromConfig("CATEGORIES.IMPORT.INVALID_FILE");
CATEGORIES_IMPORT_FILENOTFOUND = getFromConfig("CATEGORIES.IMPORT.FILENOTFOUND");
CATEGORIES_IMPORT_NOCATEGORYFOLDER = getStringFromConfig("CATEGORIES.IMPORT.NOCATEGORYFOLDER");
CATEGORIES_IMPORT_BASECOMMAND_NOFILES = getStringFromConfig("CATEGORIES.IMPORT.BASE_COMMAND.NOFILES");
CATEGORIES_IMPORT_BASECOMMAND_LIST = getStringFromConfig("CATEGORIES.IMPORT.BASE_COMMAND.LIST");
CATEGORIES_IMPORT_BASECOMMAND_LISTFORMAT = getStringFromConfig("CATEGORIES.IMPORT.BASE_COMMAND.LIST_FORMAT");
CATEGORIES_IMPORT_BASECOMMAND_CLICKTOIMPORT = getStringFromConfig("CATEGORIES.IMPORT.BASE_COMMAND.CLICKTOIMPORT");
CATEGORIES_IMPORT_SUCCESSFUL = getStringFromConfig("CATEGORIES.IMPORT.SUCCESSFUL");
CATEGORIES_IMPORT_DUBLICATE_CATEGORY = getStringFromConfig("CATEGORIES.IMPORT.DUBLICATE_CATEGORY");
CATEGORIES_IMPORT_DUBLICATE_SUBCATEGORY = getStringFromConfig("CATEGORIES.IMPORT.DUBLICATE_SUBCATEGORY");
CATEGORIES_IMPORT_ERROR = getStringFromConfig("CATEGORIES.IMPORT.ERROR");
CATEGORIES_IMPORT_INVALIDFILE = getStringFromConfig("CATEGORIES.IMPORT.INVALID_FILE");
CATEGORIES_IMPORT_FILENOTFOUND = getStringFromConfig("CATEGORIES.IMPORT.FILENOTFOUND");
UNDO_INVALID_INPUT = getFromConfig("UNDO_INVALID_INPUT");
UNDO_SUCCESSFUL = getFromConfig("UNDO_SUCCESSFUL");
UNDO_NOTHING_LEFT = getFromConfig("UNDO_NOTHING_LEFT");
GET_HEAD_NAME = getFromConfig("GET_HEAD_NAME");
GET_INVALID = getFromConfig("GET_INVALID");
SAVE_GET_TEXTURE = getFromConfig("SAVE_GET_TEXTURE");
SAVE_OWN_SUCCESSFUL = getFromConfig("SAVE_OWN_SUCCESSFUL");
SAVE_OWN_FAILED = getFromConfig("SAVE_OWN_FAILED");
SAVE_UNAVAILABLE = getFromConfig("SAVE_UNAVIABLE");
SAVE_NOT_CUSTOM_TEXTURE = getFromConfig("SAVE_NOT_CUSTOM_TEXTURE");
SAVE_SUCCESSFUL = getFromConfig("SAVE_SUCCESSFUL");
SAVE_ALREADY_EXIST = getFromConfig("SAVE_ALREADY_EXIST");
SAVE_NOT_SKULL = getFromConfig("SAVE_NOT_SKULL");
REMOVE_SUCCESSFUL = getFromConfig("REMOVE_SUCCESSFUL");
REMOVE_FAILED = getFromConfig("REMOVE_FAILED");
REMOVE_CONFIRMATION = getFromConfig("REMOVE_CONFIRMATION");
UNDO_INVALID_INPUT = getStringFromConfig("UNDO_INVALID_INPUT");
UNDO_SUCCESSFUL = getStringFromConfig("UNDO_SUCCESSFUL");
UNDO_NOTHING_LEFT = getStringFromConfig("UNDO_NOTHING_LEFT");
GET_HEAD_NAME = getStringFromConfig("GET_HEAD_NAME");
GET_INVALID = getStringFromConfig("GET_INVALID");
SAVE_GET_TEXTURE = getStringFromConfig("SAVE_GET_TEXTURE");
SAVE_OWN_SUCCESSFUL = getStringFromConfig("SAVE_OWN_SUCCESSFUL");
SAVE_OWN_FAILED = getStringFromConfig("SAVE_OWN_FAILED");
SAVE_UNAVAILABLE = getStringFromConfig("SAVE_UNAVIABLE");
SAVE_NOT_CUSTOM_TEXTURE = getStringFromConfig("SAVE_NOT_CUSTOM_TEXTURE");
SAVE_SUCCESSFUL = getStringFromConfig("SAVE_SUCCESSFUL");
SAVE_ALREADY_EXIST = getStringFromConfig("SAVE_ALREADY_EXIST");
SAVE_NOT_SKULL = getStringFromConfig("SAVE_NOT_SKULL");
REMOVE_SUCCESSFUL = getStringFromConfig("REMOVE_SUCCESSFUL");
REMOVE_FAILED = getStringFromConfig("REMOVE_FAILED");
REMOVE_CONFIRMATION = getStringFromConfig("REMOVE_CONFIRMATION");
WRITE_NOFONT = getFromConfig("WRITE_NOFONT");
WRITE_TO_LONG = getFromConfig("WRITE_TO_LONG");
WRITE_WRITING = getFromConfig("WRITE_WRITING");
WRITE_NOFONT = getStringFromConfig("WRITE_NOFONT");
WRITE_TO_LONG = getStringFromConfig("WRITE_TO_LONG");
WRITE_WRITING = getStringFromConfig("WRITE_WRITING");
FONTS_GENERAL_NOTFOUND = getFromConfig("FONTS.GENERAL_NOTFOUND");
FONTS_CREATE_ALREADYEXISTS = getFromConfig("FONTS.CREATE_ALREADYEXISTS");
FONTS_CREATE_SUCCESSFUL = getFromConfig("FONTS.CREATE_SUCCESSFUL");
FONTS_REMOVE_SUCCESSFUL = getFromConfig("FONTS.REMOVE_SUCCESSFUL");
FONTS_REMOVE_FAILED = getFromConfig("FONTS.REMOVE_FAILED");
FONTS_NOFONTS = getFromConfig("FONTS.NOFONTS");
FONTS_LIST_HEADER = getFromConfig("FONTS.LIST_HEADER");
FONTS_LIST = getFromConfig("FONTS.LIST");
FONTS_GENERAL_NOTFOUND = getStringFromConfig("FONTS.GENERAL_NOTFOUND");
FONTS_CREATE_ALREADYEXISTS = getStringFromConfig("FONTS.CREATE_ALREADYEXISTS");
FONTS_CREATE_SUCCESSFUL = getStringFromConfig("FONTS.CREATE_SUCCESSFUL");
FONTS_REMOVE_SUCCESSFUL = getStringFromConfig("FONTS.REMOVE_SUCCESSFUL");
FONTS_REMOVE_FAILED = getStringFromConfig("FONTS.REMOVE_FAILED");
FONTS_NOFONTS = getStringFromConfig("FONTS.NOFONTS");
FONTS_LIST_HEADER = getStringFromConfig("FONTS.LIST_HEADER");
FONTS_LIST = getStringFromConfig("FONTS.LIST");
FONTS_EDIT_TITLE = getFromConfig("FONTS.EDIT_TITLE");
FONTS_EDIT_ADDCHARACTER = getFromConfig("FONTS.EDIT_ADDCHARACTER");
FONTS_EDIT_REMOVECHARACTER = getFromConfig("FONTS.EDIT_REMOVECHARACTER");
FONTS_EDIT_REMOVECHARACTER_INFO = getFromConfig("FONTS.EDIT_REMOVECHARACTER_INFO");
FONTS_EDIT_ADDCHARACTER_SUCCESSFUL = getFromConfig("FONTS.EDIT_ADDCHARACTER_SUCCESSFUL");
FONTS_EDIT_ADDCHARACTER_FAILED = getFromConfig("FONTS.EDIT_ADDCHARACTER_FAILED");
FONTS_EDIT_SELECTED = getFromConfig("FONTS.EDIT_SELECTED");
FONTS_EDIT_REMOVECHARCATER_CONFIRM = getFromConfig("FONTS.EDIT_REMOVECHARCATER_CONFIRM");
FONTS_EDIT_REMOVECHARCATER_PREINFO = getFromConfig("FONTS.EDIT_REMOVECHARCATER_PREINFO");
FONTS_EDIT_REMOVECHARCATER_FAILED = getFromConfig("FONTS.EDIT_REMOVECHARCATER_FAILED");
FONTS_EDIT_REMOVECHARCATER_SUCCESSFUL = getFromConfig("FONTS.EDIT_REMOVECHARCATER_SUCCESSFUL");
FONTS_EDIT_ADDCHARACTER_TITLE = getFromConfig("FONTS.EDIT_ADDCHARACTER_TITLE");
FONTS_EDIT_ADD_TOGGLE = getFromConfig("FONTS.EDIT_ADD_DROPPER_TOGGLE");
FONTS_EDIT_ADD_DROPPER_NAME = getFromConfig("FONTS.EDIT_ADD_DROPPER_NAME");
FONTS_EDIT_ADD_DROPPER_LORE = getFromConfig("FONTS.EDIT_ADD_DROPPER_LORE");
FONTS_EDIT_SAVENEXIT = getFromConfig("FONTS.EDIT_SAVENEXIT");
FONTS_EDIT_SAVE_SUCCESSFUL = getFromConfig("FONTS.EDIT_SAVE_SUCCESSFUL");
FONTS_EDIT_TITLE = getStringFromConfig("FONTS.EDIT_TITLE");
FONTS_EDIT_ADDCHARACTER = getStringFromConfig("FONTS.EDIT_ADDCHARACTER");
FONTS_EDIT_REMOVECHARACTER = getStringFromConfig("FONTS.EDIT_REMOVECHARACTER");
FONTS_EDIT_REMOVECHARACTER_INFO = getListFromConfig("FONTS.EDIT_REMOVECHARACTER_INFO");
FONTS_EDIT_ADDCHARACTER_SUCCESSFUL = getStringFromConfig("FONTS.EDIT_ADDCHARACTER_SUCCESSFUL");
FONTS_EDIT_ADDCHARACTER_FAILED = getStringFromConfig("FONTS.EDIT_ADDCHARACTER_FAILED");
FONTS_EDIT_SELECTED = getStringFromConfig("FONTS.EDIT_SELECTED");
FONTS_EDIT_REMOVECHARCATER_CONFIRM = getStringFromConfig("FONTS.EDIT_REMOVECHARCATER_CONFIRM");
FONTS_EDIT_REMOVECHARCATER_PREINFO = getStringFromConfig("FONTS.EDIT_REMOVECHARCATER_PREINFO");
FONTS_EDIT_REMOVECHARCATER_FAILED = getStringFromConfig("FONTS.EDIT_REMOVECHARCATER_FAILED");
FONTS_EDIT_REMOVECHARCATER_SUCCESSFUL = getStringFromConfig("FONTS.EDIT_REMOVECHARCATER_SUCCESSFUL");
FONTS_EDIT_ADDCHARACTER_TITLE = getStringFromConfig("FONTS.EDIT_ADDCHARACTER_TITLE");
FONTS_EDIT_ADD_TOGGLE = getStringFromConfig("FONTS.EDIT_ADD_DROPPER_TOGGLE");
FONTS_EDIT_ADD_DROPPER_NAME = getStringFromConfig("FONTS.EDIT_ADD_DROPPER_NAME");
FONTS_EDIT_ADD_DROPPER_LORE = getListFromConfig("FONTS.EDIT_ADD_DROPPER_LORE");
FONTS_EDIT_SAVENEXIT = getStringFromConfig("FONTS.EDIT_SAVENEXIT");
FONTS_EDIT_SAVE_SUCCESSFUL = getStringFromConfig("FONTS.EDIT_SAVE_SUCCESSFUL");
BACK_GENERAL = getFromConfig("BACK_GENERAL");
BACK_TO_PREVIOUS = getFromConfig("BACK_TO_PREVIOUS");
NEXT_PAGE = getFromConfig("NEXT_PAGE");
PREVIOUS_PAGE = getFromConfig("PREVIOUS_PAGE");
HISTORY_INV_TITLE = getFromConfig("HISTORY_INV_TITLE");
HISTORY_SEARCHHISTORY_ACTIVE = getFromConfig("HISTORY_SEARCHHISTORY_ACTIVE");
HISTORY_SEARCHHISTORY = getFromConfig("HISTORY_SEARCHHISTORY");
HISTORY_GETHISTORY_ACTIVE = getFromConfig("HISTORY_GETHISTORY_ACTIVE");
HISTORY_GETHISTORY = getFromConfig("HISTORY_GETHISTORY");
HISTORY_NO_HISTORY_LORE = getFromConfig("HISTORY_NO_HISTORY_LORE");
HISTORY_SEARCHHISTORY_LORE = getFromConfig("HISTORY_SEARCHHISTORY_LORE");
HISTORY_GET_LORE = getFromConfig("HISTORY_GET_LORE");
ITEMS_YOUR_HEAD = getFromConfig("ITEM_NAMES.YOUR_HEAD");
ITEMS_COLLECTION = getFromConfig("ITEM_NAMES.COLLECTION");
ITEMS_HELP = getFromConfig("ITEM_NAMES.HELP");
ITEMS_HELP_LORE = getFromConfig("ITEM_NAMES.HELP_LORE");
ITEMS_SEARCH = getFromConfig("ITEM_NAMES.SEARCH");
ITEMS_SEARCH_LORE = getFromConfig("ITEM_NAMES.SEARCH_LORE");
ITEMS_FIND_MORE = getFromConfig("ITEM_NAMES.FIND_MORE");
ITEMS_FIND_MORE_LORE = getFromConfig("ITEM_NAMES.FIND_MORE_LORE");
ITEMS_INFO = getFromConfig("ITEM_NAMES.INFO");
ITEMS_INFO_LORE = getFromConfig("ITEM_NAMES.INFO_LORE");
LOCKED = ChatColor.stripColor(getFromConfig("LOCKED"));
BACK_GENERAL = getStringFromConfig("BACK_GENERAL");
BACK_TO_PREVIOUS = getStringFromConfig("BACK_TO_PREVIOUS");
NEXT_PAGE = getStringFromConfig("NEXT_PAGE");
PREVIOUS_PAGE = getStringFromConfig("PREVIOUS_PAGE");
HISTORY_INV_TITLE = getStringFromConfig("HISTORY_INV_TITLE");
HISTORY_SEARCHHISTORY_ACTIVE = getStringFromConfig("HISTORY_SEARCHHISTORY_ACTIVE");
HISTORY_SEARCHHISTORY = getStringFromConfig("HISTORY_SEARCHHISTORY");
HISTORY_GETHISTORY_ACTIVE = getStringFromConfig("HISTORY_GETHISTORY_ACTIVE");
HISTORY_GETHISTORY = getStringFromConfig("HISTORY_GETHISTORY");
HISTORY_NO_HISTORY_LORE = getListFromConfig("HISTORY_NO_HISTORY_LORE");
HISTORY_SEARCHHISTORY_LORE = getListFromConfig("HISTORY_SEARCHHISTORY_LORE");
HISTORY_GET_LORE = getListFromConfig("HISTORY_GET_LORE");
ITEMS_YOUR_HEAD = getStringFromConfig("ITEM_NAMES.YOUR_HEAD");
ITEMS_COLLECTION = getStringFromConfig("ITEM_NAMES.COLLECTION");
ITEMS_HELP = getStringFromConfig("ITEM_NAMES.HELP");
ITEMS_HELP_LORE = getListFromConfig("ITEM_NAMES.HELP_LORE");
ITEMS_SEARCH = getStringFromConfig("ITEM_NAMES.SEARCH");
ITEMS_SEARCH_LORE = getListFromConfig("ITEM_NAMES.SEARCH_LORE");
ITEMS_FIND_MORE = getStringFromConfig("ITEM_NAMES.FIND_MORE");
ITEMS_FIND_MORE_LORE = getListFromConfig("ITEM_NAMES.FIND_MORE_LORE");
ITEMS_INFO = getStringFromConfig("ITEM_NAMES.INFO");
ITEMS_INFO_LORE = getListFromConfig("ITEM_NAMES.INFO_LORE");
LOCKED = ChatColor.stripColor(getStringFromConfig("LOCKED"));
if (!CustomHeads.hasReducedDebug())
CustomHeads.getInstance().getServer().getConsoleSender().sendMessage(CustomHeads.chPrefix + "Successfully loaded Language from language/" + language + "/language.yml in " + (System.currentTimeMillis() - timestamp) + "ms");
CustomHeads.getInstance().getServer().getConsoleSender().sendMessage(CustomHeads.PREFIX_GENERAL + "Successfully loaded Language from language/" + language + "/language.yml in " + (System.currentTimeMillis() - timestamp) + "ms");
loaded = true;
}
private <Type> Type getFromConfig(String path) {
private String getStringFromConfig(String path) {
if (!languageConfig.get().contains(path))
throw new NullPointerException("Error getting " + path + " from language/" + currentLanguage + "/language.yml. If this Error keeps occurring please try to delete the Language Folder");
if (languageConfig.get().get(path) instanceof List) {
return (Type) format(languageConfig.get().getStringList(path));
} else if (languageConfig.get().get(path) instanceof String) {
return (Type) format(languageConfig.get().getString(path));
}
return null;
return format(languageConfig.get().getString(path));
}
private List<String> getListFromConfig(String path) {
if (!languageConfig.get().contains(path))
throw new NullPointerException("Error getting " + path + " from language/" + currentLanguage + "/language.yml. If this Error keeps occurring please try to delete the Language Folder");
return format(languageConfig.get().getStringList(path));
}
}

View File

@ -36,19 +36,19 @@ public class Looks {
private static boolean loaded = false;
public HashMap<Integer, Inventory> subCategoryLooks = new HashMap<>();
private HashMap<String, Inventory> createdMenus = new HashMap<>();
private HashMap<String, String> createdMenuTitles = new HashMap<>();
private HashMap<String, String[]> menuInfo = new HashMap<>();
private HashMap<String, ItemStack> items = new HashMap<>();
private final HashMap<String, Inventory> createdMenus = new HashMap<>();
private final HashMap<String, String> createdMenuTitles = new HashMap<>();
private final HashMap<String, String[]> menuInfo = new HashMap<>();
private final HashMap<String, ItemStack> items = new HashMap<>();
private List<SubCategory> usedSubCategories = new ArrayList<>();
private List<Category> usedCategories = new ArrayList<>();
private final List<SubCategory> usedSubCategories = new ArrayList<>();
private final List<Category> usedCategories = new ArrayList<>();
public Looks(String language) {
loaded = false;
if (!CustomHeads.hasReducedDebug())
CustomHeads.getInstance().getServer().getConsoleSender().sendMessage(CustomHeads.chPrefix + "Loading Looks from language/" + language + "/settings.json");
CustomHeads.getInstance().getServer().getConsoleSender().sendMessage(CustomHeads.PREFIX_GENERAL + "Loading Looks from language/" + language + "/settings.json");
long timestamp = System.currentTimeMillis();
JsonFile jsf = new JsonFile("language/" + language + "/settings.json");
@ -124,7 +124,7 @@ public class Looks {
for (JsonElement menuElement : menus) {
JsonObject menuJson = menuElement.getAsJsonObject();
if (createdMenus.containsKey(menuJson.get("id").getAsString())) {
Bukkit.getLogger().info(CustomHeads.chWarning + "Duplicate Menu ID: " + menuJson.get("id").getAsString() + ". Skipping...");
CustomHeads.getPluginLogger().info(CustomHeads.PREFIX_WARNING + "Duplicate Menu ID: " + menuJson.get("id").getAsString() + ". Skipping...");
continue;
}
Inventory menu = Bukkit.createInventory(null, menuJson.get("size").getAsInt(), format(menuJson.get("title").getAsString()));
@ -185,10 +185,10 @@ public class Looks {
}
if (!CustomHeads.hasReducedDebug())
CustomHeads.getInstance().getServer().getConsoleSender().sendMessage(CustomHeads.chPrefix + "Successfully loaded Looks from language/" + language + "/settings.json in " + (System.currentTimeMillis() - timestamp) + "ms");
CustomHeads.getInstance().getServer().getConsoleSender().sendMessage(CustomHeads.PREFIX_GENERAL + "Successfully loaded Looks from language/" + language + "/settings.json in " + (System.currentTimeMillis() - timestamp) + "ms");
loaded = true;
} catch (Exception e) {
CustomHeads.getInstance().getLogger().log(Level.WARNING, "Something went wrong while loading Looks from Settings File " + language + "/settings.json", e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Something went wrong while loading Looks from Settings File " + language + "/settings.json", e);
}
}

View File

@ -34,9 +34,9 @@ import java.util.logging.Level;
public class APIHandler implements CustomHeadsAPI {
private static Class<?> tileEntitySkullClass, blockPositionClass;
private static final Class<?> tileEntitySkullClass, blockPositionClass;
private static Constructor<?> blockPositionConstructor;
private FireworkEffect.Type[] fxTypes = {FireworkEffect.Type.BALL, FireworkEffect.Type.BALL_LARGE, FireworkEffect.Type.BURST, FireworkEffect.Type.STAR};
private static final FireworkEffect.Type[] FX_TYPES = {FireworkEffect.Type.BALL, FireworkEffect.Type.BALL_LARGE, FireworkEffect.Type.BURST, FireworkEffect.Type.STAR};
static {
tileEntitySkullClass = ReflectionUtils.getMCServerClassByName("TileEntitySkull", "world.level.block.entity");
@ -62,7 +62,7 @@ public class APIHandler implements CustomHeadsAPI {
Object list = textures.getClass().getMethod("get", int.class).invoke(textures, 0);
return list.getClass().getMethod("getString", String.class).invoke(list, "Value").toString();
} catch (Exception e) {
Bukkit.getLogger().log(Level.WARNING, "Something went wrong while getting the Texture of an Skull", e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Something went wrong while getting the Texture of an Skull", e);
}
return null;
}
@ -79,13 +79,13 @@ public class APIHandler implements CustomHeadsAPI {
Object nmsWorld = block.getWorld().getClass().getMethod("getHandle").invoke(block.getWorld());
return Utils.getTextureFromProfile((GameProfile) tileEntitySkullClass.getMethod("getGameProfile").invoke(tileEntitySkullClass.cast(nmsWorld.getClass().getMethod("getTileEntity", blockPositionClass).invoke(nmsWorld, blockPositionClass.getConstructor(int.class, int.class, int.class).newInstance(block.getX(), block.getY(), block.getZ())))));
} catch (Exception e) {
CustomHeads.getInstance().getLogger().log(Level.WARNING, "Error getting Texture from Skull", e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Error getting Texture from Skull", e);
}
return null;
}
public ItemStack getAlphabetHead(String character, HeadFontType font) {
if (!font.getCharacters().containsKey(character.charAt(0)))
if (!font.getCharacterItems().containsKey(character.charAt(0)))
throw new UnsupportedOperationException("Unsupported Character: '" + character.charAt(0) + "'");
return font.getCharacter(character.charAt(0));
}
@ -112,7 +112,7 @@ public void setSkull(Block block, String texture, BlockFace blockFace) {
skull.setRawData((byte) 1);
break;
default:
Utils.logOnce(Level.WARNING, "Falling back to newest Method since the current Version hasn't been tested yet... (This may not work so here goes)");
LoggingUtils.logOnce(Level.WARNING, "Falling back to newest Method since the current Version hasn't been tested yet... (This may not work so here goes)");
case 13:
case 14:
case 15:
@ -147,7 +147,7 @@ public void setSkull(Block block, String texture, BlockFace blockFace) {
skull.update();
setSkullTexture(block, texture);
} catch (Exception e) {
CustomHeads.getInstance().getLogger().log(Level.WARNING, "Error placing Skull", e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Error placing Skull", e);
}
}
@ -157,7 +157,7 @@ public void setSkull(Block block, String texture, BlockFace blockFace) {
Object craftSkull = tileEntitySkullClass.cast(nmsWorld.getClass().getMethod("getTileEntity", blockPositionClass).invoke(nmsWorld, blockPositionConstructor.newInstance(block.getX(), block.getY(), block.getZ())));
tileEntitySkullClass.getMethod("setGameProfile", GameProfile.class).invoke(craftSkull, GameProfileBuilder.createProfileWithTexture(texture));
} catch (Exception e) {
CustomHeads.getInstance().getLogger().log(Level.WARNING, "Failed to set Skull Texture", e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to set Skull Texture", e);
}
}
@ -190,7 +190,7 @@ public void setSkull(Block block, String texture, BlockFace blockFace) {
Firework f = (Firework) location.getWorld().spawnEntity(location, EntityType.FIREWORK);
FireworkMeta fm = f.getFireworkMeta();
FireworkEffect.Builder fx = FireworkEffect.builder();
fx.flicker(random.nextBoolean()).trail(random.nextBoolean()).with(fxTypes[random.nextInt(fxTypes.length)]);
fx.flicker(random.nextBoolean()).trail(random.nextBoolean()).with(FX_TYPES[random.nextInt(FX_TYPES.length)]);
int c = random.nextInt(2) + 2;
for (int i = 0; i < c; i++) {
fx.withColor(Color.fromRGB(random.nextInt(200) + 50, random.nextInt(200) + 50, random.nextInt(200) + 50));

View File

@ -4,6 +4,8 @@ import de.likewhat.customheads.CustomHeads;
import de.likewhat.customheads.api.CustomHeadsPlayer;
import de.likewhat.customheads.category.Category;
import de.likewhat.customheads.category.CustomHead;
import de.likewhat.customheads.utils.reflection.helpers.Version;
import lombok.Getter;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
@ -22,12 +24,13 @@ import java.util.stream.Collectors;
public class CHSearchQuery {
private List<String> badVersions = Arrays.asList("v1_8_R1", "v1_8_R2", "v1_8_R3");
private List<CustomHead> results;
private static final List<String> badVersions = Arrays.asList("v1_8_R1", "v1_8_R2", "v1_8_R3");
private final List<CustomHead> results;
private boolean recordHistory = true;
private String search;
@Getter
private final String search;
public CHSearchQuery(String search) {
this.search = search;
@ -58,7 +61,7 @@ public class CHSearchQuery {
customHeadsPlayer.getSearchHistory().addEntry(search);
String title = CustomHeads.getLanguageManager().SEARCH_TITLE.replace("{RESULTS}", "" + results.size());
title = badVersions.contains(CustomHeads.version) ? title.contains("{short}") ? title.substring(0, title.lastIndexOf("{short}") >= 32 ? 29 : title.lastIndexOf("{short}")) + "..." : title.substring(0, title.length() >= 32 ? 29 : title.length()) + "..." : title.replace("{short}", "");
title = badVersions.contains(Version.getRawVersion()) ? title.contains("{short}") ? title.substring(0, title.lastIndexOf("{short}") >= 32 ? 29 : title.lastIndexOf("{short}")) + "..." : title.substring(0, title.length() >= 32 ? 29 : title.length()) + "..." : title.replace("{short}", "");
List<ItemStack> heads = new ArrayList<>();
results.forEach(customHead -> {
ItemEditor itemEditor = new ItemEditor(customHead);

View File

@ -20,18 +20,19 @@ public class Configs {
private File file = null;
private boolean inPlugin;
private final boolean internalFile;
private String subfolder;
private String filename;
private final String subfolder;
private final String filename;
private Plugin plugin;
private final Plugin plugin;
public Configs(Plugin plugin, String filename, boolean internalFile, String... subfolder) {
this.plugin = plugin;
this.filename = filename;
this.subfolder = subfolder.length > 0 ? "plugins/" + plugin.getName() + "/" + subfolder[0] : "plugins/" + plugin.getName();
if (inPlugin = internalFile) {
this.internalFile = internalFile;
if (this.internalFile) {
Utils.saveInternalFile(filename, this.subfolder);
}
get().options().copyDefaults(true);
@ -53,21 +54,21 @@ public class Configs {
}
public void reload() {
file = new File(subfolder, filename);
config = YamlConfiguration.loadConfiguration(file);
if (inPlugin) {
InputStream dataStream = plugin.getResource(filename);
this.file = new File(this.subfolder, this.filename);
this.config = YamlConfiguration.loadConfiguration(this.file);
if (this.internalFile) {
InputStream dataStream = this.plugin.getResource(this.filename);
if (dataStream != null) {
config.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(dataStream)));
this.config.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(dataStream)));
}
}
}
public File getFile() {
if (file == null) {
if (this.file == null) {
reload();
}
return file;
return this.file;
}
}

View File

@ -1,14 +0,0 @@
package de.likewhat.customheads.utils;
/*
* Project: CustomHeads in EmptyCallback
* by LikeWhat
*
* created on 04.08.2020 at 01:57
*/
public interface EmptyCallback {
void call();
}

View File

@ -7,7 +7,6 @@ import com.mojang.authlib.properties.Property;
import com.mojang.authlib.properties.PropertyMap;
import com.mojang.util.UUIDTypeAdapter;
import de.likewhat.customheads.CustomHeads;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.BufferedReader;
@ -25,17 +24,17 @@ public class GameProfileBuilder {
private static final String JSON_CAPE = "{\"timestamp\":%d,\"profileId\":\"%s\",\"profileName\":\"%s\",\"isPublic\":true,\"textures\":{\"SKIN\":{\"url\":\"%s\"},\"CAPE\":{\"url\":\"%s\"}}}";
private static final String JSON_SKIN = "{\"timestamp\":%d,\"profileId\":\"%s\",\"profileName\":\"%s\",\"isPublic\":true,\"textures\":{\"SKIN\":{\"url\":\"%s\"}}}";
private static final String SERVICE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/%s";
private static Gson gson = new GsonBuilder().disableHtmlEscaping().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).registerTypeAdapter(GameProfile.class, new GameProfileSerializer()).registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create();
private static final Gson GSON = new GsonBuilder().disableHtmlEscaping().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).registerTypeAdapter(GameProfile.class, new GameProfileSerializer()).registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create();
public static final HashMap<UUID, CachedProfile> cache = new HashMap<>();
private static long cacheTime = 6000;
private static final long CACHE_TIME = 6000;
public static String gameProfileToString(GameProfile profile) {
return gson.toJson(profile);
return GSON.toJson(profile);
}
public static GameProfile gameProfileFromString(String string) {
return gson.fromJson(string, GameProfile.class);
return GSON.fromJson(string, GameProfile.class);
}
public static void fetch(UUID uuid, Consumer<GameProfile> consumer) {
@ -50,20 +49,20 @@ public class GameProfileBuilder {
connection.setReadTimeout(5000);
if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAVAILABLE) {
Bukkit.getLogger().warning("Service is unavailable at this moment");
CustomHeads.getPluginLogger().warning("Service is unavailable at this moment");
consumer.accept(null);
return;
}
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
GameProfile result = gson.fromJson(reader.lines().collect(Collectors.joining()), GameProfile.class);
GameProfile result = GSON.fromJson(reader.lines().collect(Collectors.joining()), GameProfile.class);
cache.put(uuid, new CachedProfile(result));
consumer.accept(result);
return;
}
}
} catch (Exception e) {
Bukkit.getLogger().log(Level.WARNING, "Failed to get Profile of " + uuid.toString(), e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to get Profile of " + uuid.toString(), e);
}
consumer.accept(null);
}
@ -80,7 +79,7 @@ public class GameProfileBuilder {
args.add(skinUrl);
if (cape)
args.add(capeUrl);
profile.getProperties().put("textures", new Property("textures", new String(Base64.getEncoder().encode(String.format(cape ? JSON_CAPE : JSON_SKIN, args.toArray(new Object[args.size()])).getBytes()), Charsets.UTF_8)));
profile.getProperties().put("textures", new Property("textures", new String(Base64.getEncoder().encode(String.format(cape ? JSON_CAPE : JSON_SKIN, args.toArray(new Object[0])).getBytes()), Charsets.UTF_8)));
return profile;
}
@ -130,7 +129,7 @@ public class GameProfileBuilder {
}
public boolean isValid() {
return cacheTime < 0 || (System.currentTimeMillis() - timestamp) < cacheTime;
return System.currentTimeMillis() - timestamp < CACHE_TIME;
}
}

View File

@ -19,6 +19,8 @@ import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.function.Consumer;
public class InteractiveDialog {
private Inventory dialog;
@ -27,7 +29,7 @@ public class InteractiveDialog {
private Listener listener;
InteractiveDialog(String title, SimpleCallback<Boolean> callback, String[] yesLore, String[] noLore, ItemStack middleItem) {
InteractiveDialog(String title, Consumer<Boolean> callback, String[] yesLore, String[] noLore, ItemStack middleItem) {
dialog = Bukkit.createInventory(null, 9 * 3, title);
yesItem = new ItemEditor(Material.SKULL_ITEM, 3).setTexture("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMzYxZTViMzMzYzJhMzg2OGJiNmE1OGI2Njc0YTI2MzkzMjM4MTU3MzhlNzdlMDUzOTc3NDE5YWYzZjc3In19fQ==").setDisplayName("§a" + CustomHeads.getLanguageManager().YES).setLore(yesLore).getItem();
noItem = new ItemEditor(Material.SKULL_ITEM, 3).setTexture("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNGJhYzc3NTIwYjllZWU2NTA2OGVmMWNkOGFiZWFkYjAxM2I0ZGUzOTUzZmQyOWFjNjhlOTBlNDg2NjIyNyJ9fX0=").setDisplayName("§c" + CustomHeads.getLanguageManager().NO).setLore(noLore).getItem();
@ -41,9 +43,9 @@ public class InteractiveDialog {
if(event.getView().getTopInventory() == dialog) {
ItemStack currentItem = event.getCurrentItem();
if (yesItem.equals(currentItem)) {
callback.call(true);
callback.accept(true);
} else if (noItem.equals(currentItem)) {
callback.call(false);
callback.accept(false);
}
}
}
@ -63,6 +65,7 @@ public class InteractiveDialog {
yesItem = null;
noItem = null;
HandlerList.unregisterAll(listener);
listener = null;
}
public void showTo(Player player) {

View File

@ -2,7 +2,10 @@ package de.likewhat.customheads.utils;
import com.mojang.authlib.GameProfile;
import de.likewhat.customheads.CustomHeads;
import de.likewhat.customheads.utils.reflection.helpers.NBTTagUtils;
import de.likewhat.customheads.utils.reflection.helpers.ReflectionUtils;
import de.likewhat.customheads.utils.reflection.helpers.Version;
import de.likewhat.customheads.utils.reflection.helpers.collections.ReflectionMethodCollection;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
@ -10,6 +13,7 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@ -24,9 +28,9 @@ import java.util.Map;
public class ItemEditor {
private ItemStack itemStack;
private final ItemStack itemStack;
private ItemMeta meta;
private final ItemMeta meta;
public ItemEditor(ItemStack itemStack) {
this.itemStack = itemStack.clone();
@ -144,16 +148,15 @@ public class ItemEditor {
if (itemStack.getType() != Material.SKULL_ITEM)
throw new IllegalArgumentException("ItemStack is not an Player Head");
GameProfile profile = GameProfileBuilder.createProfileWithTexture(texture);
// Just setting the profile breaks everything sometimes
if(ReflectionUtils.methodExists(SkullMeta.class, "setProfile", GameProfile.class)) {
if (!ReflectionUtils.setField(meta, "profile", profile)) {
throw new IllegalStateException("Unable to inject GameProfile");
}
if(Version.getCurrentVersion().isNewerThan(Version.V1_17_R1)) {
try {
ReflectionUtils.invokeMethod(ReflectionUtils.getMethod("setProfile", SkullMeta.class, GameProfile.class), meta, profile);
} catch (Exception e) {
throw new IllegalStateException("Unable to set Gameprofile");
}
} else {
if (!ReflectionUtils.setField(meta, "profile", profile)) {
throw new IllegalStateException("Unable to inject Gameprofile");
Object serializedProfile = ReflectionMethodCollection.GAMEPROFILE_SERIALIZE.invokeOn(null, NBTTagUtils.createInstance(NBTTagUtils.NBTType.COMPOUND), profile);
ReflectionUtils.setField(meta, "serializedProfile", serializedProfile);
} catch (InvocationTargetException | IllegalAccessException e) {
throw new IllegalStateException("Unable to update serialized GameProfile", e);
}
}
return this;

View File

@ -2,13 +2,17 @@ package de.likewhat.customheads.utils;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import de.likewhat.customheads.CustomHeads;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.Bukkit;
import java.io.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.logging.Level;
/*
@ -27,7 +31,7 @@ public class JsonFile {
private JsonElement json;
private File file;
private final File file;
public JsonFile(String filename) {
this(filename, defaultSubfolder);
@ -44,21 +48,18 @@ public class JsonFile {
}
public void saveJson() {
try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) {
String[] jsonSplitted = Utils.GSON_PRETTY.toJson(json).split("\n");
for (String line : jsonSplitted) {
writer.write(line + "\n");
}
try (OutputStreamWriter writer = new OutputStreamWriter(Files.newOutputStream(file.toPath()), StandardCharsets.UTF_8)) {
writer.write(Utils.GSON_PRETTY.toJson(json));
} catch (Exception e) {
e.printStackTrace();
}
}
public void reload() {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(file.toPath()), StandardCharsets.UTF_8))) {
json = PARSER.parse(reader);
} catch (Exception e) {
Bukkit.getLogger().log(Level.WARNING, "Failed to read Json from " + file.getName(), e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to read Json from " + file.getName(), e);
}
}

View File

@ -55,7 +55,7 @@ public class JsonToItem {
itemEditor.setTexture(itemObj.get("texture").getAsString());
}
} catch (Exception e) {
CustomHeads.getInstance().getLogger().log(Level.WARNING, "Failed to create Item", e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to create Item", e);
}
return itemEditor == null ? null : itemEditor.getItem();
}

View File

@ -0,0 +1,44 @@
package de.likewhat.customheads.utils;
import de.likewhat.customheads.CustomHeads;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.stream.Collectors;
public class LoggingUtils {
private static final List<String> alreadyLogged = new ArrayList<>();
public static void logOnce(Level level, String string) {
if(!alreadyLogged.contains(string)) {
alreadyLogged.add(string);
CustomHeads.getPluginLogger().log(level, string);
}
}
/**
* Returns a String that is formatted like a Method: name(bodyParams)
* @param name The "Method" Name
* @param bodyParams The Classes in the Body
* @return Formatted String
*/
public static String methodLikeString(String name, Class<?>... bodyParams) {
return methodLikeString(name, Class::getCanonicalName, bodyParams);
}
/**
* Returns a String that is formatted like a Method: name(bodyParams)
* @param name The "Method" Name
* @param mapper Function that defines how the Body Parameters should get converted
* @param bodyParams The Classes in the Body
* @return Formatted String
*/
public static String methodLikeString(String name, Function<Class<?>, String> mapper, Class<?>... bodyParams) {
return name + "(" + Arrays.stream(bodyParams).map(mapper).collect(Collectors.joining(", ")) + ")";
}
}

View File

@ -30,16 +30,16 @@ import java.util.stream.Collectors;
public class PlayerWrapper implements CustomHeadsPlayer {
private static HashMap<UUID, CustomHeadsPlayer> wrappedPlayersCache = new HashMap<>();
private static final HashMap<UUID, CustomHeadsPlayer> WRAPPED_PLAYERS_CACHE = new HashMap<>();
@Getter private List<CustomHead> unlockedHeads = new ArrayList<>();
private List<Category> unlockedCategories = new ArrayList<>();
@Getter private List<ItemStack> savedHeads = new ArrayList<>();
@Getter private final List<ItemStack> savedHeads = new ArrayList<>();
@Getter private SearchHistory searchHistory;
@Getter private GetHistory getHistory;
private OfflinePlayer player;
private final OfflinePlayer player;
private PlayerWrapper(OfflinePlayer player) {
this.player = player;
@ -79,21 +79,21 @@ public class PlayerWrapper implements CustomHeadsPlayer {
} catch (Exception e) {
e.printStackTrace();
}
wrappedPlayersCache.put(player.getUniqueId(), this);
WRAPPED_PLAYERS_CACHE.put(player.getUniqueId(), this);
}
static CustomHeadsPlayer wrapPlayer(OfflinePlayer player) {
return wrappedPlayersCache.containsKey(player.getUniqueId()) ? wrappedPlayersCache.get(player.getUniqueId()) : new PlayerWrapper(player);
return WRAPPED_PLAYERS_CACHE.containsKey(player.getUniqueId()) ? WRAPPED_PLAYERS_CACHE.get(player.getUniqueId()) : new PlayerWrapper(player);
}
public static void clearCache() {
if (wrappedPlayersCache.isEmpty())
if (WRAPPED_PLAYERS_CACHE.isEmpty())
return;
JsonFile jsonFile = CustomHeads.getPlayerDataFile();
JsonObject rootObjects = jsonFile.getJson().getAsJsonObject();
for (UUID uuid : wrappedPlayersCache.keySet()) {
CustomHeadsPlayer customHeadsPlayer = wrappedPlayersCache.get(uuid);
for (UUID uuid : WRAPPED_PLAYERS_CACHE.keySet()) {
CustomHeadsPlayer customHeadsPlayer = WRAPPED_PLAYERS_CACHE.get(uuid);
JsonObject uuidObject = rootObjects.has(uuid.toString()) ? rootObjects.getAsJsonObject(uuid.toString()) : new JsonObject();
JsonObject savedHeads = new JsonObject();
List<ItemStack> saved = customHeadsPlayer.getSavedHeads();
@ -136,7 +136,7 @@ public class PlayerWrapper implements CustomHeadsPlayer {
}
jsonFile.setJson(rootObjects);
jsonFile.saveJson();
wrappedPlayersCache.clear();
WRAPPED_PLAYERS_CACHE.clear();
}
public List<Category> getUnlockedCategories(boolean ignorePermission) {

View File

@ -19,57 +19,57 @@ import java.util.*;
public class ScrollableInventory {
private static List<Comparator<ItemStack>> sorting = new ArrayList<>(Arrays.asList((o1, o2) -> 0, Comparator.comparing(item -> ChatColor.stripColor(Utils.format(item.getItemMeta().getDisplayName()))), Comparator.comparing(item -> item.getItemMeta().getDisplayName().substring(1, 2))));
private static final List<Comparator<ItemStack>> SORTING = new ArrayList<>(Arrays.asList((o1, o2) -> 0, Comparator.comparing(item -> ChatColor.stripColor(Utils.format(item.getItemMeta().getDisplayName()))), Comparator.comparing(item -> item.getItemMeta().getDisplayName().substring(1, 2))));
public static List<String> sortName = new ArrayList<>(Arrays.asList("invalid", CustomHeads.getLanguageManager().CYCLE_ARRANGEMENT_DEFAULT, CustomHeads.getLanguageManager().CYCLE_ARRANGEMENT_ALPHABETICAL, CustomHeads.getLanguageManager().CYCLE_ARRANGEMENT_COLOR));
private final long cacheTime;
private static HashMap<String, ScrollableInventory> cachedInventories = new HashMap<>();
private HashMap<Integer, ItemStack> buttons = new HashMap<>();
private static final HashMap<String, ScrollableInventory> CACHED_INVENTORIES = new HashMap<>();
private final HashMap<Integer, ItemStack> buttons = new HashMap<>();
private Language language = CustomHeads.getLanguageManager();
private final Language language = CustomHeads.getLanguageManager();
private List<ItemStack> content;
private LinkedList<ItemStack> defContent;
private boolean clonable = false;
private boolean contentClonable = false;
private boolean contentMovable = true;
private int currentArrangement;
private int currentPage = 1;
private Inventory inventory;
private final Inventory inventory;
private String[] extraTags;
private String uid;
private final String uid;
public ScrollableInventory(String title) {
this(title, new ArrayList<>());
}
public ScrollableInventory(String title, List<ItemStack> content) {
inventory = Bukkit.createInventory(null, 54, title);
uid = Utils.randomAlphabetic(6);
this.inventory = Bukkit.createInventory(null, 54, title);
this.uid = Utils.randomAlphabetic(6);
setContent(content);
cachedInventories.put(uid, this);
cacheTime = System.currentTimeMillis();
CACHED_INVENTORIES.put(this.uid, this);
this.cacheTime = System.currentTimeMillis();
}
public static HashMap<String, ScrollableInventory> getInventories() {
return cachedInventories;
return CACHED_INVENTORIES;
}
public static ScrollableInventory getInventoryByID(String uid) {
return cachedInventories.get(uid);
return CACHED_INVENTORIES.get(uid);
}
public static void clearCache() {
if (cachedInventories.isEmpty()) return;
cachedInventories.keySet().removeIf(uid -> System.currentTimeMillis() - cachedInventories.get(uid).cacheTime > 6000);
if (CACHED_INVENTORIES.isEmpty()) return;
CACHED_INVENTORIES.keySet().removeIf(uid -> System.currentTimeMillis() - CACHED_INVENTORIES.get(uid).cacheTime > 6000);
}
public ScrollableInventory setBarItem(int index, ItemStack itemStack) {
buttons.put(index, itemStack);
this.buttons.put(index, itemStack);
return this;
}
public ScrollableInventory setContentsClonable(boolean clonable) {
this.clonable = clonable;
this.contentClonable = clonable;
return this;
}
@ -86,7 +86,7 @@ public class ScrollableInventory {
public void refreshContent() {
for (int i = 0; i < content.size(); i++) {
ItemStack item = content.get(i);
if (clonable)
if (contentClonable)
item = CustomHeads.getTagEditor().addTags(item, "clonable");
if (!contentMovable)
item = CustomHeads.getTagEditor().addTags(item, "blockMoving");
@ -95,11 +95,11 @@ public class ScrollableInventory {
}
public void refreshCurrentPage() {
setPage(currentPage);
setPage(this.currentPage);
}
public void setPage(int page) {
currentPage = page;
this.currentPage = page;
for (int i = 0; i <= 45; i++)
inventory.setItem(i, null);
@ -126,12 +126,12 @@ public class ScrollableInventory {
}
public int reArrangeContents(int method) {
if ((currentArrangement = method < 1 ? 1 : Math.min(method, (sorting.size() + 1))) == 1) {
content = new ArrayList<>(defContent);
if ((currentArrangement = method < 1 ? 1 : Math.min(method, (SORTING.size() + 1))) == 1) {
this.content = new ArrayList<>(defContent);
} else {
content.sort(sorting.get(currentArrangement - 1));
this.content.sort(SORTING.get(currentArrangement - 1));
}
setPage(currentPage);
setPage(this.currentPage);
return currentArrangement;
}
@ -143,25 +143,25 @@ public class ScrollableInventory {
}
public int nextArrangement() {
return reArrangeContents(++currentArrangement > sorting.size() ? currentArrangement = 1 : currentArrangement);
return reArrangeContents(++currentArrangement > SORTING.size() ? currentArrangement = 1 : currentArrangement);
}
public void nextPage() {
if (hasPage(currentPage + 1))
setPage(++currentPage);
if (hasPage(this.currentPage + 1))
setPage(++this.currentPage);
}
public void previousPage() {
if (hasPage(currentPage - 1))
setPage(--currentPage);
if (hasPage(this.currentPage - 1))
setPage(--this.currentPage);
}
public String[] getExtraTags() {
return extraTags;
return this.extraTags;
}
public ScrollableInventory setExtraTags(String... tags) {
extraTags = tags;
this.extraTags = tags;
return this;
}
@ -178,7 +178,7 @@ public class ScrollableInventory {
public int getPages() {
int p;
return (p = (int) Math.ceil(content.size() / 45.0)) < 1 ? 1 : p;
return (p = (int) Math.ceil(this.content.size() / 45.0)) < 1 ? 1 : p;
}
public List<ItemStack> getContentFromPage(int page, boolean tags) {
@ -188,11 +188,11 @@ public class ScrollableInventory {
throw new IllegalArgumentException("Unknown Page " + page);
int start = (page - 1) * 45;
int end = page * 45;
return contentCopy.subList(start, content.size() > end ? end : content.size());
return contentCopy.subList(start, Math.min(this.content.size(), end));
}
public void setItemOnCurrentPage(int index, ItemStack to) {
setItem(currentPage, index, to);
setItem(this.currentPage, index, to);
}
public void setItem(int page, int index, ItemStack to) {
@ -207,6 +207,6 @@ public class ScrollableInventory {
}
public int getCurrentPage() {
return currentPage;
return this.currentPage;
}
}

View File

@ -1,14 +0,0 @@
package de.likewhat.customheads.utils;
/*
* Project: CustomHeads in SimpleCallback
* by LikeWhat
*
* created on 06.02.2020 at 23:35
*/
public interface SimpleCallback<T> {
void call(T object);
}

View File

@ -13,7 +13,8 @@ import de.likewhat.customheads.category.SubCategory;
import de.likewhat.customheads.utils.reflection.AnvilGUI;
import de.likewhat.customheads.utils.reflection.helpers.ItemNBTUtils;
import de.likewhat.customheads.utils.reflection.helpers.ReflectionUtils;
import de.likewhat.customheads.utils.updaters.AsyncFileDownloader;
import de.likewhat.customheads.utils.reflection.helpers.collections.ReflectionClassCollection;
import de.likewhat.customheads.utils.reflection.helpers.collections.ReflectionConstructorCollection;
import de.likewhat.customheads.utils.updaters.FetchResult;
import de.likewhat.customheads.utils.updaters.GitHubDownloader;
import org.bukkit.Bukkit;
@ -56,7 +57,6 @@ public class Utils {
private static HashMap<Character, ItemStack> alphabet;
private static HashMap<String, String[]> subCommands;
private static HashMap<String, String[]> perms;
private static long lastRedownload = 0;
private static final String TEXTURE_LINK = "http://textures.minecraft.net/texture/%s";
@ -301,7 +301,7 @@ public class Utils {
* @param noLore Lore of the No Button
* @param middleItem Item in the Middle of the Dialog
*/
public static void showInteractiveDialog(Player player, String title, SimpleCallback<Boolean> callback, String[] yesLore, String[] noLore, ItemStack middleItem) {
public static void showInteractiveDialog(Player player, String title, Consumer<Boolean> callback, String[] yesLore, String[] noLore, ItemStack middleItem) {
new InteractiveDialog(title, callback, yesLore, noLore, middleItem).showTo(player);
}
@ -420,7 +420,7 @@ public class Utils {
Object tex = prop.getClass().getMethod("getList", String.class, int.class).invoke(prop, "textures", 10);
Object list = tex.getClass().getMethod("get", int.class).invoke(tex, 0);
return list.getClass().getMethod("getString", String.class).invoke(list, "Value").toString() != null;
} catch (Exception whoops) {
} catch (Exception ignored) {
}
return false;
}
@ -503,8 +503,8 @@ public class Utils {
}
public static void getUUID(String name, Consumer<String> consumer) {
if (CustomHeads.uuidCache.containsKey(name)) {
consumer.accept(CustomHeads.uuidCache.get(name));
if (CustomHeads.UUID_CACHE.containsKey(name)) {
consumer.accept(CustomHeads.UUID_CACHE.get(name));
return;
}
Utils.runAsync(new BukkitRunnable() {
@ -513,7 +513,7 @@ public class Utils {
HttpURLConnection connection = (HttpURLConnection) new URL(String.format("https://api.mojang.com/users/profiles/minecraft/%s", name)).openConnection();
connection.setReadTimeout(5000);
if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAVAILABLE) {
Bukkit.getLogger().warning("Service is unaviable a this moment: " + connection.getResponseMessage());
CustomHeads.getPluginLogger().warning("Service is unaviable a this moment: " + connection.getResponseMessage());
consumer.accept(null);
return;
}
@ -532,7 +532,7 @@ public class Utils {
});
}
} catch (Exception whoops) {
Bukkit.getLogger().log(Level.WARNING, "Couldn't get UUID from " + name, whoops);
CustomHeads.getPluginLogger().log(Level.WARNING, "Couldn't get UUID from " + name, whoops);
Utils.runSynced(new BukkitRunnable() {
public void run() {
consumer.accept(null);
@ -548,7 +548,7 @@ public class Utils {
if (!outputDir.exists())
Files.createParentDirs(new File(outputDir, "a.temp"));
ZipEntry zipEntry;
Bukkit.getLogger().info("[FileZipper] Unzipping " + zipFile.getName());
CustomHeads.getPluginLogger().info("[FileZipper] Unzipping " + zipFile.getName());
while ((zipEntry = inputStream.getNextEntry()) != null) {
File zipEntryFile = new File(outputDir, zipEntry.getName());
if (getExtension(zipEntry.getName()).length() > 0) {
@ -563,9 +563,9 @@ public class Utils {
}
inputStream.closeEntry();
inputStream.close();
Bukkit.getLogger().info("[FileZipper] Unzip finished");
CustomHeads.getPluginLogger().info("[FileZipper] Unzip finished");
} catch (Exception exception) {
Bukkit.getLogger().log(Level.WARNING, "[FileZipper] Failed to unzip " + zipFile.getName(), exception);
CustomHeads.getPluginLogger().log(Level.WARNING, "[FileZipper] Failed to unzip " + zipFile.getName(), exception);
}
}
@ -573,13 +573,13 @@ public class Utils {
boolean console = sender instanceof ConsoleCommandSender;
if (System.currentTimeMillis() - lastRedownload < TimeUnit.MINUTES.toMillis(2)) {
sender.sendMessage((console ? CustomHeads.chPrefix : "") + CustomHeads.getLanguageManager().LANGUAGE_REDOWNLOAD_FAILED_WAIT);
sender.sendMessage((console ? CustomHeads.PREFIX_GENERAL : "") + CustomHeads.getLanguageManager().LANGUAGE_REDOWNLOAD_FAILED_WAIT);
return false;
}
lastRedownload = System.currentTimeMillis();
// Backing up jic >_>
sender.sendMessage((console ? CustomHeads.chPrefix : "") + CustomHeads.getLanguageManager().LANGUAGE_REDOWNLOAD_BACKING_UP);
sender.sendMessage((console ? CustomHeads.PREFIX_GENERAL : "") + CustomHeads.getLanguageManager().LANGUAGE_REDOWNLOAD_BACKING_UP);
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date(System.currentTimeMillis());
@ -594,22 +594,22 @@ public class Utils {
for (File langDir : langRoot.listFiles()) {
if(!langDir.renameTo(new File(backUpRoot + "/" + langDir.getName()))) {
Bukkit.getLogger().warning("Failed to move Directory");
CustomHeads.getPluginLogger().warning("Failed to move Directory");
}
// FileUtils.moveDirectory(langDir, new File(backUpRoot + "/" + langDir.getName()));
}
} catch (Exception e) {
CustomHeads.getInstance().getLogger().log(Level.WARNING, "Failed to move Directory", e);
sender.sendMessage((console ? CustomHeads.chPrefix : "") + CustomHeads.getLanguageManager().LANGUAGE_REDOWNLOAD_BACKUP_FAILED);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to move Directory", e);
sender.sendMessage((console ? CustomHeads.PREFIX_GENERAL : "") + CustomHeads.getLanguageManager().LANGUAGE_REDOWNLOAD_BACKUP_FAILED);
return false;
}
sender.sendMessage((console ? CustomHeads.chPrefix : "") + CustomHeads.getLanguageManager().LANGUAGE_REDOWNLOAD_DOWNLOADING);
sender.sendMessage((console ? CustomHeads.PREFIX_GENERAL : "") + CustomHeads.getLanguageManager().LANGUAGE_REDOWNLOAD_DOWNLOADING);
GitHubDownloader gitGetter = new GitHubDownloader("IHasName", "CustomHeads").enableAutoUnzipping();
gitGetter.download(CustomHeads.getInstance().getDescription().getVersion(), "en_EN.zip", new File("plugins/CustomHeads/language"), (AsyncFileDownloader.AfterTask) () -> {
CustomHeads.silentReload();
sender.sendMessage((console ? CustomHeads.chPrefix : "") + CustomHeads.getLanguageManager().LANGUAGE_REDOWNLOAD_DONE);
gitGetter.download(CustomHeads.getInstance().getDescription().getVersion(), "en_EN.zip", new File("plugins/CustomHeads/language"), () -> {
CustomHeads.reload(null);
sender.sendMessage((console ? CustomHeads.PREFIX_GENERAL : "") + CustomHeads.getLanguageManager().LANGUAGE_REDOWNLOAD_DONE);
});
return true;
}
@ -623,12 +623,12 @@ public class Utils {
try (InputStream fileInputStream = CustomHeads.getInstance().getResource(filename); FileOutputStream fileOutputStream = new FileOutputStream(outFile)) {
fileOutputStream.getChannel().transferFrom(Channels.newChannel(fileInputStream), 0, Integer.MAX_VALUE);
} catch (FileNotFoundException e) {
Bukkit.getLogger().log(Level.WARNING, "Failed to create File " + filename, e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to create File " + filename, e);
}
}
return outFile;
} catch (IOException e) {
Bukkit.getLogger().log(Level.WARNING, "Failed to create File " + filename, e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to create File " + filename, e);
}
return null;
}
@ -678,14 +678,17 @@ public class Utils {
Object chat = ReflectionUtils.getMCServerClassByName("ChatSerializer", "network.chat").getMethod("a", String.class).invoke(null, json);
Object packet;
if(ReflectionUtils.MC_VERSION >= 16) {
Class<?> chatMessageTypeClass = ReflectionUtils.getMCServerClassByName("ChatMessageType", "network.chat");
packet = ReflectionUtils.getMCServerClassByName("PacketPlayOutChat", "network.protocol.game").getConstructor(ReflectionUtils.getMCServerClassByName("IChatBaseComponent", "network.chat"), chatMessageTypeClass, UUID.class).newInstance(chat, ReflectionUtils.getEnumConstant(chatMessageTypeClass, "CHAT"), null);
Enum<?> messageType = ReflectionUtils.getEnumConstant(ReflectionClassCollection.CHAT_MESSAGE_TYPE, "CHAT");
if(messageType == null) {
messageType = ReflectionUtils.getEnumConstant(ReflectionClassCollection.CHAT_MESSAGE_TYPE, "a");
}
packet = ReflectionConstructorCollection.PACKET_PLAYOUT_CHAT.construct(chat, messageType, null);
} else {
packet = ReflectionUtils.getMCServerClassByName("PacketPlayOutChat", "network.protocol.game").getConstructor(ReflectionUtils.getMCServerClassByName("IChatBaseComponent", "network.chat")).newInstance(chat);
packet = ReflectionConstructorCollection.PACKET_PLAYOUT_CHAT.construct(chat);
}
ReflectionUtils.sendPacket(packet, player);
} catch (Exception e) {
CustomHeads.getInstance().getLogger().log(Level.WARNING, "Could not send JSON-Message to Player", e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Could not send JSON-Message to Player", e);
}
}
@ -729,13 +732,4 @@ public class Utils {
return newArray;
}
private static final List<String> alreadyLogged = new ArrayList<>();
public static void logOnce(Level level, String string) {
if(!alreadyLogged.contains(string)) {
alreadyLogged.add(string);
Bukkit.getLogger().log(level, string);
}
}
}

View File

@ -1,8 +1,10 @@
package de.likewhat.customheads.utils.reflection;
import de.likewhat.customheads.CustomHeads;
import de.likewhat.customheads.utils.Utils;
import de.likewhat.customheads.utils.LoggingUtils;
import de.likewhat.customheads.utils.reflection.helpers.ReflectionUtils;
import de.likewhat.customheads.utils.reflection.helpers.Version;
import de.likewhat.customheads.utils.reflection.helpers.collections.ReflectionClassCollection;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.Bukkit;
@ -31,39 +33,29 @@ import java.util.logging.Level;
*/
public class AnvilGUI {
private static final Class<?> containerAnvilClass;
private static final Class<?> packetPlayOutOpenWindowClass;
private static final Class<?> containerClass;
static {
containerAnvilClass = ReflectionUtils.getMCServerClassByName("ContainerAnvil", "world.inventory");
packetPlayOutOpenWindowClass = ReflectionUtils.getMCServerClassByName("PacketPlayOutOpenWindow", "network.protocol.game");
containerClass = ReflectionUtils.getMCServerClassByName("Container", "world.inventory");
}
private HashMap<AnvilSlot, ItemStack> items = new HashMap<>();
private AnvilClickEventHandler handler;
private ItemStack currentitem = null;
private ItemStack currentItem = null;
private Inventory inventory;
private Listener listener;
private Player player;
private String title;
private final String title;
public AnvilGUI(final Player player, String title, final AnvilClickEventHandler anvilhandler) {
public AnvilGUI(final Player player, String title, final AnvilClickEventHandler anvilHandler) {
this.player = player;
this.title = title;
handler = anvilhandler;
this.handler = anvilHandler;
this.listener = new Listener() {
@EventHandler
public void anvilClick(InventoryClickEvent e) {
if (e.getWhoClicked() instanceof Player) {
if (e.getClickedInventory() == null) return;
if (e.getClickedInventory().equals(inventory)) {
ItemStack item = e.getCurrentItem();
int slot = e.getRawSlot();
public void anvilClick(InventoryClickEvent event) {
if (event.getWhoClicked() instanceof Player) {
if (event.getClickedInventory() == null) return;
if (event.getClickedInventory().equals(inventory)) {
ItemStack item = event.getCurrentItem();
int slot = event.getRawSlot();
String name = "";
if (item != null) {
currentitem = e.getCurrentItem();
currentItem = event.getCurrentItem();
if (item.hasItemMeta()) {
ItemMeta meta = item.getItemMeta();
if (meta.hasDisplayName()) {
@ -71,13 +63,13 @@ public class AnvilGUI {
}
}
}
AnvilClickEvent cE = new AnvilClickEvent(AnvilSlot.bySlot(slot), name);
handler.onAnvilClick(cE);
e.setCancelled(!cE.canTakeOut());
if (cE.willClose()) {
e.getWhoClicked().closeInventory();
AnvilClickEvent anvilClickEvent = new AnvilClickEvent(AnvilSlot.bySlot(slot), name);
handler.onAnvilClick(anvilClickEvent);
event.setCancelled(!anvilClickEvent.canTakeOut());
if (anvilClickEvent.willClose()) {
event.getWhoClicked().closeInventory();
}
if (cE.isWillDestroy()) {
if (anvilClickEvent.isWillDestroy()) {
destroy();
}
}
@ -87,13 +79,13 @@ public class AnvilGUI {
@EventHandler
public void anvilClose(InventoryCloseEvent event) {
if (event.getPlayer() instanceof Player) {
Inventory inv = event.getInventory();
if (inv.equals(AnvilGUI.this.inventory)) {
Inventory inventory = event.getInventory();
if (inventory.equals(AnvilGUI.this.inventory)) {
if (player.getGameMode() == GameMode.SURVIVAL || player.getGameMode() == GameMode.ADVENTURE) {
player.setLevel(player.getLevel() - 1);
}
handler.onAnvilClose();
inv.clear();
inventory.clear();
destroy();
}
}
@ -117,15 +109,6 @@ public class AnvilGUI {
Bukkit.getPluginManager().registerEvents(listener, CustomHeads.getInstance());
}
private static Class<?> getClassbyName(String ClassName) {
try {
return Class.forName("net.minecraft.server." + CustomHeads.version + "." + ClassName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
public Player getPlayer() {
return player;
}
@ -140,9 +123,9 @@ public class AnvilGUI {
}
try {
Object p = player.getClass().getMethod("getHandle").invoke(player);
Class<?> playerHandleClass = p.getClass();
int nextContainerId = (int) playerHandleClass.getMethod("nextContainerCounter").invoke(p);
Object playerHandle = player.getClass().getMethod("getHandle").invoke(player);
Class<?> playerHandleClass = playerHandle.getClass();
int nextContainerId = (int) playerHandleClass.getMethod("nextContainerCounter").invoke(playerHandle);
Location location = player.getLocation();
Constructor<?> chatMessageConstructor = ReflectionUtils.getMCServerClassByName("ChatMessage", "network.chat").getConstructor(String.class, Object[].class);
@ -158,29 +141,29 @@ public class AnvilGUI {
case 11:
case 12:
case 13:
container = containerAnvilClass.getConstructor(getClassbyName("PlayerInventory"), getClassbyName("World"), getClassbyName("BlockPosition"), getClassbyName("EntityHuman")).newInstance(playerHandleClass.getField("inventory").get(p), playerHandleClass.getField("world").get(p), getClassbyName("BlockPosition").getConstructor(int.class, int.class, int.class).newInstance(location.getBlockX(), location.getBlockY(), location.getBlockZ()), p);
packet = packetPlayOutOpenWindowClass.getConstructor(int.class, String.class, getClassbyName("IChatBaseComponent"), int.class).newInstance(nextContainerId, "minecraft:anvil", chatMessageConstructor.newInstance(title, new Object[]{}), 0);
windowIdField = containerClass.getField("windowId");
container = ReflectionClassCollection.CONTAINER_ANVIL.getConstructor(ReflectionUtils.getMCServerClassByName("PlayerInventory"), ReflectionUtils.getMCServerClassByName("World"), ReflectionUtils.getMCServerClassByName("BlockPosition"), ReflectionUtils.getMCServerClassByName("EntityHuman")).newInstance(playerHandleClass.getField("inventory").get(playerHandle), playerHandleClass.getField("world").get(playerHandle), ReflectionUtils.getMCServerClassByName("BlockPosition").getConstructor(int.class, int.class, int.class).newInstance(location.getBlockX(), location.getBlockY(), location.getBlockZ()), playerHandle);
packet = ReflectionClassCollection.PACKET_PLAY_OUT_OPEN_WINDOW.getConstructor(int.class, String.class, ReflectionUtils.getMCServerClassByName("IChatBaseComponent"), int.class).newInstance(nextContainerId, "minecraft:anvil", chatMessageConstructor.newInstance(title, new Object[]{}), 0);
windowIdField = ReflectionClassCollection.CONTAINER.getField("windowId");
activeContainerField = ReflectionUtils.getFieldDynamic(playerHandleClass, "activeContainer");
break;
case 14:
case 15:
case 16:
containersClass = ReflectionUtils.getMCServerClassByName("Containers", "world.inventory");
container = containerAnvilClass.getConstructor(int.class, ReflectionUtils.getMCServerClassByName("PlayerInventory", "world.entity.player"), ReflectionUtils.getMCServerClassByName("ContainerAccess", "world.inventory")).newInstance(nextContainerId, playerHandleClass.getField("inventory").get(p), ReflectionUtils.getMCServerClassByName("ContainerAccess", "world.inventory").getMethod("at", ReflectionUtils.getMCServerClassByName("World", "world.level"), ReflectionUtils.getMCServerClassByName("BlockPosition", "core")).invoke(ReflectionUtils.getMCServerClassByName("ContainerAccess", "world.inventory"), playerHandleClass.getField("world").get(p), ReflectionUtils.getMCServerClassByName("BlockPosition", "core").getConstructor(int.class, int.class, int.class).newInstance(location.getBlockX(), location.getBlockY(), location.getBlockZ())));
packet = packetPlayOutOpenWindowClass.getConstructor(int.class, containersClass, ReflectionUtils.getMCServerClassByName("IChatBaseComponent", "network.chat")).newInstance(nextContainerId, containersClass.getField("ANVIL").get(containersClass), chatMessageConstructor.newInstance(title, new Object[]{}));
windowIdField = containerClass.getField("windowId");
container = ReflectionClassCollection.CONTAINER_ANVIL.getConstructor(int.class, ReflectionUtils.getMCServerClassByName("PlayerInventory", "world.entity.player"), ReflectionUtils.getMCServerClassByName("ContainerAccess", "world.inventory")).newInstance(nextContainerId, playerHandleClass.getField("inventory").get(playerHandle), ReflectionUtils.getMCServerClassByName("ContainerAccess", "world.inventory").getMethod("at", ReflectionUtils.getMCServerClassByName("World", "world.level"), ReflectionUtils.getMCServerClassByName("BlockPosition", "core")).invoke(ReflectionUtils.getMCServerClassByName("ContainerAccess", "world.inventory"), playerHandleClass.getField("world").get(playerHandle), ReflectionUtils.getMCServerClassByName("BlockPosition", "core").getConstructor(int.class, int.class, int.class).newInstance(location.getBlockX(), location.getBlockY(), location.getBlockZ())));
packet = ReflectionClassCollection.PACKET_PLAY_OUT_OPEN_WINDOW.getConstructor(int.class, containersClass, ReflectionUtils.getMCServerClassByName("IChatBaseComponent", "network.chat")).newInstance(nextContainerId, containersClass.getField("ANVIL").get(containersClass), chatMessageConstructor.newInstance(title, new Object[]{}));
windowIdField = ReflectionClassCollection.CONTAINER.getField("windowId");
activeContainerField = ReflectionUtils.getFieldDynamic(playerHandleClass, "activeContainer");
break;
default:
Utils.logOnce(Level.WARNING, "Current MC Version (" + CustomHeads.version + ") may not work with AnvilGUI");
LoggingUtils.logOnce(Level.WARNING, "Current MC Version (" + Version.getRawVersion() + ") may not work with AnvilGUI");
case 17:
//case 18:
containersClass = ReflectionUtils.getMCServerClassByName("Containers", "world.inventory");
Class<?> containerAccessClass = ReflectionUtils.getMCServerClassByName("ContainerAccess", "world.inventory");
container = containerAnvilClass.getConstructor(int.class, ReflectionUtils.getMCServerClassByName("PlayerInventory", "world.entity.player"), containerAccessClass).newInstance(nextContainerId, playerHandleClass.getMethod("getInventory").invoke(p), containerAccessClass.getMethod("at", ReflectionUtils.getMCServerClassByName("World", "world.level"), ReflectionUtils.getMCServerClassByName("BlockPosition", "core")).invoke(containerAccessClass, playerHandleClass.getField("t").get(p), ReflectionUtils.getMCServerClassByName("BlockPosition", "core").getConstructor(int.class, int.class, int.class).newInstance(location.getBlockX(), location.getBlockY(), location.getBlockZ())));
packet = packetPlayOutOpenWindowClass.getConstructor(int.class, containersClass, ReflectionUtils.getMCServerClassByName("IChatBaseComponent", "network.chat")).newInstance(nextContainerId, containersClass.getField("h").get(containersClass), chatMessageConstructor.newInstance(title, new Object[]{}));
windowIdField = containerClass.getDeclaredField("j");
container = ReflectionClassCollection.CONTAINER_ANVIL.getConstructor(int.class, ReflectionUtils.getMCServerClassByName("PlayerInventory", "world.entity.player"), containerAccessClass).newInstance(nextContainerId, playerHandleClass.getMethod("getInventory").invoke(playerHandle), containerAccessClass.getMethod("at", ReflectionUtils.getMCServerClassByName("World", "world.level"), ReflectionUtils.getMCServerClassByName("BlockPosition", "core")).invoke(containerAccessClass, playerHandleClass.getField("t").get(playerHandle), ReflectionUtils.getMCServerClassByName("BlockPosition", "core").getConstructor(int.class, int.class, int.class).newInstance(location.getBlockX(), location.getBlockY(), location.getBlockZ())));
packet = ReflectionClassCollection.PACKET_PLAY_OUT_OPEN_WINDOW.getConstructor(int.class, containersClass, ReflectionUtils.getMCServerClassByName("IChatBaseComponent", "network.chat")).newInstance(nextContainerId, containersClass.getField("h").get(containersClass), chatMessageConstructor.newInstance(title, new Object[]{}));
windowIdField = ReflectionClassCollection.CONTAINER.getDeclaredField("j");
activeContainerField = playerHandleClass.getField("bV");
break;
}
@ -189,23 +172,20 @@ public class AnvilGUI {
for (AnvilSlot slot : items.keySet()) {
inventory.setItem(slot.getSlot(), items.get(slot));
}
containerClass.getField("checkReachable").set(container, false);
ReflectionUtils.setField(container, "checkReachable", false);
ReflectionUtils.sendPacket(packet, player);
//playerConnection.getClass().getMethod("sendPacket", ReflectionUtils.getMCServerClassByName("Packet", "network.protocol")).invoke(playerConnection, packet);
activeContainerField.setAccessible(true);
activeContainerField.set(p, container);
windowIdField.setAccessible(true);
windowIdField.set(activeContainerField.get(p), nextContainerId);
ReflectionUtils.setField(playerHandle, activeContainerField, container);
ReflectionUtils.setField(activeContainerField.get(playerHandle), windowIdField, nextContainerId);
// Thanks to JordanPlayz for helping me find this Issue with the GUI
if(ReflectionUtils.MC_VERSION >= 17) {
p.getClass().getMethod("initMenu", containerClass).invoke(p, container);
playerHandle.getClass().getMethod("initMenu", ReflectionClassCollection.CONTAINER).invoke(playerHandle, container);
} else {
containerClass.getMethod("addSlotListener", ReflectionUtils.getMCServerClassByName("ICrafting")).invoke(container, p);
ReflectionClassCollection.CONTAINER.getMethod("addSlotListener", ReflectionUtils.getMCServerClassByName("ICrafting")).invoke(container, playerHandle);
}
} catch (Exception exception) {
Bukkit.getLogger().log(Level.WARNING, "Failed to open AnvilGUI", exception);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to open AnvilGUI", exception);
}
}
@ -219,7 +199,7 @@ public class AnvilGUI {
public enum AnvilSlot {
INPUT_LEFT(0), INPUT_RIGHT(1), OUTPUT(2);
private int slot;
private final int slot;
AnvilSlot(int slot) {
this.slot = slot;
@ -246,8 +226,8 @@ public class AnvilGUI {
@Getter
public class AnvilClickEvent {
private AnvilSlot slot;
private String name;
private final AnvilSlot slot;
private final String name;
@Setter
private boolean willDestroy = false;
private boolean takeout = false;
@ -280,7 +260,7 @@ public class AnvilGUI {
}
public ItemStack getItem() {
return currentitem;
return currentItem;
}
public ItemStack getItem(AnvilSlot slot) {

View File

@ -20,10 +20,10 @@ import java.util.logging.Level;
// It all started as an simple idea >_>
public class TagEditor {
private String tagname;
private final String tagName;
public TagEditor(String tagname) {
this.tagname = tagname;
public TagEditor(String tagName) {
this.tagName = tagName;
}
public static ItemStack clearTags(ItemStack itemStack) {
@ -35,26 +35,7 @@ public class TagEditor {
ItemNBTUtils.setTagOnItem(copy, itemTagCompound);
return ItemNBTUtils.asBukkitCopy(copy);
} catch (IllegalAccessException | InvocationTargetException e) {
CustomHeads.getInstance().getLogger().log(Level.WARNING, "Failed to reset Tags from Item", e);
return null;
}
}
public ItemStack setTags(ItemStack itemStack, List<String> tags) {
try {
Object copy = ItemNBTUtils.asNMSCopy(itemStack);
Object itemTagCompound = ItemNBTUtils.getTagFromItem(itemStack);
Object nbtTagCompound = ReflectionMethodCollection.NBT_TAGCOMPOUND_HASKEY.invokeOn(itemTagCompound, "tagEditor") ? ReflectionMethodCollection.NBT_TAGCOMPOUND_GETCOMPOUND.invokeOn(itemTagCompound, "tagEditor") : NBTTagUtils.createInstance(NBTTagUtils.NBTType.COMPOUND);
Object nbtTagList = NBTTagUtils.createInstance(NBTTagUtils.NBTType.LIST);
for (String tag : tags) {
NBTTagUtils.addObjectToNBTList(nbtTagList, NBTTagUtils.createInstance(NBTTagUtils.NBTType.STRING, tag));
}
ReflectionMethodCollection.NBT_TAGCOMPOUND_SET.invokeOn(nbtTagCompound, tagname, nbtTagList);
ReflectionMethodCollection.NBT_TAGCOMPOUND_SET.invokeOn(itemTagCompound, "tagEditor", nbtTagCompound);
ItemNBTUtils.setTagOnItem(copy, itemTagCompound);
return ItemNBTUtils.asBukkitCopy(copy);
} catch (Exception e) {
CustomHeads.getInstance().getLogger().log(Level.WARNING, "Failed to save Tags to Item", e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to reset Tags from Item", e);
return null;
}
}
@ -63,6 +44,25 @@ public class TagEditor {
return setTags(itemStack, Arrays.asList(tags));
}
public ItemStack setTags(ItemStack itemStack, List<String> tags) {
try {
Object copy = ItemNBTUtils.asNMSCopy(itemStack);
Object itemTagCompound = ItemNBTUtils.getTagFromItem(itemStack);
Object nbtTagCompound = ReflectionMethodCollection.NBT_TAGCOMPOUND_GETCOMPOUND.invokeOn(itemTagCompound, "tagEditor");
Object nbtTagList = NBTTagUtils.createInstance(NBTTagUtils.NBTType.LIST);
for (String tag : tags) {
NBTTagUtils.addObjectToNBTList(nbtTagList, NBTTagUtils.createInstance(NBTTagUtils.NBTType.STRING, tag));
}
ReflectionMethodCollection.NBT_TAGCOMPOUND_SET.invokeOn(nbtTagCompound, tagName, nbtTagList);
ReflectionMethodCollection.NBT_TAGCOMPOUND_SET.invokeOn(itemTagCompound, "tagEditor", nbtTagCompound);
ItemNBTUtils.setTagOnItem(copy, itemTagCompound);
return ItemNBTUtils.asBukkitCopy(copy);
} catch (Exception e) {
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to save Tags to Item", e);
return null;
}
}
public ItemStack addTags(ItemStack itemStack, String... tags) {
return addTags(itemStack, Arrays.asList(tags));
}
@ -93,14 +93,14 @@ public class TagEditor {
}
Object itemTag = ItemNBTUtils.getTagFromItem(itemStack);
Object itemTagCompound = ReflectionMethodCollection.NBT_TAGCOMPOUND_GETCOMPOUND.invokeOn(itemTag, "tagEditor");
Object nbtList = ReflectionMethodCollection.NBT_TAGCOMPOUND_GETLIST.invokeOn(itemTagCompound, tagname, NBTTagUtils.NBTType.STRING.id);
Object nbtList = ReflectionMethodCollection.NBT_TAGCOMPOUND_GETLIST.invokeOn(itemTagCompound, tagName, NBTTagUtils.NBTType.STRING.getId());
List<String> result = new ArrayList<>();
for (int i = 0; i < ReflectionMethodCollection.NBT_TAGLIST_SIZE.invokeOn(nbtList); i++) {
result.add(ReflectionMethodCollection.NBT_TAGLIST_GETSTRING.invokeOn(nbtList, i));
}
return result;
} catch (Exception e) {
CustomHeads.getInstance().getLogger().log(Level.WARNING, "Failed to get Tags from Item", e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to get Tags from Item", e);
}
return new ArrayList<>();
}
@ -120,7 +120,7 @@ public class TagEditor {
}
Object itemTag = ItemNBTUtils.getTagFromItem(item);
Object itemTagCompound = ReflectionMethodCollection.NBT_TAGCOMPOUND_GETCOMPOUND.invokeOn(itemTag, "tagEditor");
return ReflectionMethodCollection.NBT_TAGCOMPOUND_HASKEY.invokeOn(itemTagCompound, tagname);
return ReflectionMethodCollection.NBT_TAGCOMPOUND_HASKEY.invokeOn(itemTagCompound, tagName);
} catch (Exception e) {
return false;
}

View File

@ -1,7 +1,8 @@
package de.likewhat.customheads.utils.reflection.helpers;
import de.likewhat.customheads.CustomHeads;
import de.likewhat.customheads.utils.reflection.helpers.collections.ReflectionClassCollection;
import de.likewhat.customheads.utils.reflection.helpers.collections.ReflectionMethodCollection;
import org.bukkit.Bukkit;
import org.bukkit.inventory.ItemStack;
import java.lang.reflect.InvocationTargetException;
@ -9,12 +10,6 @@ import java.util.logging.Level;
public class ItemNBTUtils {
public static final Class<?> MINECRAFT_ITEMSTACK_CLASS;
static {
MINECRAFT_ITEMSTACK_CLASS = ReflectionUtils.getMCServerClassByName("ItemStack", "world.item");
}
public static Object asNMSCopy(ItemStack item) {
try {
return ReflectionUtils.getCBClass("inventory.CraftItemStack").getMethod("asNMSCopy", ItemStack.class).invoke(null, item);
@ -26,7 +21,7 @@ public class ItemNBTUtils {
public static ItemStack asBukkitCopy(Object itemInstance) {
try {
return (ItemStack) ReflectionUtils.getCBClass("inventory.CraftItemStack").getMethod("asBukkitCopy", MINECRAFT_ITEMSTACK_CLASS).invoke(null, itemInstance);
return (ItemStack) ReflectionUtils.getCBClass("inventory.CraftItemStack").getMethod("asBukkitCopy", ReflectionClassCollection.MINECRAFT_ITEMSTACK_CLASS).invoke(null, itemInstance);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
}
@ -40,29 +35,35 @@ public class ItemNBTUtils {
return ReflectionMethodCollection.ITEMSTACK_HASTAG.invokeOn(nmsCopy);
}
} catch (Exception e) {
Bukkit.getLogger().log(Level.WARNING, "Failed to check NBT from Item", e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to check NBT from Item", e);
}
return false;
}
public static Object getTagFromItem(ItemStack itemStack) {
if(!hasNBTTag(itemStack)) {
return getTagFromItem(itemStack, false);
}
public static Object getTagFromItem(ItemStack itemStack, boolean force) {
if(!force && !hasNBTTag(itemStack)) {
return NBTTagUtils.createInstance(NBTTagUtils.NBTType.COMPOUND);
}
try {
Object nmsCopy = ItemNBTUtils.asNMSCopy(itemStack);
return ReflectionMethodCollection.ITEMSTACK_GETTAG.invokeOn(nmsCopy);
} catch(Exception e) {
Bukkit.getLogger().log(Level.WARNING, "Failed to get NBT from Item", e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to get NBT from Item", e);
}
return null;
}
public static void setTagOnItem(Object item, Object nbt) {
try {
ReflectionMethodCollection.ITEMSTACK_SETTAG.invokeOn(item, nbt);
} catch(Exception e) {
Bukkit.getLogger().log(Level.WARNING, "Failed to update NBT of Item", e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to update NBT of Item", e);
}
}
}

View File

@ -7,23 +7,17 @@ package de.likewhat.customheads.utils.reflection.helpers;
* created on 17.12.2019 at 23:29
*/
import de.likewhat.customheads.CustomHeads;
import de.likewhat.customheads.utils.reflection.helpers.collections.ReflectionMethodCollection;
import org.bukkit.Bukkit;
import lombok.Getter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.logging.Level;
public class NBTTagUtils {
public static final Class<?> NBTBASE_CLASS;
static {
NBTBASE_CLASS = ReflectionUtils.getMCServerClassByName("NBTBase", "nbt");
}
public static void addObjectToNBTList(Object list, Object objectToAdd) {
try {
if(Version.getCurrentVersion().isOlderThan(ReflectionMethodCollection.NBT_TAGLIST_ADD_V1141.getFrom())) {
@ -32,28 +26,19 @@ public class NBTTagUtils {
ReflectionMethodCollection.NBT_TAGLIST_ADD.invokeOn(list, ReflectionMethodCollection.NBT_TAGLIST_SIZE.invokeOn(list), objectToAdd);
}
} catch(IllegalAccessException | InvocationTargetException e) {
Bukkit.getLogger().log(Level.WARNING, "Failed to add Object to NBT List", e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to add Object to NBT List", e);
}
}
public static Class<?> getNBTClass(NBTType nbtType) {
try {
return ReflectionUtils.getMCServerClassByName(nbtType.className, "nbt");
} catch(Exception e) {
Bukkit.getLogger().log(Level.WARNING, "Failed to get NBT Class", e);
}
return null;
}
public static Object createInstance(NBTType nbtType) {
try {
Class<?> clazz = getNBTClass(nbtType);
Class<?> clazz = nbtType.getNBTClass();
if(clazz == null) {
return null;
}
return clazz.newInstance();
} catch(Exception e) {
Bukkit.getLogger().log(Level.WARNING, "Failed to create Instance of " + nbtType.name() + " ("+ nbtType.className + ")", e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to create Instance of " + nbtType.name() + " ("+ nbtType.getClassName() + ")", e);
}
return null;
}
@ -61,12 +46,12 @@ public class NBTTagUtils {
// Don't ask what I did here. It works for what I need it to do and it didn't break anything... yet
public static <T> Object createInstance(NBTType nbtType, T newInstanceObject) {
try {
Class<?> clazz = getNBTClass(nbtType);
Class<?> clazz = nbtType.getNBTClass();
if(clazz == null) {
return null;
}
Object instance = null;
// Just return an new empty Instance if the Object is null
// Just return a new empty Instance if the Object is null
if(newInstanceObject == null) {
return clazz.newInstance();
}
@ -78,16 +63,17 @@ public class NBTTagUtils {
// Newer Versions use the a Method to initialize an Instance
instance = clazz.getMethod("a", newInstanceObject.getClass()).invoke(null, newInstanceObject);
} catch(NoSuchMethodException e2) {
Bukkit.getLogger().log(Level.WARNING, "Failed to initialize Instance of " + clazz.getCanonicalName());
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to initialize Instance of " + clazz.getCanonicalName());
}
}
return instance;
} catch(Exception e) {
Bukkit.getLogger().log(Level.WARNING, "Failed to create Instance of " + nbtType.name() + " ("+ nbtType.className + ")", e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to create Instance of " + nbtType.name() + " ("+ nbtType.getClassName() + ")", e);
}
return null;
}
@Getter
public enum NBTType {
END(0, "NBTTagEnd"),
BYTE(1, "NBTTagByte"),
@ -102,14 +88,23 @@ public class NBTTagUtils {
COMPOUND(10, "NBTTagCompound"),
INTEGER_LIST(11, "NBTTagIntArray");
public final int id;
public final String className;
private final int id;
private final String className;
NBTType(int id, String className) {
this.id = id;
this.className = className;
}
public Class<?> getNBTClass() {
try {
return ReflectionUtils.getMCServerClassByName(this.className, "nbt");
} catch(Exception e) {
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to get NBT Class", e);
}
return null;
}
public static NBTType getById(int id) {
return Arrays.stream(values()).filter(nbtType -> nbtType.id == id).findFirst().orElse(null);
}

View File

@ -1,9 +1,11 @@
package de.likewhat.customheads.utils.reflection.helpers;
import de.likewhat.customheads.CustomHeads;
import org.bukkit.Bukkit;
import de.likewhat.customheads.utils.LoggingUtils;
import de.likewhat.customheads.utils.reflection.helpers.collections.ReflectionMethodCollection;
import org.bukkit.entity.Player;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@ -14,10 +16,10 @@ import java.util.logging.Level;
public class ReflectionUtils {
public static final int MC_VERSION;
private static final HashMap<String, Class<?>> cachedClasses = new HashMap<>();
private static final HashMap<String, Class<?>> CACHED_CLASSES = new HashMap<>();
static {
MC_VERSION = Integer.parseInt(CustomHeads.version.split("_")[1]);
MC_VERSION = Integer.parseInt(Version.getRawVersion().split("_")[1]);
}
/**
@ -28,26 +30,35 @@ public class ReflectionUtils {
* @return true when the Field was modified successfully, false if not
*/
public static boolean setField(Object objectInstance, String fieldName, Object newValue) {
boolean wasAccessible = true;
Field fieldToModify = null;
try {
Class<?> sourceClass = objectInstance.getClass();
Field fieldToModify;
try {
fieldToModify = sourceClass.getField(fieldName);
} catch(NoSuchFieldException e) {
fieldToModify = sourceClass.getDeclaredField(fieldName);
}
wasAccessible = fieldToModify.isAccessible();
return setField(objectInstance, fieldToModify, newValue);
} catch(NoSuchFieldException e) {
e.printStackTrace();
}
return false;
}
public static boolean setField(Object objectInstance, Field field, Object newValue) {
boolean wasAccessible = field.isAccessible();
try {
if(!wasAccessible) {
fieldToModify.setAccessible(true);
field.setAccessible(true);
}
fieldToModify.set(objectInstance, newValue);
field.set(objectInstance, newValue);
return true;
} catch(Exception e) {
e.printStackTrace();
return false;
} finally {
if(fieldToModify != null && !wasAccessible) {
fieldToModify.setAccessible(false);
if(!wasAccessible) {
field.setAccessible(false);
}
}
}
@ -72,6 +83,26 @@ public class ReflectionUtils {
return result;
}
/**
* Tries to get a Constructor by its Name (tries Normal Constructors first and then Declared Constructors)
* @param clazz The Class that has the Constructor
* @param paramTypes The Constructor Parameters
* @return Constructor from the given Class and Parameter Types
*/
public static Constructor<?> getConstructorDynamic(Class<?> clazz, Class<?>... paramTypes) throws NoSuchMethodException {
Constructor<?> result;
try {
result = clazz.getConstructor(paramTypes);
} catch (NoSuchMethodException noConstructor) {
try {
result = clazz.getDeclaredConstructor(paramTypes);
} catch(NoSuchMethodException noDeclaredConstructor) {
throw new NoSuchMethodException("Failed to find Constructor for " + LoggingUtils.methodLikeString(clazz.getCanonicalName(), paramTypes) + " in either declared or non-declared State");
}
}
return result;
}
/**
* Check whether the given Method exists or not
* @param clazz The Class where the Method could be
@ -103,7 +134,7 @@ public class ReflectionUtils {
try {
return clazz.getMethod(methodName, params);
} catch(NoSuchMethodException e) {
throw new NoSuchMethodException("Failed to get Method from Class " + clazz.getCanonicalName() + ": " + e.getMessage());
throw new NoSuchMethodException("Failed to get Method from Class " + clazz.getCanonicalName());
}
}
@ -116,7 +147,15 @@ public class ReflectionUtils {
public static Object invokeMethod(Method method, Object object, Object... params) throws InvocationTargetException, IllegalAccessException {
Objects.requireNonNull(method);
Objects.requireNonNull(object);
return method.invoke(object, params);
boolean wasAccessible = method.isAccessible();
if(!wasAccessible) {
method.setAccessible(true);
}
try {
return method.invoke(object, params);
} finally {
method.setAccessible(wasAccessible);
}
}
/**
@ -126,10 +165,10 @@ public class ReflectionUtils {
* @return Enum Constant by given Name
*/
public static Enum<?> getEnumConstant(Class<?> clazz, String enumName) {
enumName = enumName.toUpperCase();
// enumName = enumName.toUpperCase();
try {
for (Object eenum : clazz.getEnumConstants()) {
if (eenum.getClass().getMethod("name").invoke(eenum).equals(enumName)) {
if (clazz.getMethod("name").invoke(eenum).equals(enumName)) {
return (Enum<?>) eenum;
}
}
@ -147,57 +186,49 @@ public class ReflectionUtils {
} else {
connection = playerHandle.getClass().getField("playerConnection").get(playerHandle);
}
connection.getClass().getMethod("sendPacket", ReflectionUtils.getMCServerClassByName("Packet", "network.protocol")).invoke(connection, packet);
ReflectionMethodCollection.PLAYER_SEND_PACKET.invokeOn(connection, packet);
// connection.getClass().getMethod("sendPacket", ReflectionUtils.getMCServerClassByName("Packet", "network.protocol")).invoke(connection, packet);
}
public static Class<?> getMCServerClassByName(String className, boolean useVersionTag) {
if (className.equals("ChatSerializer") && Version.getCurrentVersion() == Version.V1_8_R1) {
className = "IChatBaseComponent$ChatSerializer";
}
String classPath;
if(useVersionTag) {
classPath = "net.minecraft.server." + CustomHeads.version + "." + className;
} else {
classPath = "net.minecraft." + className;
}
return checkCached(classPath);
public static Class<?> getMCServerClassByName(String className) {
return getMCServerClassByName(className, null);
}
public static Class<?> getMCServerClassByName(String className, String... alternativePrefix) {
if (className.equals("ChatSerializer") && Version.getCurrentVersion() == Version.V1_8_R1) {
public static Class<?> getMCServerClassByName(String className, String alternativePrefix) {
if (className.equals("ChatSerializer") && (Version.getCurrentVersion() == Version.V1_8_R1 || Version.getCurrentVersion().isNewerThan(Version.V1_17_R1))) {
className = "IChatBaseComponent$ChatSerializer";
}
String classPath;
if(MC_VERSION >= 17) {
String altPrefix = "";
if(alternativePrefix != null && alternativePrefix.length > 0) {
altPrefix = alternativePrefix[0] + ".";
if(alternativePrefix != null) {
altPrefix = alternativePrefix + ".";
}
classPath = "net.minecraft." + altPrefix + className;
} else {
classPath = "net.minecraft.server." + CustomHeads.version + "." + className;
classPath = "net.minecraft.server." + Version.getRawVersion() + "." + className;
}
return checkCached(classPath);
return checkCachedClassname(classPath);
}
public static Class<?> getClassByName(String className) {
return checkCached(className);
return checkCachedClassname(className);
}
public static Class<?> getCBClass(String className) {
return checkCached("org.bukkit.craftbukkit." + CustomHeads.version + "." + className);
return checkCachedClassname("org.bukkit.craftbukkit." + Version.getRawVersion() + "." + className);
}
private static Class<?> checkCached(String className) {
if(cachedClasses.containsKey(className)) {
return cachedClasses.get(className);
private static Class<?> checkCachedClassname(String className) {
if(CACHED_CLASSES.containsKey(className)) {
return CACHED_CLASSES.get(className);
} else {
try {
Class<?> clazz = Class.forName(className);
cachedClasses.put(className, clazz);
CACHED_CLASSES.put(className, clazz);
return clazz;
} catch(Exception e) {
Bukkit.getLogger().log(Level.SEVERE, "Failed to cache Class", e);
CustomHeads.getPluginLogger().log(Level.SEVERE, "Failed to cache Class", e);
}
}
return null;

View File

@ -1,6 +1,7 @@
package de.likewhat.customheads.utils.reflection.helpers;
import de.likewhat.customheads.CustomHeads;
import lombok.Getter;
import org.bukkit.Bukkit;
import java.util.Arrays;
@ -15,11 +16,14 @@ public enum Version {
V1_13_R1(1131), V1_13_R2(1132),
V1_14_R1(1141),
V1_15_R1(1151),
V1_16_R1(1161), V1_16_R3(1163),
V1_16_R1(1161), V1_16_R2(1162), V1_16_R3(1163),
V1_17_R1(1171),
V1_18_R1(1181),
V1_18_R1(1181), V1_18_R2(1182),
LATEST(99999999);
private static final String packet = Bukkit.getServer().getClass().getPackage().getName();
@Getter private static final String rawVersion = packet.substring(packet.lastIndexOf('.') + 1);
public final int versionValue;
Version(int versionValue) {
@ -44,7 +48,7 @@ public enum Version {
if(currentVersion != null) {
return currentVersion;
}
currentVersion = fromValue(Integer.parseInt(CustomHeads.version.replaceAll("[^0-9]+", "")));
currentVersion = fromValue(Integer.parseInt(rawVersion.replaceAll("\\D+", "")));
return currentVersion;
}
}

View File

@ -1,6 +1,18 @@
package de.likewhat.customheads.utils.reflection.helpers.collections;
// TODO: Add some Classes
// Don't know if I'll need it anyway but just in case
import de.likewhat.customheads.utils.reflection.helpers.ReflectionUtils;
public class ReflectionClassCollection {
public static final Class<?> PACKET_PLAYOUT_CHAT = ReflectionUtils.getMCServerClassByName("PacketPlayOutChat", "network.protocol.game");
public static final Class<?> ICHAT_BASE_COMPONENT = ReflectionUtils.getMCServerClassByName("IChatBaseComponent", "network.chat");
public static final Class<?> CHAT_MESSAGE_TYPE = ReflectionUtils.getMCServerClassByName("ChatMessageType", "network.chat");
public static final Class<?> MINECRAFT_ITEMSTACK_CLASS = ReflectionUtils.getMCServerClassByName("ItemStack", "world.item");
public static final Class<?> NBTBASE_CLASS = ReflectionUtils.getMCServerClassByName("NBTBase", "nbt");
public static final Class<?> CONTAINER_ANVIL = ReflectionUtils.getMCServerClassByName("ContainerAnvil", "world.inventory");
public static final Class<?> PACKET_PLAY_OUT_OPEN_WINDOW = ReflectionUtils.getMCServerClassByName("PacketPlayOutOpenWindow", "network.protocol.game");
public static final Class<?> CONTAINER = ReflectionUtils.getMCServerClassByName("Container", "world.inventory");
}

View File

@ -0,0 +1,13 @@
package de.likewhat.customheads.utils.reflection.helpers.collections;
import de.likewhat.customheads.utils.reflection.helpers.Version;
import de.likewhat.customheads.utils.reflection.helpers.wrappers.ConstructorWrapper;
import java.util.UUID;
public class ReflectionConstructorCollection {
public static final ConstructorWrapper<?> PACKET_PLAYOUT_CHAT_V1161 = new ConstructorWrapper<>(Version.V1_16_R1, null, ReflectionClassCollection.PACKET_PLAYOUT_CHAT, ReflectionClassCollection.ICHAT_BASE_COMPONENT, ReflectionClassCollection.CHAT_MESSAGE_TYPE, UUID.class);
public static final ConstructorWrapper<?> PACKET_PLAYOUT_CHAT = new ConstructorWrapper<>(null, Version.V1_15_R1, ReflectionClassCollection.PACKET_PLAYOUT_CHAT, PACKET_PLAYOUT_CHAT_V1161, ReflectionClassCollection.ICHAT_BASE_COMPONENT);
}

View File

@ -1,46 +1,56 @@
package de.likewhat.customheads.utils.reflection.helpers.collections;
import de.likewhat.customheads.utils.reflection.helpers.ItemNBTUtils;
import com.mojang.authlib.GameProfile;
import de.likewhat.customheads.utils.reflection.helpers.NBTTagUtils;
import de.likewhat.customheads.utils.reflection.helpers.ReflectionUtils;
import de.likewhat.customheads.utils.reflection.helpers.Version;
import de.likewhat.customheads.utils.reflection.helpers.wrappers.MethodWrapper;
public class ReflectionMethodCollection {
// NBTTagCompound
public static final MethodWrapper<Object> NBT_TAGCOMPOUND_GET_V1181 = new MethodWrapper<>(Version.V1_18_R1, null, "c", NBTTagUtils.getNBTClass(NBTTagUtils.NBTType.COMPOUND), String.class);
public static final MethodWrapper<Object> NBT_TAGCOMPOUND_GET = new MethodWrapper<>(null, Version.V1_17_R1, "get", NBTTagUtils.getNBTClass(NBTTagUtils.NBTType.COMPOUND), NBT_TAGCOMPOUND_GET_V1181, String.class);
public static final MethodWrapper<Object> NBT_TAGCOMPOUND_GET_V1181 = new MethodWrapper<>(Version.V1_18_R1, null, "c", NBTTagUtils.NBTType.COMPOUND.getNBTClass(), String.class);
public static final MethodWrapper<Object> NBT_TAGCOMPOUND_GET = new MethodWrapper<>(null, Version.V1_17_R1, "get", NBTTagUtils.NBTType.COMPOUND.getNBTClass(), NBT_TAGCOMPOUND_GET_V1181, String.class);
public static final MethodWrapper<Object> NBT_TAGCOMPOUND_GETCOMPOUND_V1181 = new MethodWrapper<>(Version.V1_18_R1, null, "p", NBTTagUtils.getNBTClass(NBTTagUtils.NBTType.COMPOUND), String.class);
public static final MethodWrapper<Object> NBT_TAGCOMPOUND_GETCOMPOUND = new MethodWrapper<>(null, Version.V1_17_R1, "getCompound", NBTTagUtils.getNBTClass(NBTTagUtils.NBTType.COMPOUND), NBT_TAGCOMPOUND_GETCOMPOUND_V1181, String.class);
public static final MethodWrapper<Object> NBT_TAGCOMPOUND_GETCOMPOUND_V1181 = new MethodWrapper<>(Version.V1_18_R1, null, "p", NBTTagUtils.NBTType.COMPOUND.getNBTClass(), String.class);
public static final MethodWrapper<Object> NBT_TAGCOMPOUND_GETCOMPOUND = new MethodWrapper<>(null, Version.V1_17_R1, "getCompound", NBTTagUtils.NBTType.COMPOUND.getNBTClass(), NBT_TAGCOMPOUND_GETCOMPOUND_V1181, String.class);
public static final MethodWrapper<Object> NBT_TAGCOMPOUND_GETLIST_V1181 = new MethodWrapper<>(Version.V1_18_R1, null, "c", NBTTagUtils.getNBTClass(NBTTagUtils.NBTType.COMPOUND), String.class, int.class);
public static final MethodWrapper<Object> NBT_TAGCOMPOUND_GETLIST = new MethodWrapper<>(null, Version.V1_17_R1, "getList", NBTTagUtils.getNBTClass(NBTTagUtils.NBTType.COMPOUND), NBT_TAGCOMPOUND_GETLIST_V1181, String.class, int.class);
public static final MethodWrapper<Object> NBT_TAGCOMPOUND_GETLIST_V1181 = new MethodWrapper<>(Version.V1_18_R1, null, "c", NBTTagUtils.NBTType.COMPOUND.getNBTClass(), String.class, int.class);
public static final MethodWrapper<Object> NBT_TAGCOMPOUND_GETLIST = new MethodWrapper<>(null, Version.V1_17_R1, "getList", NBTTagUtils.NBTType.COMPOUND.getNBTClass(), NBT_TAGCOMPOUND_GETLIST_V1181, String.class, int.class);
public static final MethodWrapper<Void> NBT_TAGCOMPOUND_SET_V1181 = new MethodWrapper<>(Version.V1_18_R1, null, "a", NBTTagUtils.getNBTClass(NBTTagUtils.NBTType.COMPOUND), String.class, NBTTagUtils.NBTBASE_CLASS);
public static final MethodWrapper<Void> NBT_TAGCOMPOUND_SET = new MethodWrapper<>(null, Version.V1_17_R1, "set", NBTTagUtils.getNBTClass(NBTTagUtils.NBTType.COMPOUND), NBT_TAGCOMPOUND_SET_V1181, String.class, NBTTagUtils.NBTBASE_CLASS);
public static final MethodWrapper<Void> NBT_TAGCOMPOUND_SET_V1181 = new MethodWrapper<>(Version.V1_18_R1, null, "a", NBTTagUtils.NBTType.COMPOUND.getNBTClass(), String.class, ReflectionClassCollection.NBTBASE_CLASS);
public static final MethodWrapper<Void> NBT_TAGCOMPOUND_SET = new MethodWrapper<>(null, Version.V1_17_R1, "set", NBTTagUtils.NBTType.COMPOUND.getNBTClass(), NBT_TAGCOMPOUND_SET_V1181, String.class, ReflectionClassCollection.NBTBASE_CLASS);
public static final MethodWrapper<Boolean> NBT_TAGCOMPOUND_HASKEY_V1181 = new MethodWrapper<>(Version.V1_18_R1, null, "e", NBTTagUtils.getNBTClass(NBTTagUtils.NBTType.COMPOUND), String.class);
public static final MethodWrapper<Boolean> NBT_TAGCOMPOUND_HASKEY = new MethodWrapper<>(null, Version.V1_17_R1, "hasKey", NBTTagUtils.getNBTClass(NBTTagUtils.NBTType.COMPOUND), NBT_TAGCOMPOUND_HASKEY_V1181, String.class);
public static final MethodWrapper<Boolean> NBT_TAGCOMPOUND_HASKEY_V1181 = new MethodWrapper<>(Version.V1_18_R1, null, "e", NBTTagUtils.NBTType.COMPOUND.getNBTClass(), String.class);
public static final MethodWrapper<Boolean> NBT_TAGCOMPOUND_HASKEY = new MethodWrapper<>(null, Version.V1_17_R1, "hasKey", NBTTagUtils.NBTType.COMPOUND.getNBTClass(), NBT_TAGCOMPOUND_HASKEY_V1181, String.class);
// NBTTagList
public static final MethodWrapper<Void> NBT_TAGLIST_ADD_V1181 = new MethodWrapper<>(Version.V1_8_R1, null, "b", NBTTagUtils.getNBTClass(NBTTagUtils.NBTType.LIST), int.class, NBTTagUtils.NBTBASE_CLASS);
public static final MethodWrapper<Void> NBT_TAGLIST_ADD_V1141 = new MethodWrapper<>(Version.V1_14_R1, Version.V1_17_R1, "add", NBTTagUtils.getNBTClass(NBTTagUtils.NBTType.LIST), NBT_TAGLIST_ADD_V1181, int.class, NBTTagUtils.NBTBASE_CLASS);
public static final MethodWrapper<Void> NBT_TAGLIST_ADD = new MethodWrapper<>(null, Version.V1_13_R1, "add", NBTTagUtils.getNBTClass(NBTTagUtils.NBTType.LIST), NBT_TAGLIST_ADD_V1141, NBTTagUtils.NBTBASE_CLASS);
public static final MethodWrapper<Void> NBT_TAGLIST_ADD_V1181 = new MethodWrapper<>(Version.V1_18_R1, null, "b", NBTTagUtils.NBTType.LIST.getNBTClass(), int.class, ReflectionClassCollection.NBTBASE_CLASS);
public static final MethodWrapper<Void> NBT_TAGLIST_ADD_V1141 = new MethodWrapper<>(Version.V1_14_R1, Version.V1_17_R1, "add", NBTTagUtils.NBTType.LIST.getNBTClass(), NBT_TAGLIST_ADD_V1181, int.class, ReflectionClassCollection.NBTBASE_CLASS);
public static final MethodWrapper<Void> NBT_TAGLIST_ADD = new MethodWrapper<>(null, Version.V1_13_R2, "add", NBTTagUtils.NBTType.LIST.getNBTClass(), NBT_TAGLIST_ADD_V1141, ReflectionClassCollection.NBTBASE_CLASS);
public static final MethodWrapper<Integer> NBT_TAGLIST_SIZE = new MethodWrapper<>(null, null, "size", NBTTagUtils.getNBTClass(NBTTagUtils.NBTType.LIST));
public static final MethodWrapper<Integer> NBT_TAGLIST_SIZE = new MethodWrapper<>(null, null, "size", NBTTagUtils.NBTType.LIST.getNBTClass());
public static final MethodWrapper<String> NBT_TAGLIST_GETSTRING_V1181 = new MethodWrapper<>(Version.V1_18_R1, null, "j", NBTTagUtils.getNBTClass(NBTTagUtils.NBTType.LIST), int.class);
public static final MethodWrapper<String> NBT_TAGLIST_GETSTRING = new MethodWrapper<>(null, Version.V1_17_R1, "getString", NBTTagUtils.getNBTClass(NBTTagUtils.NBTType.LIST), NBT_TAGLIST_GETSTRING_V1181, int.class);
public static final MethodWrapper<String> NBT_TAGLIST_GETSTRING_V1181 = new MethodWrapper<>(Version.V1_18_R1, null, "j", NBTTagUtils.NBTType.LIST.getNBTClass(), int.class);
public static final MethodWrapper<String> NBT_TAGLIST_GETSTRING = new MethodWrapper<>(null, Version.V1_17_R1, "getString", NBTTagUtils.NBTType.LIST.getNBTClass(), NBT_TAGLIST_GETSTRING_V1181, int.class);
// ItemStack
public static final MethodWrapper<Boolean> ITEMSTACK_HASTAG_V1181 = new MethodWrapper<>(Version.V1_18_R1, null, "r", ItemNBTUtils.MINECRAFT_ITEMSTACK_CLASS);
public static final MethodWrapper<Boolean> ITEMSTACK_HASTAG = new MethodWrapper<>(null, Version.V1_17_R1, "hasTag", ItemNBTUtils.MINECRAFT_ITEMSTACK_CLASS, ITEMSTACK_HASTAG_V1181);
public static final MethodWrapper<Boolean> ITEMSTACK_HASTAG_V1182 = new MethodWrapper<>(Version.V1_18_R2, null, "s", ReflectionClassCollection.MINECRAFT_ITEMSTACK_CLASS);
public static final MethodWrapper<Boolean> ITEMSTACK_HASTAG_V1181 = new MethodWrapper<>(Version.V1_18_R1, Version.V1_18_R1, "r", ReflectionClassCollection.MINECRAFT_ITEMSTACK_CLASS, ITEMSTACK_HASTAG_V1182);
public static final MethodWrapper<Boolean> ITEMSTACK_HASTAG = new MethodWrapper<>(null, Version.V1_17_R1, "hasTag", ReflectionClassCollection.MINECRAFT_ITEMSTACK_CLASS, ITEMSTACK_HASTAG_V1181);
public static final MethodWrapper<Object> ITEMSTACK_GETTAG_V1181 = new MethodWrapper<>(Version.V1_18_R1, null, "t", ItemNBTUtils.MINECRAFT_ITEMSTACK_CLASS);
public static final MethodWrapper<Object> ITEMSTACK_GETTAG = new MethodWrapper<>(null, Version.V1_17_R1, "getTag", ItemNBTUtils.MINECRAFT_ITEMSTACK_CLASS, ITEMSTACK_GETTAG_V1181);
public static final MethodWrapper<Object> ITEMSTACK_GETTAG_V1182 = new MethodWrapper<>(Version.V1_18_R2, null, "t", ReflectionClassCollection.MINECRAFT_ITEMSTACK_CLASS);
public static final MethodWrapper<Object> ITEMSTACK_GETTAG_V1181 = new MethodWrapper<>(Version.V1_18_R1, Version.V1_18_R1, "s", ReflectionClassCollection.MINECRAFT_ITEMSTACK_CLASS, ITEMSTACK_GETTAG_V1182);
public static final MethodWrapper<Object> ITEMSTACK_GETTAG = new MethodWrapper<>(null, Version.V1_17_R1, "getTag", ReflectionClassCollection.MINECRAFT_ITEMSTACK_CLASS, ITEMSTACK_GETTAG_V1181);
public static final MethodWrapper<Void> ITEMSTACK_SETTAG_V1181 = new MethodWrapper<>(Version.V1_18_R1, null, "c", ItemNBTUtils.MINECRAFT_ITEMSTACK_CLASS, NBTTagUtils.getNBTClass(NBTTagUtils.NBTType.COMPOUND));
public static final MethodWrapper<Void> ITEMSTACK_SETTAG = new MethodWrapper<>(null, Version.V1_17_R1, "setTag", ItemNBTUtils.MINECRAFT_ITEMSTACK_CLASS, ITEMSTACK_SETTAG_V1181, NBTTagUtils.getNBTClass(NBTTagUtils.NBTType.COMPOUND));
public static final MethodWrapper<Void> ITEMSTACK_SETTAG_V1181 = new MethodWrapper<>(Version.V1_18_R1, null, "c", ReflectionClassCollection.MINECRAFT_ITEMSTACK_CLASS, NBTTagUtils.NBTType.COMPOUND.getNBTClass());
public static final MethodWrapper<Void> ITEMSTACK_SETTAG = new MethodWrapper<>(null, Version.V1_17_R1, "setTag", ReflectionClassCollection.MINECRAFT_ITEMSTACK_CLASS, ITEMSTACK_SETTAG_V1181, NBTTagUtils.NBTType.COMPOUND.getNBTClass());
// GameProfile
public static final MethodWrapper<Object> GAMEPROFILE_SERIALIZE = new MethodWrapper<>(Version.V1_18_R1, null, "a", ReflectionUtils.getMCServerClassByName("GameProfileSerializer", "nbt"), NBTTagUtils.NBTType.COMPOUND.getNBTClass(), GameProfile.class);
// Player Packet Handling
public static final MethodWrapper<Void> PLAYER_SEND_PACKET_V1181 = new MethodWrapper<>(Version.V1_18_R1, null, "a", ReflectionUtils.getMCServerClassByName("PlayerConnection", "server.network"), ReflectionUtils.getMCServerClassByName("Packet", "network.protocol"));
public static final MethodWrapper<Void> PLAYER_SEND_PACKET = new MethodWrapper<>(null, Version.V1_17_R1, "sendPacket", ReflectionUtils.getMCServerClassByName("PlayerConnection", "server.network"), PLAYER_SEND_PACKET_V1181, ReflectionUtils.getMCServerClassByName("Packet", "network.protocol"));
}

View File

@ -0,0 +1,33 @@
package de.likewhat.customheads.utils.reflection.helpers.wrappers;
import de.likewhat.customheads.CustomHeads;
import de.likewhat.customheads.utils.LoggingUtils;
import de.likewhat.customheads.utils.reflection.helpers.ReflectionUtils;
import de.likewhat.customheads.utils.reflection.helpers.Version;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
public class ConstructorWrapper<T> extends WrapperBase<ConstructorWrapper<T>, Constructor<?>> {
public ConstructorWrapper(Version from, Version to, Class<?> clazz, Class<?>... paramTypes) {
this(from, to, clazz, null, paramTypes);
}
public ConstructorWrapper(Version from, Version to, Class<?> clazz, ConstructorWrapper<T> replacedBy, Class<?>... paramTypes) {
super(from, to, clazz, paramTypes, replacedBy);
}
protected Constructor<?> resolveValue() throws Throwable {
return ReflectionUtils.getConstructorDynamic(super.targetClass, super.params);
}
protected void errorHandler(Throwable throwable) {
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to resolve Constructor for " + LoggingUtils.methodLikeString(super.targetClass.getSimpleName(), super.params));
}
public T construct(Object... params) throws IllegalAccessException, InvocationTargetException, InstantiationException {
return (T) resolve().newInstance(params);
}
}

View File

@ -1,73 +1,36 @@
package de.likewhat.customheads.utils.reflection.helpers.wrappers;
import de.likewhat.customheads.CustomHeads;
import de.likewhat.customheads.utils.LoggingUtils;
import de.likewhat.customheads.utils.reflection.helpers.ReflectionUtils;
import de.likewhat.customheads.utils.reflection.helpers.Version;
import lombok.Getter;
import org.bukkit.Bukkit;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Level;
public class MethodWrapper<T> {
public class MethodWrapper<T> extends WrapperBase<MethodWrapper<T>, Method> {
@Getter private Version from;
@Getter private Version to;
private String methodName;
private Class<?>[] params;
private Class<?> targetClass;
private Method targetMethod;
private MethodWrapper replacedBy;
public MethodWrapper(Version from, Version to, String methodName, MinecraftServerClassWrapper clazz, Class<?>... params) {
this(from, to, methodName, clazz, null, params);
}
private final String methodName;
public MethodWrapper(Version from, Version to, String methodName, Class<?> clazz, Class<?>... params) {
this(from, to, methodName, clazz, null, params);
}
public MethodWrapper(Version from, Version to, String methodName, MinecraftServerClassWrapper classWrapper, MethodWrapper replacedBy, Class<?>... params) {
this(from, to, methodName, classWrapper.getClazz(), replacedBy, params);
}
public MethodWrapper(Version from, Version to, String methodName, Class<?> clazz, MethodWrapper replacedBy, Class<?>... params) {
this.from = from == null ? Version.OLDEST : from;
this.to = to == null ? Version.LATEST : to;
public MethodWrapper(Version from, Version to, String methodName, Class<?> clazz, MethodWrapper<T> replacedBy, Class<?>... params) {
super(from, to, clazz, params, replacedBy);
this.methodName = methodName;
this.replacedBy = replacedBy;
this.params = params;
this.targetClass = clazz;
}
public Method getMethod() {
if(targetMethod != null) {
return targetMethod;
}
Version current = Version.getCurrentVersion();
if(current.isOlderThan(from)) {
throw new UnsupportedOperationException("Version " + current.name() + " doesn't Support this Method yet (from " + from.name() + ")");
} else if(current.isNewerThan(to)) {
if(replacedBy == null) {
throw new UnsupportedOperationException("Version " + current.name() + " doesn't Support this Method yet (from " + from.name() + ")");
} else {
return replacedBy.getMethod();
}
} else {
try {
this.targetMethod = ReflectionUtils.getMethod(methodName, targetClass, params);
return targetMethod;
} catch (NoSuchMethodException e) {
Bukkit.getLogger().log(Level.SEVERE, "Failed to get Method: " + e.getMessage(), e);
}
}
return null;
protected Method resolveValue() throws Throwable {
return ReflectionUtils.getMethod(methodName, targetClass, params);
}
protected void errorHandler(Throwable throwable) {
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to get Method for " + LoggingUtils.methodLikeString(this.methodName, super.params));
}
public T invokeOn(Object object, Object... params) throws InvocationTargetException, IllegalAccessException {
return (T) getMethod().invoke(object, params);
return (T) resolve().invoke(object, params);
}
}

View File

@ -1,47 +0,0 @@
package de.likewhat.customheads.utils.reflection.helpers.wrappers;
import de.likewhat.customheads.utils.reflection.helpers.ReflectionUtils;
import de.likewhat.customheads.utils.reflection.helpers.Version;
public class MinecraftServerClassWrapper {
private Version from;
private Version to;
private String className;
private boolean newMapping; // Whether or not to use the Versioning Tag or not (net.minecraft.server.v1_2_3.this.is.a.package or net.minecraft.server.this.is.a.package)
private MinecraftServerClassWrapper replacedBy;
private Class<?> targetClass;
public MinecraftServerClassWrapper(Version from, Version to, String className) {
this(from, to, className, null);
}
public MinecraftServerClassWrapper(Version from, Version to, String className, MinecraftServerClassWrapper replacedBy) {
this.from = from == null ? Version.OLDEST : from;
this.to = to == null ? Version.LATEST : to;
this.className = className;
this.newMapping = Version.getCurrentVersion().isNewerThan(Version.V1_16_R1);
this.replacedBy = replacedBy;
}
public Class<?> getClazz() {
if(targetClass != null) {
return targetClass;
}
Version current = Version.getCurrentVersion();
if(current.versionValue < from.versionValue) {
throw new UnsupportedOperationException("Version " + current.name() + " doesn't Support this Method yet (from " + from.name() + ")");
} else if(current.versionValue > to.versionValue) {
if(targetClass == null && to != Version.LATEST) {
throw new UnsupportedOperationException("This Method hasn't been implemented yet for " + current.name());
} else {
return replacedBy.getClazz();
}
} else {
targetClass = ReflectionUtils.getMCServerClassByName(className, !newMapping);
return targetClass;
}
}
}

View File

@ -0,0 +1,73 @@
package de.likewhat.customheads.utils.reflection.helpers.wrappers;
import de.likewhat.customheads.CustomHeads;
import de.likewhat.customheads.utils.LoggingUtils;
import de.likewhat.customheads.utils.reflection.helpers.Version;
import lombok.Getter;
import java.util.logging.Level;
/**
* Base Class to use for different Wrappers
* @param <M> The Class itself (used for Constructors replacedBy)
* @param <T> The Value that {@link de.likewhat.customheads.utils.reflection.helpers.wrappers.WrapperBase#resolve()} should return
*/
public abstract class WrapperBase<M extends WrapperBase<M, T>, T> {
@Getter
protected Version from;
@Getter
protected Version to;
protected Class<?> targetClass;
protected Class<?>[] params;
protected WrapperBase<M, T> replacedBy;
protected T resolvedValue;
public WrapperBase(Version from, Version to, Class<?> targetClass, Class<?>[] params, WrapperBase<M, T> replacedBy) {
this.from = from == null ? Version.OLDEST : from;
this.to = to == null ? Version.LATEST : to;
if(this.from.isNewerThan(this.to)) {
throw new IllegalArgumentException("From-Version should be older than To-Version");
}
if(this.to.isOlderThan(this.from)) {
throw new IllegalArgumentException("To-Version should be newer than From-Version");
}
this.targetClass = targetClass;
this.params = params;
this.replacedBy = replacedBy;
}
public final T resolve() {
if(resolvedValue != null) {
return resolvedValue;
}
Version current = Version.getCurrentVersion();
if(current.isOlderThan(from)) {
throw new UnsupportedOperationException("Version " + current.name() + " doesn't Support this Method yet (from " + from.name() + ")");
} else if(current.isNewerThan(to)) {
if(replacedBy == null) {
throw new UnsupportedOperationException("This Method hasn't been implemented yet for " + current.name() + " - " + LoggingUtils.methodLikeString(targetClass.getCanonicalName(), params));
} else {
return replacedBy.resolve();
}
} else {
try {
resolvedValue = resolveValue();
if(resolvedValue == null) {
errorHandler(new NullPointerException("Resolved Value is null"));
}
} catch(Throwable e) {
errorHandler(e);
}
return resolvedValue;
}
}
protected abstract T resolveValue() throws Throwable;
protected void errorHandler(Throwable throwable) {
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to resolve Value", throwable);
}
}

View File

@ -1,8 +1,8 @@
package de.likewhat.customheads.utils.updaters;
import com.google.common.io.Files;
import de.likewhat.customheads.CustomHeads;
import de.likewhat.customheads.utils.Utils;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.File;
@ -21,9 +21,9 @@ import java.nio.channels.ReadableByteChannel;
public class AsyncFileDownloader {
private String userAgent = "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko";
private String fileName;
private String path;
private String url;
private final String fileName;
private final String path;
private final String url;
public AsyncFileDownloader(String url, String fileName, String toPath) {
this.url = url;
@ -36,7 +36,7 @@ public class AsyncFileDownloader {
}
public void startDownload(FileDownloaderCallback callback) {
Bukkit.getLogger().info("Downloading " + fileName + "...");
CustomHeads.getPluginLogger().info("Downloading " + fileName + "...");
Utils.runAsync(new BukkitRunnable() {
public void run() {
try {

View File

@ -28,12 +28,12 @@ public class GitHubDownloader {
private static final File downloadDir = new File(CustomHeads.getInstance().getDataFolder(), "downloads");
private static final String GITHUB_REPO_URL = "https://api.github.com/repos/%s/%s";
private static HashMap<String, CachedResponse<JsonElement>> responseCache = new HashMap<>();
private String apiURLFormatted;
private static final HashMap<String, CachedResponse<JsonElement>> RESPONSE_CACHE = new HashMap<>();
private final String apiURLFormatted;
private boolean unzip = false;
private String author;
private String projectName;
private final String author;
private final String projectName;
public GitHubDownloader(String author, String projectName) {
this.author = author;
@ -42,7 +42,7 @@ public class GitHubDownloader {
}
public static void clearCache() {
responseCache.values().removeIf(cachedResponse -> cachedResponse.getCacheTime() - System.currentTimeMillis() > 600000);
RESPONSE_CACHE.values().removeIf(cachedResponse -> cachedResponse.getCacheTime() - System.currentTimeMillis() > 600000);
}
public GitHubDownloader enableAutoUnzipping() {
@ -51,8 +51,8 @@ public class GitHubDownloader {
}
private static void getResponseAsJson(String url, FetchResult<JsonElement> fetchResult, boolean force) {
if (responseCache.containsKey(url) && !force) {
fetchResult.success(responseCache.get(url).getData());
if (RESPONSE_CACHE.containsKey(url) && !force) {
fetchResult.success(RESPONSE_CACHE.get(url).getData());
return;
}
@ -69,7 +69,7 @@ public class GitHubDownloader {
fetchResult.error(new NullPointerException("Release API resopnded with: " + response.getAsJsonObject().get("message").getAsString()));
return;
}
responseCache.put(url, new CachedResponse<>(System.currentTimeMillis(), response));
RESPONSE_CACHE.put(url, new CachedResponse<>(System.currentTimeMillis(), response));
fetchResult.success(response);
} catch (Exception e) {
fetchResult.error(e);
@ -80,7 +80,7 @@ public class GitHubDownloader {
getRateLimit(new FetchResult<JsonObject>() {
public void success(JsonObject rateLimit) {
if(rateLimit.get("remaining").getAsInt() == 0) {
Bukkit.getLogger().info(Utils.GSON_PRETTY.toJson(rateLimit));
CustomHeads.getPluginLogger().info(Utils.GSON_PRETTY.toJson(rateLimit));
fetchResult.error(new RateLimitExceededException(rateLimit.get("reset").getAsLong()));
return;
}
@ -96,14 +96,14 @@ public class GitHubDownloader {
}
if (release == null) {
fetchResult.error(new NullPointerException("Unkown Tag: " + tag));
fetchResult.error(new NullPointerException("Unknown Tag: " + tag));
return;
}
fetchResult.success(release);
}
public void error(Exception exception) {
Bukkit.getLogger().log(Level.WARNING, "Failed to get Release", exception);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to get Release", exception);
}
}, false);
}
@ -124,7 +124,7 @@ public class GitHubDownloader {
AsyncFileDownloader downloader = new AsyncFileDownloader(jsonObject.get("browser_download_url").getAsString(), assetName, downloadDir.getPath());
downloader.startDownload(new AsyncFileDownloader.FileDownloaderCallback() {
public void complete() {
Bukkit.getServer().getConsoleSender().sendMessage(CustomHeads.chPrefix + "Download of " + assetName + " complete.");
Bukkit.getServer().getConsoleSender().sendMessage(CustomHeads.PREFIX_GENERAL + "Download of " + assetName + " complete.");
if (unzip && assetName.endsWith(".zip")) {
Utils.unzipFile(new File(downloadDir, assetName), downloadTo);
if (afterTask.length > 0)
@ -138,15 +138,15 @@ public class GitHubDownloader {
if (afterTask.length > 0)
afterTask[0].call();
} catch (Exception e) {
CustomHeads.getInstance().getLogger().log(Level.WARNING, "Failed to copy downloaded File", e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to copy downloaded File", e);
}
}
public void failed(AsyncFileDownloader.DownloaderStatus status) {
if (status == AsyncFileDownloader.DownloaderStatus.ERROR) {
Bukkit.getLogger().log(Level.WARNING, "Something went wrong while downloading " + assetName, status.getException());
CustomHeads.getPluginLogger().log(Level.WARNING, "Something went wrong while downloading " + assetName, status.getException());
} else {
Bukkit.getServer().getConsoleSender().sendMessage(CustomHeads.chError + "Failed to download " + assetName + ". " + status);
Bukkit.getServer().getConsoleSender().sendMessage(CustomHeads.PREFIX_ERROR + "Failed to download " + assetName + ". " + status);
}
}
});
@ -156,7 +156,7 @@ public class GitHubDownloader {
}
public void error(Exception exception) {
Bukkit.getLogger().log(Level.WARNING, "Failed to download Files", exception);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to download Files", exception);
}
});
}
@ -168,7 +168,7 @@ public class GitHubDownloader {
}
public void error(Exception exception) {
Bukkit.getLogger().log(Level.WARNING, "Failed to fetch latest Data", exception);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to fetch latest Data", exception);
}
}, false);
}

View File

@ -25,7 +25,7 @@ public class JsonFetcher {
private static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko";
private static final JsonParser PARSER = new JsonParser();
private String url;
private final String url;
private Proxy proxy;
private String userAgent;

View File

@ -7,7 +7,6 @@ import de.likewhat.customheads.utils.Utils;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.InputStreamReader;
@ -41,10 +40,10 @@ public class SpigetResourceFetcher {
private static final String DESCRIPTION_URL = "https://api.spiget.org/v2/resources/%s/updates?size=2147483647&sort=-date";
@Setter
private static String userAgent = "SpigetResourceFetcher/1.2";
private String descriptionUrlFormatted;
private String versionUrlFormatted;
private final String descriptionUrlFormatted;
private final String versionUrlFormatted;
private static JsonParser jsonParser = new JsonParser();
private static final JsonParser JSON_PARSER = new JsonParser();
public SpigetResourceFetcher(int resourceId) {
descriptionUrlFormatted = String.format(DESCRIPTION_URL, resourceId);
@ -61,13 +60,13 @@ public class SpigetResourceFetcher {
JsonArray versionArray;
boolean fromCache = false;
if (updateFile.get().isSet("lastVersionFetch") && TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis() - lastFetch) <= 0) {
versionArray = jsonParser.parse(new String(Base64.getDecoder().decode(updateFile.get().getString("lastVersionFetch").getBytes()))).getAsJsonArray();
versionArray = JSON_PARSER.parse(new String(Base64.getDecoder().decode(updateFile.get().getString("lastVersionFetch").getBytes()))).getAsJsonArray();
fromCache = true;
} else {
HttpURLConnection connection = (HttpURLConnection) new URL(versionUrlFormatted).openConnection();
connection.addRequestProperty("User-Agent", userAgent);
connection.setReadTimeout(5000);
versionArray = jsonParser.parse(new InputStreamReader(connection.getInputStream())).getAsJsonArray();
versionArray = JSON_PARSER.parse(new InputStreamReader(connection.getInputStream())).getAsJsonArray();
}
List<ResourceRelease> releaseList = new ArrayList<>();
@ -94,7 +93,7 @@ public class SpigetResourceFetcher {
}
}
} catch (Exception e) {
Bukkit.getLogger().log(Level.WARNING, "Failed to fetch Version List", e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to fetch Version List", e);
}
}
});
@ -114,13 +113,13 @@ public class SpigetResourceFetcher {
JsonArray descriptionArray;
boolean fromCache = false;
if (updateFile.get().isSet("lastDescriptionFetch") && TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis() - lastFetch) == 0) {
descriptionArray = jsonParser.parse(new String(Base64.getDecoder().decode(updateFile.get().getString("lastDescriptionFetch")))).getAsJsonArray();
descriptionArray = JSON_PARSER.parse(new String(Base64.getDecoder().decode(updateFile.get().getString("lastDescriptionFetch")))).getAsJsonArray();
fromCache = true;
} else {
HttpURLConnection descriptionConnection = (HttpURLConnection) new URL(descriptionUrlFormatted).openConnection();
descriptionConnection.addRequestProperty("User-Agent", userAgent);
descriptionConnection.setReadTimeout(5000);
descriptionArray = jsonParser.parse(new InputStreamReader(descriptionConnection.getInputStream())).getAsJsonArray();
descriptionArray = JSON_PARSER.parse(new InputStreamReader(descriptionConnection.getInputStream())).getAsJsonArray();
}
List<ResourceUpdate> updateList = new ArrayList<>();
@ -134,7 +133,7 @@ public class SpigetResourceFetcher {
consumer.accept(updateList);
return;
} catch (Exception e) {
Bukkit.getLogger().log(Level.WARNING, "Failed to fetch Update List", e);
CustomHeads.getPluginLogger().log(Level.WARNING, "Failed to fetch Update List", e);
}
consumer.accept(null);
}

View File

@ -2,7 +2,7 @@ main: ${project.groupId}.${project.artifactId}
name: ${project.artifactId}
version: ${project.version}
author: LikeWhat
softdepend: [Vault]
softdepend: [Vault, Essentials]
commands:
heads: