Remove all static & improve it

This commit is contained in:
Ryder Belserion 2022-10-11 16:46:43 -04:00
parent 134f4a5a08
commit b76ea867e6
No known key found for this signature in database
GPG Key ID: 3DE16C386AE324DE
14 changed files with 515 additions and 676 deletions

View File

@ -0,0 +1,72 @@
package com.badbones69.crazyauctions;
import com.badbones69.crazyauctions.api.CrazyManager;
import com.badbones69.crazyauctions.api.FileManager;
import com.badbones69.crazyauctions.api.FileManager.Files;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
public class CrazyAuctions extends JavaPlugin implements Listener {
private static CrazyAuctions plugin;
private Starter starter;
private final FileManager fileManager = getStarter().getFileManager();
private final CrazyManager crazyManager = getStarter().getCrazyManager();
private final Methods methods = getStarter().getMethods();
private boolean isEnabled = false;
@Override
public void onEnable() {
try {
plugin = this;
starter = new Starter();
starter.run();
fileManager.setup();
crazyManager.load();
// methods.updateAuction();
} catch (Exception e) {
e.printStackTrace();
isEnabled = false;
return;
}
isEnabled = true;
enable();
}
@Override
public void onDisable() {
if (!isEnabled) return;
disable();
}
private void enable() {
}
private void disable() {
Files.DATA.saveFile();
}
public static CrazyAuctions getPlugin() {
return plugin;
}
public Starter getStarter() {
return starter;
}
}

View File

@ -1,283 +1,128 @@
package com.badbones69.crazyauctions; package com.badbones69.crazyauctions;
import com.badbones69.crazyauctions.api.FileManager; import com.badbones69.crazyauctions.api.CrazyManager;
import com.badbones69.crazyauctions.api.FileManager.Files; import com.badbones69.crazyauctions.api.FileManager.Files;
import com.badbones69.crazyauctions.api.Messages; import com.badbones69.crazyauctions.api.enums.Messages;
import com.badbones69.crazyauctions.api.Version; import com.badbones69.crazyauctions.utils.ItemBuilder;
import com.badbones69.crazyauctions.api.events.AuctionExpireEvent; import com.badbones69.crazyauctions.utils.func.ServerProtocol;
import com.badbones69.crazyauctions.api.events.AuctionWinBidEvent; import net.md_5.bungee.api.chat.TextComponent;
import com.badbones69.crazyauctions.currency.CurrencyManager;
import org.bukkit.*; import org.bukkit.*;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.Plugin;
import java.util.*; import java.util.*;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@SuppressWarnings("deprecation")
public class Methods { public class Methods {
public static Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("CrazyAuctions"); private final CrazyAuctions plugin = CrazyAuctions.getPlugin();
private static FileManager fileManager = FileManager.getInstance();
public final static Pattern HEX_PATTERN = Pattern.compile("#[a-fA-F0-9]{6}"); private final CrazyManager crazyManager = plugin.getStarter().getCrazyManager();
public static String color(String message) { public final Pattern HEX_PATTERN = Pattern.compile("#[a-fA-F0-9]{6}");
if (Version.isNewer(Version.v1_15_R1)) {
public String color(String message) {
if (ServerProtocol.isNewer(ServerProtocol.v1_15_R1)) {
Matcher matcher = HEX_PATTERN.matcher(message); Matcher matcher = HEX_PATTERN.matcher(message);
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
while (matcher.find()) { while (matcher.find()) {
matcher.appendReplacement(buffer, net.md_5.bungee.api.ChatColor.of(matcher.group()).toString()); matcher.appendReplacement(buffer, net.md_5.bungee.api.ChatColor.of(matcher.group()).toString());
} }
return ChatColor.translateAlternateColorCodes('&', matcher.appendTail(buffer).toString()); return ChatColor.translateAlternateColorCodes('&', matcher.appendTail(buffer).toString());
} }
return ChatColor.translateAlternateColorCodes('&', message); return ChatColor.translateAlternateColorCodes('&', message);
} }
public static String getPrefix() { public String getPrefix() {
return color(Files.CONFIG.getFile().getString("Settings.Prefix", "")); return color(Files.CONFIG.getFile().getString("Settings.Prefix", ""));
} }
public static String getPrefix(String msg) { public String getPrefix(String msg) {
return color(Files.CONFIG.getFile().getString("Settings.Prefix", "") + msg); return color(Files.CONFIG.getFile().getString("Settings.Prefix", "") + msg);
} }
public static String removeColor(String msg) { public String sanitizeColor(String msg) {
return sanitizeFormat(color(msg));
}
public String removeColor(String msg) {
return ChatColor.stripColor(msg); return ChatColor.stripColor(msg);
} }
public static ItemStack makeItem(String type, int amount) { public static String sanitizeFormat(String string) {
int ty = 0; return TextComponent.toLegacyText(TextComponent.fromLegacyText(string));
if (type.contains(":")) {
String[] b = type.split(":");
type = b[0];
ty = Integer.parseInt(b[1]);
}
Material m = Material.matchMaterial(type);
ItemStack item;
try {
item = new ItemStack(m, amount, (short) ty);
} catch (Exception e) {
if (Version.isNewer(Version.v1_12_R1)) {
item = new ItemStack(Material.matchMaterial("RED_TERRACOTTA"), 1);
} else {
item = new ItemStack(Material.matchMaterial("STAINED_CLAY"), 1, (short) 14);
}
}
return item;
} }
public static ItemStack makeItem(String type, int amount, String name) { public ItemStack makeItem(Material material, int amount, String name, List<String> lore, HashMap<Enchantment, Integer> enchants) {
int ty = 0; ItemBuilder newItem = new ItemBuilder().setMaterial(material).setAmount(amount).setName(name).setLore(lore).setEnchantments(enchants);
if (type.contains(":")) { return newItem.build();
String[] b = type.split(":");
type = b[0];
ty = Integer.parseInt(b[1]);
}
Material m = Material.matchMaterial(type);
ItemStack item;
try {
item = new ItemStack(m, amount, (short) ty);
} catch (Exception e) {
if (Version.isNewer(Version.v1_12_R1)) {
item = new ItemStack(Material.matchMaterial("RED_TERRACOTTA"), 1);
} else {
item = new ItemStack(Material.matchMaterial("STAINED_CLAY"), 1, (short) 14);
}
}
ItemMeta me = item.getItemMeta();
me.setDisplayName(color(name));
item.setItemMeta(me);
return item;
} }
public static ItemStack makeItem(String type, int amount, String name, List<String> lore) { public ItemStack getItemInHand(Player player) {
ArrayList<String> l = new ArrayList<>(); if (ServerProtocol.isAtLeast(ServerProtocol.v1_12_R1)) {
int ty = 0;
if (type.contains(":")) {
String[] b = type.split(":");
type = b[0];
ty = Integer.parseInt(b[1]);
}
Material m = Material.matchMaterial(type);
ItemStack item;
try {
item = new ItemStack(m, amount, (short) ty);
} catch (Exception e) {
if (Version.isNewer(Version.v1_12_R1)) {
item = new ItemStack(Material.matchMaterial("RED_TERRACOTTA"), 1);
} else {
item = new ItemStack(Material.matchMaterial("STAINED_CLAY"), 1, (short) 14);
}
}
ItemMeta me = item.getItemMeta();
me.setDisplayName(color(name));
for (String L : lore)
l.add(color(L));
me.setLore(l);
item.setItemMeta(me);
return item;
}
public static ItemStack makeItem(Material material, int amount, int type, String name) {
ItemStack item = new ItemStack(material, amount, (short) type);
ItemMeta m = item.getItemMeta();
m.setDisplayName(color(name));
item.setItemMeta(m);
return item;
}
public static ItemStack makeItem(Material material, int amount, int type, String name, List<String> lore) {
ArrayList<String> l = new ArrayList<>();
ItemStack item = new ItemStack(material, amount, (short) type);
ItemMeta m = item.getItemMeta();
m.setDisplayName(color(name));
for (String L : lore)
l.add(color(L));
m.setLore(l);
item.setItemMeta(m);
return item;
}
public static ItemStack makeItem(Material material, int amount, int type, String name, List<String> lore, Map<Enchantment, Integer> enchants) {
ItemStack item = new ItemStack(material, amount, (short) type);
ItemMeta m = item.getItemMeta();
m.setDisplayName(name);
m.setLore(lore);
item.setItemMeta(m);
item.addUnsafeEnchantments(enchants);
return item;
}
public static ItemStack addLore(ItemStack item, String i) {
ArrayList<String> lore = new ArrayList<>();
ItemMeta m = item.getItemMeta();
if (item.getItemMeta().hasLore()) {
lore.addAll(item.getItemMeta().getLore());
}
lore.add(i);
m.setLore(lore);
item.setItemMeta(m);
return item;
}
public static ItemStack addLore(ItemStack item, List<String> list) {
if (item != null && item.getType() != Material.AIR) {
ArrayList<String> lore = new ArrayList<>();
ItemMeta m = item.getItemMeta();
if (item.hasItemMeta() && item.getItemMeta().hasLore()) {
lore.addAll(item.getItemMeta().getLore());
}
for (String i : list)
lore.add(color(i));
m.setLore(lore);
item.setItemMeta(m);
}
return item;
}
public static Integer getVersion() {
String ver = Bukkit.getServer().getClass().getPackage().getName();
ver = ver.substring(ver.lastIndexOf('.') + 1);
ver = ver.replace("_", "").replace("R", "").replace("v", "");
return Integer.parseInt(ver);
}
@SuppressWarnings("deprecation")
public static ItemStack getItemInHand(Player player) {
if (getVersion() >= 191) {
return player.getInventory().getItemInMainHand(); return player.getInventory().getItemInMainHand();
} else { } else {
return player.getItemInHand(); return player.getItemInHand();
} }
} }
@SuppressWarnings("deprecation") public void setItemInHand(Player player, ItemStack item) {
public static void setItemInHand(Player player, ItemStack item) { if (ServerProtocol.isAtLeast(ServerProtocol.v1_12_R1)) {
if (getVersion() >= 191) {
player.getInventory().setItemInMainHand(item); player.getInventory().setItemInMainHand(item);
} else { } else {
player.setItemInHand(item); player.setItemInHand(item);
} }
} }
public static boolean isInt(String s) { public Player getPlayer(String name) {
try { try {
Integer.parseInt(s); return plugin.getServer().getPlayer(name);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
public static boolean isLong(String s) {
try {
Long.parseLong(s);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
public static Player getPlayer(String name) {
try {
return Bukkit.getServer().getPlayer(name);
} catch (Exception e) { } catch (Exception e) {
return null; return null;
} }
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public static OfflinePlayer getOfflinePlayer(String name) { public OfflinePlayer getOfflinePlayer(String name) {
return Bukkit.getServer().getOfflinePlayer(name); return plugin.getServer().getOfflinePlayer(name);
} }
public static Location getLoc(Player player) { public boolean isOnline(String name) {
return player.getLocation(); for (Player player : plugin.getServer().getOnlinePlayers()) {
if (player.getName().equalsIgnoreCase(name)) return true;
} }
public static void runCMD(Player player, String CMD) {
player.performCommand(CMD);
}
public static boolean isOnline(String name) {
for (Player player : Bukkit.getServer().getOnlinePlayers()) {
if (player.getName().equalsIgnoreCase(name)) {
return true;
}
}
return false; return false;
} }
public static boolean isOnline(String name, CommandSender p) { public boolean isOnline(String name, CommandSender commandSender) {
for (Player player : Bukkit.getServer().getOnlinePlayers()) { for (Player player : plugin.getServer().getOnlinePlayers()) {
if (player.getName().equalsIgnoreCase(name)) { if (player.getName().equalsIgnoreCase(name)) return true;
return true;
} }
}
p.sendMessage(Messages.NOT_ONLINE.getMessage()); commandSender.sendMessage(Messages.NOT_ONLINE.getMessage());
return false; return false;
} }
public static boolean hasPermission(Player player, String perm) { public boolean hasPermission(Player player, String perm) {
if (!player.hasPermission("crazyauctions." + perm)) { if (!player.hasPermission("crazyauctions." + perm)) {
player.sendMessage(Messages.NO_PERMISSION.getMessage()); player.sendMessage(Messages.NO_PERMISSION.getMessage());
return false; return false;
} }
return true; return true;
} }
public static boolean hasPermission(CommandSender sender, String perm) { public boolean hasPermission(CommandSender sender, String perm) {
if (sender instanceof Player) { if (sender instanceof Player) {
Player player = (Player) sender; Player player = (Player) sender;
if (!player.hasPermission("crazyauctions." + perm)) { if (!player.hasPermission("crazyauctions." + perm)) {
player.sendMessage(Messages.NO_PERMISSION.getMessage()); player.sendMessage(Messages.NO_PERMISSION.getMessage());
return false; return false;
@ -289,171 +134,7 @@ public class Methods {
} }
} }
public static List<ItemStack> getPage(List<ItemStack> list, Integer page) { public boolean isInvFull(Player player) {
List<ItemStack> items = new ArrayList<>();
if (page <= 0) page = 1;
int max = 45;
int index = page * max - max;
int endIndex = index >= list.size() ? list.size() - 1 : index + max;
for (; index < endIndex; index++) {
if (index < list.size()) items.add(list.get(index));
}
for (; items.size() == 0; page--) {
if (page <= 0) break;
index = page * max - max;
endIndex = index >= list.size() ? list.size() - 1 : index + max;
for (; index < endIndex; index++) {
if (index < list.size()) items.add(list.get(index));
}
}
return items;
}
public static List<Integer> getPageInts(List<Integer> list, Integer page) {
List<Integer> items = new ArrayList<>();
if (page <= 0) page = 1;
int max = 45;
int index = page * max - max;
int endIndex = index >= list.size() ? list.size() - 1 : index + max;
for (; index < endIndex; index++) {
if (index < list.size()) items.add(list.get(index));
}
for (; items.size() == 0; page--) {
if (page <= 0) break;
index = page * max - max;
endIndex = index >= list.size() ? list.size() - 1 : index + max;
for (; index < endIndex; index++) {
if (index < list.size()) items.add(list.get(index));
}
}
return items;
}
public static int getMaxPage(List<ItemStack> list) {
int maxPage = 1;
int amount = list.size();
for (; amount > 45; amount -= 45, maxPage++) ;
return maxPage;
}
public static String convertToTime(long time) {
Calendar C = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time);
int total = ((int) (cal.getTimeInMillis() / 1000) - (int) (C.getTimeInMillis() / 1000));
int D = 0;
int H = 0;
int M = 0;
int S = 0;
for (; total > 86400; total -= 86400, D++) ;
for (; total > 3600; total -= 3600, H++) ;
for (; total > 60; total -= 60, M++) ;
S += total;
return D + "d " + H + "h " + M + "m " + S + "s ";
}
public static long convertToMill(String time) {
Calendar cal = Calendar.getInstance();
for (String i : time.split(" ")) {
if (i.contains("D") || i.contains("d")) {
cal.add(Calendar.DATE, Integer.parseInt(i.replace("D", "").replace("d", "")));
}
if (i.contains("H") || i.contains("h")) {
cal.add(Calendar.HOUR, Integer.parseInt(i.replace("H", "").replace("h", "")));
}
if (i.contains("M") || i.contains("m")) {
cal.add(Calendar.MINUTE, Integer.parseInt(i.replace("M", "").replace("m", "")));
}
if (i.contains("S") || i.contains("s")) {
cal.add(Calendar.SECOND, Integer.parseInt(i.replace("S", "").replace("s", "")));
}
}
return cal.getTimeInMillis();
}
public static boolean isInvFull(Player player) {
return player.getInventory().firstEmpty() == -1; return player.getInventory().firstEmpty() == -1;
} }
public static void updateAuction() {
FileConfiguration data = Files.DATA.getFile();
Calendar cal = Calendar.getInstance();
Calendar expireTime = Calendar.getInstance();
Calendar fullExpireTime = Calendar.getInstance();
boolean shouldSave = false;
if (data.contains("OutOfTime/Cancelled")) {
for (String i : data.getConfigurationSection("OutOfTime/Cancelled").getKeys(false)) {
fullExpireTime.setTimeInMillis(data.getLong("OutOfTime/Cancelled." + i + ".Full-Time"));
if (cal.after(fullExpireTime)) {
data.set("OutOfTime/Cancelled." + i, null);
shouldSave = true;
}
}
}
if (data.contains("Items")) {
for (String i : data.getConfigurationSection("Items").getKeys(false)) {
expireTime.setTimeInMillis(data.getLong("Items." + i + ".Time-Till-Expire"));
fullExpireTime.setTimeInMillis(data.getLong("Items." + i + ".Full-Time"));
if (cal.after(expireTime)) {
int num = 1;
for (; data.contains("OutOfTime/Cancelled." + num); num++) ;
if (data.getBoolean("Items." + i + ".Biddable") && !data.getString("Items." + i + ".TopBidder").equalsIgnoreCase("None") && CurrencyManager.getMoney(getPlayer(data.getString("Items." + i + ".TopBidder"))) >= data.getInt("Items." + i + ".Price")) {
String winner = data.getString("Items." + i + ".TopBidder");
String seller = data.getString("Items." + i + ".Seller");
Long price = data.getLong("Items." + i + ".Price");
CurrencyManager.addMoney(getOfflinePlayer(seller), price);
CurrencyManager.removeMoney(getOfflinePlayer(winner), price);
HashMap<String, String> placeholders = new HashMap<>();
placeholders.put("%Price%", getPrice(i, false));
placeholders.put("%price%", getPrice(i, false));
placeholders.put("%Player%", winner);
placeholders.put("%player%", winner);
if (isOnline(winner) && getPlayer(winner) != null) {
Player player = getPlayer(winner);
Bukkit.getPluginManager().callEvent(new AuctionWinBidEvent(player, data.getItemStack("Items." + i + ".Item"), price));
player.sendMessage(Messages.WIN_BIDDING.getMessage(placeholders));
}
if (isOnline(seller) && getPlayer(seller) != null) {
Player player = getPlayer(seller);
player.sendMessage(Messages.SOMEONE_WON_PLAYERS_BID.getMessage(placeholders));
}
data.set("OutOfTime/Cancelled." + num + ".Seller", winner);
data.set("OutOfTime/Cancelled." + num + ".Full-Time", fullExpireTime.getTimeInMillis());
data.set("OutOfTime/Cancelled." + num + ".StoreID", data.getInt("Items." + i + ".StoreID"));
data.set("OutOfTime/Cancelled." + num + ".Item", data.getItemStack("Items." + i + ".Item"));
} else {
String seller = data.getString("Items." + i + ".Seller");
Player player = getPlayer(seller);
if (isOnline(seller) && getPlayer(seller) != null) {
player.sendMessage(Messages.ITEM_HAS_EXPIRED.getMessage());
}
AuctionExpireEvent event = new AuctionExpireEvent(player, data.getItemStack("Items." + i + ".Item"));
Bukkit.getPluginManager().callEvent(event);
data.set("OutOfTime/Cancelled." + num + ".Seller", data.getString("Items." + i + ".Seller"));
data.set("OutOfTime/Cancelled." + num + ".Full-Time", fullExpireTime.getTimeInMillis());
data.set("OutOfTime/Cancelled." + num + ".StoreID", data.getInt("Items." + i + ".StoreID"));
data.set("OutOfTime/Cancelled." + num + ".Item", data.getItemStack("Items." + i + ".Item"));
}
data.set("Items." + i, null);
shouldSave = true;
}
}
}
if (shouldSave) Files.DATA.saveFile();
}
public static String getPrice(String ID, Boolean Expired) {
long price = 0L;
if (Expired) {
if (Files.DATA.getFile().contains("OutOfTime/Cancelled." + ID + ".Price")) {
price = Files.DATA.getFile().getLong("OutOfTime/Cancelled." + ID + ".Price");
}
} else {
if (Files.DATA.getFile().contains("Items." + ID + ".Price")) {
price = Files.DATA.getFile().getLong("Items." + ID + ".Price");
}
}
return String.valueOf(price);
}
} }

View File

@ -1,29 +1,24 @@
package com.badbones69.crazyauctions.api; package com.badbones69.crazyauctions.api;
import com.badbones69.crazyauctions.api.FileManager.Files; import com.badbones69.crazyauctions.api.FileManager.Files;
import com.badbones69.crazyauctions.api.enums.ShopCategories;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import java.util.ArrayList; import java.util.ArrayList;
public class CrazyAuctions { public class CrazyManager {
private static CrazyAuctions instance = new CrazyAuctions();
private FileManager fileManager = FileManager.getInstance();
private Boolean sellingEnabled; private Boolean sellingEnabled;
private Boolean biddingEnabled; private Boolean biddingEnabled;
public static CrazyAuctions getInstance() { public void load() {
return instance;
}
public void loadCrazyAuctions() {
if (Files.CONFIG.getFile().contains("Settings.Feature-Toggle.Selling")) { if (Files.CONFIG.getFile().contains("Settings.Feature-Toggle.Selling")) {
this.sellingEnabled = Files.CONFIG.getFile().getBoolean("Settings.Feature-Toggle.Selling"); this.sellingEnabled = Files.CONFIG.getFile().getBoolean("Settings.Feature-Toggle.Selling");
} else { } else {
this.sellingEnabled = true; this.sellingEnabled = true;
} }
if (Files.CONFIG.getFile().contains("Settings.Feature-Toggle.Bidding")) { if (Files.CONFIG.getFile().contains("Settings.Feature-Toggle.Bidding")) {
this.biddingEnabled = Files.CONFIG.getFile().getBoolean("Settings.Feature-Toggle.Bidding"); this.biddingEnabled = Files.CONFIG.getFile().getBoolean("Settings.Feature-Toggle.Bidding");
} else { } else {
@ -42,35 +37,32 @@ public class CrazyAuctions {
public ArrayList<ItemStack> getItems(Player player) { public ArrayList<ItemStack> getItems(Player player) {
FileConfiguration data = Files.DATA.getFile(); FileConfiguration data = Files.DATA.getFile();
ArrayList<ItemStack> items = new ArrayList<>(); ArrayList<ItemStack> items = new ArrayList<>();
if (data.contains("Items")) { if (data.contains("Items")) {
for (String i : data.getConfigurationSection("Items").getKeys(false)) { for (String i : data.getConfigurationSection("Items").getKeys(false)) {
if (data.getString("Items." + i + ".Seller").equalsIgnoreCase(player.getName())) { if (data.getString("Items." + i + ".Seller").equalsIgnoreCase(player.getName())) items.add(data.getItemStack("Items." + i + ".Item").clone());
items.add(data.getItemStack("Items." + i + ".Item").clone());
}
} }
} }
return items; return items;
} }
public ArrayList<ItemStack> getItems(Player player, ShopType type) { public ArrayList<ItemStack> getItems(Player player, ShopCategories type) {
FileConfiguration data = Files.DATA.getFile(); FileConfiguration data = Files.DATA.getFile();
ArrayList<ItemStack> items = new ArrayList<>(); ArrayList<ItemStack> items = new ArrayList<>();
if (data.contains("Items")) { if (data.contains("Items")) {
for (String i : data.getConfigurationSection("Items").getKeys(false)) { for (String i : data.getConfigurationSection("Items").getKeys(false)) {
if (data.getString("Items." + i + ".Seller").equalsIgnoreCase(player.getName())) { if (data.getString("Items." + i + ".Seller").equalsIgnoreCase(player.getName())) {
if (data.getBoolean("Items." + i + ".Biddable")) { if (data.getBoolean("Items." + i + ".Biddable")) {
if (type == ShopType.BID) { if (type == ShopCategories.BID) items.add(data.getItemStack("Items." + i + ".Item").clone());
items.add(data.getItemStack("Items." + i + ".Item").clone());
}
} else { } else {
if (type == ShopType.SELL) { if (type == ShopCategories.SELL) items.add(data.getItemStack("Items." + i + ".Item").clone());
items.add(data.getItemStack("Items." + i + ".Item").clone());
} }
} }
} }
} }
}
return items;
}
return items;
}
} }

View File

@ -1,9 +1,9 @@
package com.badbones69.crazyauctions.api; package com.badbones69.crazyauctions.api;
import com.badbones69.crazyauctions.CrazyAuctions;
import com.badbones69.crazyauctions.utils.func.ServerProtocol;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@ -13,110 +13,118 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
/** /**
*
* @author BadBones69 * @author BadBones69
* @version v1.0 * @version v1.0
*
*/ */
public class FileManager { public class FileManager {
private static FileManager instance = new FileManager(); private final CrazyAuctions plugin = CrazyAuctions.getPlugin();
private Plugin plugin;
private String prefix = "";
private Boolean log = false;
private HashMap<Files, File> files = new HashMap<>();
private ArrayList<String> homeFolders = new ArrayList<>();
private ArrayList<CustomFile> customFiles = new ArrayList<>();
private HashMap<String, String> autoGenerateFiles = new HashMap<>();
private HashMap<Files, FileConfiguration> configurations = new HashMap<>();
public static FileManager getInstance() { private boolean log = false;
return instance;
} private final HashMap<Files, File> files = new HashMap<>();
private final ArrayList<String> homeFolders = new ArrayList<>();
private final ArrayList<CustomFile> customFiles = new ArrayList<>();
private final HashMap<String, String> jarHomeFolders = new HashMap<>();
private final HashMap<String, String> autoGenerateFiles = new HashMap<>();
private final HashMap<Files, FileConfiguration> configurations = new HashMap<>();
/** /**
* Sets up the plugin and loads all necessary files. * Loads all necessary files.
* @param plugin The plugin this is getting loading for.
*/ */
public FileManager setup(Plugin plugin) { public FileManager setup() {
prefix = "[" + plugin.getName() + "] "; if (!plugin.getDataFolder().exists()) plugin.getDataFolder().mkdirs();
this.plugin = plugin;
if (!plugin.getDataFolder().exists()) {
plugin.getDataFolder().mkdirs();
}
files.clear(); files.clear();
customFiles.clear(); customFiles.clear();
//Loads all the normal static files.
// Loads all the normal static files.
for (Files file : Files.values()) { for (Files file : Files.values()) {
File newFile = new File(plugin.getDataFolder(), file.getFileLocation()); File newFile = new File(plugin.getDataFolder(), file.getFileLocation());
if (log) System.out.println(prefix + "Loading the " + file.getFileName());
if (isLogging()) plugin.getLogger().info("Loading the " + file.getFileName());
if (!newFile.exists()) { if (!newFile.exists()) {
try { try {
String fileLocation = file.getFileLocation(); String fileLocation = file.getFileLocation();
//Switch between 1.12.2- and 1.13+ config version.
// Switch between 1.12.2- and 1.13+ config version.
if (file == Files.CONFIG) { if (file == Files.CONFIG) {
if (Version.isOlder(Version.v1_13_R2)) { if (ServerProtocol.isOlder(ServerProtocol.v1_13_R2)) {
fileLocation = "config1.12.2-Down.yml"; fileLocation = "config1.12.2-Down.yml";
} else { } else {
fileLocation = "config1.13-Up.yml"; fileLocation = "config1.13-Up.yml";
} }
} }
File serverFile = new File(plugin.getDataFolder(), "/" + file.getFileLocation()); File serverFile = new File(plugin.getDataFolder(), "/" + file.getFileLocation());
InputStream jarFile = getClass().getResourceAsStream("/" + fileLocation); InputStream jarFile = getClass().getResourceAsStream("/" + file.getFileJar());
copyFile(jarFile, serverFile); copyFile(jarFile, serverFile);
} catch (Exception e) { } catch (Exception e) {
if (log) System.out.println(prefix + "Failed to load " + file.getFileName()); if (isLogging()) plugin.getLogger().info("Failed to load " + file.getFileName());
e.printStackTrace(); e.printStackTrace();
continue; continue;
} }
} }
files.put(file, newFile); files.put(file, newFile);
configurations.put(file, YamlConfiguration.loadConfiguration(newFile)); configurations.put(file, YamlConfiguration.loadConfiguration(newFile));
if (log) System.out.println(prefix + "Successfully loaded " + file.getFileName());
if (isLogging()) plugin.getLogger().info("Successfully loaded " + file.getFileName());
} }
//Starts to load all the custom files.
// Starts to load all the custom files.
if (homeFolders.size() > 0) { if (homeFolders.size() > 0) {
if (log) System.out.println(prefix + "Loading custom files."); if (isLogging()) plugin.getLogger().info("Loading custom files.");
for (String homeFolder : homeFolders) { for (String homeFolder : homeFolders) {
File homeFile = new File(plugin.getDataFolder(), "/" + homeFolder); File homeFile = new File(plugin.getDataFolder(), "/" + homeFolder);
if (homeFile.exists()) { if (homeFile.exists()) {
String[] list = homeFile.list(); String[] list = homeFile.list();
if (list != null) { if (list != null) {
for (String name : list) { for (String name : list) {
if (name.endsWith(".yml")) { if (name.endsWith(".yml")) {
CustomFile file = new CustomFile(name, homeFolder, plugin); CustomFile file = new CustomFile(name, homeFolder);
if (file.exists()) { if (file.exists()) {
customFiles.add(file); customFiles.add(file);
if (log) System.out.println(prefix + "Loaded new custom file: " + homeFolder + "/" + name + ".");
if (isLogging()) plugin.getLogger().info("Loaded new custom file: " + homeFolder + "/" + name + ".");
}
}
}
}
} else {
homeFile.mkdir();
if (isLogging()) plugin.getLogger().info("The folder " + homeFolder + "/ was not found so it was created.");
for (String fileName : autoGenerateFiles.keySet()) {
if (autoGenerateFiles.get(fileName).equalsIgnoreCase(homeFolder)) {
homeFolder = autoGenerateFiles.get(fileName);
try {
File serverFile = new File(plugin.getDataFolder(), homeFolder + "/" + fileName);
InputStream jarFile = getClass().getResourceAsStream(homeFolder + "/" + fileName);
copyFile(jarFile, serverFile);
if (fileName.toLowerCase().endsWith(".yml")) customFiles.add(new CustomFile(fileName, homeFolder));
if (isLogging()) plugin.getLogger().info("Created new default file: " + homeFolder + "/" + fileName + ".");
} catch (Exception e) {
if (isLogging()) plugin.getLogger().info("Failed to create new default file: " + homeFolder + "/" + fileName + "!");
e.printStackTrace();
}
} }
} }
} }
} }
} else { if (isLogging()) plugin.getLogger().info("Finished loading custom files.");
homeFile.mkdir();
if (log) System.out.println(prefix + "The folder " + homeFolder + "/ was not found so it was created.");
for (String fileName : autoGenerateFiles.keySet()) {
if (autoGenerateFiles.get(fileName).equalsIgnoreCase(homeFolder)) {
homeFolder = autoGenerateFiles.get(fileName);
try {
File serverFile = new File(plugin.getDataFolder(), homeFolder + "/" + fileName);
InputStream jarFile = getClass().getResourceAsStream(homeFolder + "/" + fileName);
copyFile(jarFile, serverFile);
if (fileName.toLowerCase().endsWith(".yml")) {
customFiles.add(new CustomFile(fileName, homeFolder, plugin));
}
if (log) System.out.println(prefix + "Created new default file: " + homeFolder + "/" + fileName + ".");
} catch (Exception e) {
if (log) System.out.println(prefix + "Failed to create new default file: " + homeFolder + "/" + fileName + "!");
e.printStackTrace();
}
}
}
}
}
if (log) System.out.println(prefix + "Finished loading custom files.");
} }
return this; return this;
} }
@ -124,7 +132,7 @@ public class FileManager {
* Turn on the logger system for the FileManager. * Turn on the logger system for the FileManager.
* @param log True to turn it on and false for it to be off. * @param log True to turn it on and false for it to be off.
*/ */
public FileManager logInfo(Boolean log) { public FileManager setLog(boolean log) {
this.log = log; this.log = log;
return this; return this;
} }
@ -133,7 +141,7 @@ public class FileManager {
* Check if the logger is logging in console. * Check if the logger is logging in console.
* @return True if it is and false if it isn't. * @return True if it is and false if it isn't.
*/ */
public Boolean isLogging() { public boolean isLogging() {
return log; return log;
} }
@ -190,42 +198,21 @@ public class FileManager {
*/ */
public CustomFile getFile(String name) { public CustomFile getFile(String name) {
for (CustomFile file : customFiles) { for (CustomFile file : customFiles) {
if (file.getName().equalsIgnoreCase(name)) { if (file.getName().equalsIgnoreCase(name)) return file;
return file;
}
} }
return null; return null;
} }
/** /**
* Saves the file from the loaded state to the file system. * Saves the file from the loaded state to the file system.
*/ */
public void saveFile(Files file, boolean sync) { public void saveFile(Files file) {
try { try {
File targetFile = files.get(file); configurations.get(file).save(files.get(file));
FileConfiguration configuration = configurations.get(file);
YamlConfiguration copy = new YamlConfiguration();
configuration.getValues(false).forEach(copy :: set);
BukkitRunnable runnable = new BukkitRunnable() {
@Override
public void run() {
try {
copy.save(targetFile);
} catch (IOException e) { } catch (IOException e) {
System.out.println(prefix + "Could not save " + file.getFileName() + "!"); plugin.getLogger().warning("Could not save " + file.getFileName() + "!");
e.printStackTrace();
}
}
};
if (sync) {
runnable.run();
} else {
runnable.runTaskAsynchronously(plugin);
}
} catch (NullPointerException e) {
System.out.println(prefix + "File is null " + file.getFileName() + "!");
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -236,16 +223,18 @@ public class FileManager {
*/ */
public void saveFile(String name) { public void saveFile(String name) {
CustomFile file = getFile(name); CustomFile file = getFile(name);
if (file != null) { if (file != null) {
try { try {
file.getFile().save(new File(plugin.getDataFolder(), file.getHomeFolder() + "/" + file.getFileName())); file.getFile().save(new File(plugin.getDataFolder(), file.getHomeFolder() + "/" + file.getFileName()));
if (log) System.out.println(prefix + "Successfuly saved the " + file.getFileName() + ".");
if (isLogging()) plugin.getLogger().info("Successfully saved the " + file.getFileName() + ".");
} catch (Exception e) { } catch (Exception e) {
System.out.println(prefix + "Could not save " + file.getFileName() + "!"); plugin.getLogger().warning("Could not save " + file.getFileName() + "!");
e.printStackTrace(); e.printStackTrace();
} }
} else { } else {
if (log) System.out.println(prefix + "The file " + name + ".yml could not be found!"); if (isLogging()) plugin.getLogger().warning("The file " + name + ".yml could not be found!");
} }
} }
@ -254,7 +243,7 @@ public class FileManager {
* @param file The custom file you are saving. * @param file The custom file you are saving.
* @return True if the file saved correct and false if there was an error. * @return True if the file saved correct and false if there was an error.
*/ */
public Boolean saveFile(CustomFile file) { public boolean saveFile(CustomFile file) {
return file.saveFile(); return file.saveFile();
} }
@ -270,16 +259,18 @@ public class FileManager {
*/ */
public void reloadFile(String name) { public void reloadFile(String name) {
CustomFile file = getFile(name); CustomFile file = getFile(name);
if (file != null) { if (file != null) {
try { try {
file.file = YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(), "/" + file.getHomeFolder() + "/" + file.getFileName())); file.file = YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(), "/" + file.getHomeFolder() + "/" + file.getFileName()));
if (log) System.out.println(prefix + "Successfuly reload the " + file.getFileName() + ".");
if (isLogging()) plugin.getLogger().info("Successfully reloaded the " + file.getFileName() + ".");
} catch (Exception e) { } catch (Exception e) {
System.out.println(prefix + "Could not reload the " + file.getFileName() + "!"); plugin.getLogger().warning("Could not reload the " + file.getFileName() + "!");
e.printStackTrace(); e.printStackTrace();
} }
} else { } else {
if (log) System.out.println(prefix + "The file " + name + ".yml could not be found!"); if (isLogging()) plugin.getLogger().warning("The file " + name + ".yml could not be found!");
} }
} }
@ -287,25 +278,31 @@ public class FileManager {
* Overrides the loaded state file and loads the filesystems file. * Overrides the loaded state file and loads the filesystems file.
* @return True if it reloaded correct and false if the file wasn't found. * @return True if it reloaded correct and false if the file wasn't found.
*/ */
public Boolean reloadFile(CustomFile file) { public boolean reloadFile(CustomFile file) {
return file.reloadFile(); return file.reloadFile();
} }
/** /**
* Was found here: https://bukkit.org/threads/extracting-file-from-jar.16962 * Was found here: <a href="https://bukkit.org/threads/extracting-file-from-jar.16962">...</a>
*/ */
private void copyFile(InputStream in, File out) throws Exception { private void copyFile(InputStream in, File out) throws Exception {
try (FileOutputStream fos = new FileOutputStream(out)) { try (InputStream fis = in; FileOutputStream fos = new FileOutputStream(out)) {
byte[] buf = new byte[1024]; byte[] buf = new byte[1024];
int i; int i;
while ((i = in.read(buf)) != -1) {
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i); fos.write(buf, 0, i);
} }
} finally { }
if (in != null) {
in.close();
} }
public void reloadAllFiles() {
for (Files file : Files.values()) {
file.reloadFile();
}
for (CustomFile file : customFiles) {
file.reloadFile();
} }
} }
@ -319,16 +316,32 @@ public class FileManager {
TEST_FILE("test-file.yml", "test-file.yml"); TEST_FILE("test-file.yml", "test-file.yml");
private final String fileName; private final String fileName;
private final String fileJar;
private final String fileLocation; private final String fileLocation;
private final CrazyAuctions plugin = CrazyAuctions.getPlugin();
private final FileManager fileManager = plugin.getStarter().getFileManager();
/** /**
* The files that the server will try and load. * The files that the server will try and load.
* @param fileName The file name that will be in the plugin's folder. * @param fileName The file name that will be in the plugin's folder.
* @param fileLocation The location the file is in while in the Jar. * @param fileLocation The location the file in the plugin's folder.
*/ */
private Files(String fileName, String fileLocation) { Files(String fileName, String fileLocation) {
this(fileName, fileLocation, fileLocation);
}
/**
* The files that the server will try and load.
* @param fileName The file name that will be in the plugin's folder.
* @param fileLocation The location of the file will be in the plugin's folder.
* @param fileJar The location of the file in the jar.
*/
Files(String fileName, String fileLocation, String fileJar) {
this.fileName = fileName; this.fileName = fileName;
this.fileLocation = fileLocation; this.fileLocation = fileLocation;
this.fileJar = fileJar;
} }
/** /**
@ -347,53 +360,56 @@ public class FileManager {
return fileLocation; return fileLocation;
} }
/**
* Get the location of the file in the jar.
* @return The location of the file in the jar.
*/
public String getFileJar() {
return fileJar;
}
/** /**
* Gets the file from the system. * Gets the file from the system.
* @return The file from the system. * @return The file from the system.
*/ */
public FileConfiguration getFile() { public FileConfiguration getFile() {
return getInstance().getFile(this); return fileManager.getFile(this);
} }
/** /**
* Saves the file from the loaded state to the file system. * Saves the file from the loaded state to the file system.
*/ */
public void saveFile(boolean sync) {
getInstance().saveFile(this, sync);
}
public void saveFile() { public void saveFile() {
getInstance().saveFile(this, false); fileManager.saveFile(this);
} }
/** /**
* Overrides the loaded state file and loads the file systems file. * Overrides the loaded state file and loads the file systems file.
*/ */
public void relaodFile() { public void reloadFile() {
getInstance().reloadFile(this); fileManager.reloadFile(this);
} }
} }
public class CustomFile { public class CustomFile {
private String name; private final String name;
private Plugin plugin; private final String fileName;
private String fileName; private final String homeFolder;
private String homeFolder;
private FileConfiguration file; private FileConfiguration file;
private final CrazyAuctions plugin = CrazyAuctions.getPlugin();
/** /**
* A custom file that is being made. * A custom file that is being made.
* @param name Name of the file. * @param name Name of the file.
* @param homeFolder The home folder of the file. * @param homeFolder The home folder of the file.
* @param plugin The plugin the files belong to.
*/ */
public CustomFile(String name, String homeFolder, Plugin plugin) { public CustomFile(String name, String homeFolder) {
this.name = name.replace(".yml", ""); this.name = name.replace(".yml", "");
this.plugin = plugin;
this.fileName = name; this.fileName = name;
this.homeFolder = homeFolder; this.homeFolder = homeFolder;
if (new File(plugin.getDataFolder(), "/" + homeFolder).exists()) { if (new File(plugin.getDataFolder(), "/" + homeFolder).exists()) {
if (new File(plugin.getDataFolder(), "/" + homeFolder + "/" + name).exists()) { if (new File(plugin.getDataFolder(), "/" + homeFolder + "/" + name).exists()) {
file = YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(), "/" + homeFolder + "/" + name)); file = YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(), "/" + homeFolder + "/" + name));
@ -402,7 +418,9 @@ public class FileManager {
} }
} else { } else {
new File(plugin.getDataFolder(), "/" + homeFolder).mkdir(); new File(plugin.getDataFolder(), "/" + homeFolder).mkdir();
if (log) System.out.println(prefix + "The folder " + homeFolder + "/ was not found so it was created.");
if (isLogging()) plugin.getLogger().info("The folder " + homeFolder + "/ was not found so it was created.");
file = null; file = null;
} }
} }
@ -431,14 +449,6 @@ public class FileManager {
return homeFolder; return homeFolder;
} }
/**
* Get the plugin the file belongs to.
* @return The plugin the file belongs to.
*/
public Plugin getPlugin() {
return plugin;
}
/** /**
* Get the ConfigurationFile. * Get the ConfigurationFile.
* @return The ConfigurationFile of this file. * @return The ConfigurationFile of this file.
@ -463,39 +473,43 @@ public class FileManager {
if (file != null) { if (file != null) {
try { try {
file.save(new File(plugin.getDataFolder(), homeFolder + "/" + fileName)); file.save(new File(plugin.getDataFolder(), homeFolder + "/" + fileName));
if (log) System.out.println(prefix + "Successfuly saved the " + fileName + ".");
if (isLogging()) plugin.getLogger().info("Successfully saved the " + fileName + ".");
return true; return true;
} catch (Exception e) { } catch (Exception e) {
System.out.println(prefix + "Could not save " + fileName + "!"); plugin.getLogger().warning("Could not save " + fileName + "!");
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }
} else { } else {
if (log) System.out.println(prefix + "There was a null custom file that could not be found!"); if (isLogging()) plugin.getLogger().warning("There was a null custom file that could not be found!");
} }
return false; return false;
} }
/** /**
* Overrides the loaded state file and loads the filesystems file. * Overrides the loaded state file and loads the filesystems file.
* @return True if it reloaded correct and false if the file wasn't found or errored. * @return True if it reloaded correct and false if the file wasn't found or error.
*/ */
public Boolean reloadFile() { public Boolean reloadFile() {
if (file != null) { if (file != null) {
try { try {
file = YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(), "/" + homeFolder + "/" + fileName)); file = YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(), "/" + homeFolder + "/" + fileName));
if (log) System.out.println(prefix + "Successfuly reload the " + fileName + ".");
if (isLogging()) plugin.getLogger().info("Successfully reloaded the " + fileName + ".");
return true; return true;
} catch (Exception e) { } catch (Exception e) {
System.out.println(prefix + "Could not reload the " + fileName + "!"); plugin.getLogger().warning("Could not reload the " + fileName + "!");
e.printStackTrace(); e.printStackTrace();
} }
} else { } else {
if (log) System.out.println(prefix + "There was a null custom file that was not found!"); if (isLogging()) plugin.getLogger().warning("There was a null custom file that was not found!");
} }
return false; return false;
} }
} }
} }

View File

@ -1,10 +1,10 @@
package com.badbones69.crazyauctions.api; package com.badbones69.crazyauctions.api.enums;
import com.badbones69.crazyauctions.utils.func.ServerProtocol;
import org.bukkit.Material; import org.bukkit.Material;
import java.util.ArrayList; import java.util.ArrayList;
public enum Category { public enum AuctionCategories {
NONE("None", new ArrayList<>()), NONE("None", new ArrayList<>()),
OTHER("Other", getOthers()), OTHER("Other", getOthers()),
@ -21,7 +21,7 @@ public enum Category {
/** /**
* @param name Name of the Shop Type. * @param name Name of the Shop Type.
*/ */
private Category(String name, ArrayList<Material> items) { AuctionCategories(String name, ArrayList<Material> items) {
this.name = name; this.name = name;
this.items = items; this.items = items;
} }
@ -30,18 +30,18 @@ public enum Category {
* @param name Name of the Type you want. * @param name Name of the Type you want.
* @return Returns the Type as an Enum. * @return Returns the Type as an Enum.
*/ */
public static Category getFromName(String name) { public static AuctionCategories getFromName(String name) {
for (Category type : Category.values()) { for (AuctionCategories type : AuctionCategories.values()) {
if (type.getName().equalsIgnoreCase(name)) { if (type.getName().equalsIgnoreCase(name)) return type;
return type;
}
} }
return null; return null;
} }
private static ArrayList<Material> getArmor() { private static ArrayList<Material> getArmor() {
ArrayList<Material> ma = new ArrayList<>(); ArrayList<Material> ma = new ArrayList<>();
if (Version.isNewer(Version.v1_12_R1)) {
if (ServerProtocol.isNewer(ServerProtocol.v1_12_R1)) {
ma.add(Material.matchMaterial("GOLDEN_HELMET")); ma.add(Material.matchMaterial("GOLDEN_HELMET"));
ma.add(Material.matchMaterial("GOLDEN_CHESTPLATE")); ma.add(Material.matchMaterial("GOLDEN_CHESTPLATE"));
ma.add(Material.matchMaterial("GOLDEN_LEGGINGS")); ma.add(Material.matchMaterial("GOLDEN_LEGGINGS"));
@ -52,6 +52,7 @@ public enum Category {
ma.add(Material.matchMaterial("GOLD_LEGGINGS")); ma.add(Material.matchMaterial("GOLD_LEGGINGS"));
ma.add(Material.matchMaterial("GOLD_BOOTS")); ma.add(Material.matchMaterial("GOLD_BOOTS"));
} }
ma.add(Material.DIAMOND_HELMET); ma.add(Material.DIAMOND_HELMET);
ma.add(Material.DIAMOND_CHESTPLATE); ma.add(Material.DIAMOND_CHESTPLATE);
ma.add(Material.DIAMOND_LEGGINGS); ma.add(Material.DIAMOND_LEGGINGS);
@ -68,18 +69,21 @@ public enum Category {
ma.add(Material.DIAMOND_CHESTPLATE); ma.add(Material.DIAMOND_CHESTPLATE);
ma.add(Material.DIAMOND_LEGGINGS); ma.add(Material.DIAMOND_LEGGINGS);
ma.add(Material.DIAMOND_BOOTS); ma.add(Material.DIAMOND_BOOTS);
if (Version.isNewer(Version.v1_15_R1)) {
if (ServerProtocol.isNewer(ServerProtocol.v1_15_R1)) {
ma.add(Material.NETHERITE_HELMET); ma.add(Material.NETHERITE_HELMET);
ma.add(Material.NETHERITE_CHESTPLATE); ma.add(Material.NETHERITE_CHESTPLATE);
ma.add(Material.NETHERITE_LEGGINGS); ma.add(Material.NETHERITE_LEGGINGS);
ma.add(Material.NETHERITE_BOOTS); ma.add(Material.NETHERITE_BOOTS);
} }
return ma; return ma;
} }
private static ArrayList<Material> getTools() { private static ArrayList<Material> getTools() {
ArrayList<Material> ma = new ArrayList<>(); ArrayList<Material> ma = new ArrayList<>();
if (Version.isNewer(Version.v1_12_R1)) {
if (ServerProtocol.isNewer(ServerProtocol.v1_12_R1)) {
ma.add(Material.matchMaterial("WOODEN_PICKAXE")); ma.add(Material.matchMaterial("WOODEN_PICKAXE"));
ma.add(Material.matchMaterial("WOODEN_AXE")); ma.add(Material.matchMaterial("WOODEN_AXE"));
ma.add(Material.matchMaterial("WOODEN_SHOVEL")); ma.add(Material.matchMaterial("WOODEN_SHOVEL"));
@ -104,6 +108,7 @@ public enum Category {
ma.add(Material.matchMaterial("IRON_SPADE")); ma.add(Material.matchMaterial("IRON_SPADE"));
ma.add(Material.matchMaterial("DIAMOND_SPADE")); ma.add(Material.matchMaterial("DIAMOND_SPADE"));
} }
ma.add(Material.STONE_PICKAXE); ma.add(Material.STONE_PICKAXE);
ma.add(Material.IRON_PICKAXE); ma.add(Material.IRON_PICKAXE);
ma.add(Material.DIAMOND_PICKAXE); ma.add(Material.DIAMOND_PICKAXE);
@ -113,18 +118,21 @@ public enum Category {
ma.add(Material.STONE_HOE); ma.add(Material.STONE_HOE);
ma.add(Material.IRON_HOE); ma.add(Material.IRON_HOE);
ma.add(Material.DIAMOND_HOE); ma.add(Material.DIAMOND_HOE);
if (Version.isNewer(Version.v1_15_R1)) {
if (ServerProtocol.isNewer(ServerProtocol.v1_15_R1)) {
ma.add(Material.NETHERITE_PICKAXE); ma.add(Material.NETHERITE_PICKAXE);
ma.add(Material.NETHERITE_AXE); ma.add(Material.NETHERITE_AXE);
ma.add(Material.NETHERITE_HOE); ma.add(Material.NETHERITE_HOE);
ma.add(Material.NETHERITE_SHOVEL); ma.add(Material.NETHERITE_SHOVEL);
} }
return ma; return ma;
} }
private static ArrayList<Material> getWeapons() { private static ArrayList<Material> getWeapons() {
ArrayList<Material> ma = new ArrayList<>(); ArrayList<Material> ma = new ArrayList<>();
if (Version.isNewer(Version.v1_12_R1)) {
if (ServerProtocol.isNewer(ServerProtocol.v1_12_R1)) {
ma.add(Material.matchMaterial("WOODEN_SWORD")); ma.add(Material.matchMaterial("WOODEN_SWORD"));
ma.add(Material.matchMaterial("WOODEN_AXE")); ma.add(Material.matchMaterial("WOODEN_AXE"));
ma.add(Material.matchMaterial("GOLDEN_SWORD")); ma.add(Material.matchMaterial("GOLDEN_SWORD"));
@ -135,6 +143,7 @@ public enum Category {
ma.add(Material.matchMaterial("GOLD_SWORD")); ma.add(Material.matchMaterial("GOLD_SWORD"));
ma.add(Material.matchMaterial("GOLD_AXE")); ma.add(Material.matchMaterial("GOLD_AXE"));
} }
ma.add(Material.STONE_SWORD); ma.add(Material.STONE_SWORD);
ma.add(Material.IRON_SWORD); ma.add(Material.IRON_SWORD);
ma.add(Material.DIAMOND_SWORD); ma.add(Material.DIAMOND_SWORD);
@ -142,41 +151,42 @@ public enum Category {
ma.add(Material.IRON_AXE); ma.add(Material.IRON_AXE);
ma.add(Material.DIAMOND_AXE); ma.add(Material.DIAMOND_AXE);
ma.add(Material.BOW); ma.add(Material.BOW);
if (Version.isNewer(Version.v1_15_R1)) {
if (ServerProtocol.isNewer(ServerProtocol.v1_15_R1)) {
ma.add(Material.NETHERITE_SWORD); ma.add(Material.NETHERITE_SWORD);
ma.add(Material.NETHERITE_AXE); ma.add(Material.NETHERITE_AXE);
} }
return ma; return ma;
} }
private static ArrayList<Material> getFood() { private static ArrayList<Material> getFood() {
ArrayList<Material> ma = new ArrayList<>(); ArrayList<Material> ma = new ArrayList<>();
for (Material m : Material.values()) { for (Material m : Material.values()) {
if (m.isEdible()) { if (m.isEdible()) {
if (m != Material.POTION) ma.add(m); if (m != Material.POTION) ma.add(m);
} }
} }
return ma; return ma;
} }
private static ArrayList<Material> getPotions() { private static ArrayList<Material> getPotions() {
ArrayList<Material> ma = new ArrayList<>(); ArrayList<Material> ma = new ArrayList<>();
ma.add(Material.POTION); ma.add(Material.POTION);
if (Material.matchMaterial("SPLASH_POTION") != null) {
ma.add(Material.matchMaterial("SPLASH_POTION")); if (Material.matchMaterial("SPLASH_POTION") != null) ma.add(Material.matchMaterial("SPLASH_POTION"));
}
if (Material.matchMaterial("LINGERING_POTION") != null) { if (Material.matchMaterial("LINGERING_POTION") != null) ma.add(Material.matchMaterial("LINGERING_POTION"));
ma.add(Material.matchMaterial("LINGERING_POTION"));
}
return ma; return ma;
} }
private static ArrayList<Material> getBlocks() { private static ArrayList<Material> getBlocks() {
ArrayList<Material> ma = new ArrayList<>(); ArrayList<Material> ma = new ArrayList<>();
for (Material m : Material.values()) { for (Material m : Material.values()) {
if (m.isBlock()) { if (m.isBlock()) ma.add(m);
ma.add(m);
}
} }
return ma; return ma;
} }
@ -184,9 +194,7 @@ public enum Category {
private static ArrayList<Material> getOthers() { private static ArrayList<Material> getOthers() {
ArrayList<Material> ma = new ArrayList<>(); ArrayList<Material> ma = new ArrayList<>();
for (Material m : Material.values()) { for (Material m : Material.values()) {
if (!(getArmor().contains(m) || getTools().contains(m) || getWeapons().contains(m) || getFood().contains(m) || getPotions().contains(m) || getBlocks().contains(m))) { if (!(getArmor().contains(m) || getTools().contains(m) || getWeapons().contains(m) || getFood().contains(m) || getPotions().contains(m) || getBlocks().contains(m))) ma.add(m);
ma.add(m);
}
} }
return ma; return ma;
} }
@ -201,5 +209,4 @@ public enum Category {
public ArrayList<Material> getItems() { public ArrayList<Material> getItems() {
return items; return items;
} }
} }

View File

@ -10,5 +10,4 @@ public enum CancelledReason {
* Cancelled by the player them self. * Cancelled by the player them self.
*/ */
PLAYER_FORCE_CANCEL() PLAYER_FORCE_CANCEL()
} }

View File

@ -1,6 +1,8 @@
package com.badbones69.crazyauctions.api; package com.badbones69.crazyauctions.api.enums;
import com.badbones69.crazyauctions.CrazyAuctions;
import com.badbones69.crazyauctions.Methods; import com.badbones69.crazyauctions.Methods;
import com.badbones69.crazyauctions.api.FileManager;
import com.badbones69.crazyauctions.api.FileManager.Files; import com.badbones69.crazyauctions.api.FileManager.Files;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
@ -54,47 +56,54 @@ public enum Messages {
"&9/Ah Expired/Collect - &eView and manage your cancelled and expired items.", "&9/Ah Expired/Collect - &eView and manage your cancelled and expired items.",
"&9/Ah Listed - &eView and manage the items you are selling.", "&9/Ah Listed - &eView and manage the items you are selling.",
"&9/Ah Help - &eView this help menu.")); "&9/Ah Help - &eView this help menu."));
private static final FileManager fileManager = FileManager.getInstance();
private final String path; private final String path;
private String defaultMessage; private String defaultMessage;
private List<String> defaultListMessage; private List<String> defaultListMessage;
private Messages(String path, String defaultMessage) { private static final CrazyAuctions plugin = CrazyAuctions.getPlugin();
private static final Methods methods = plugin.getStarter().getMethods();
Messages(String path, String defaultMessage) {
this.path = path; this.path = path;
this.defaultMessage = defaultMessage; this.defaultMessage = defaultMessage;
} }
private Messages(String path, List<String> defaultListMessage) { Messages(String path, List<String> defaultListMessage) {
this.path = path; this.path = path;
this.defaultListMessage = defaultListMessage; this.defaultListMessage = defaultListMessage;
} }
public static String convertList(List<String> list) { public static String convertList(List<String> list) {
String message = ""; StringBuilder message = new StringBuilder();
for (String m : list) { for (String m : list) {
message += Methods.color(m) + "\n"; message.append(methods.color(m)).append("\n");
} }
return message;
return message.toString();
} }
public static String convertList(List<String> list, HashMap<String, String> placeholders) { public static String convertList(List<String> list, HashMap<String, String> placeholders) {
String message = ""; StringBuilder message = new StringBuilder();
for (String m : list) { for (String m : list) {
message += Methods.color(m) + "\n"; message.append(methods.color(m)).append("\n");
} }
for (String ph : placeholders.keySet()) { for (String ph : placeholders.keySet()) {
message = Methods.color(message.replace(ph, placeholders.get(ph))).replace(ph, placeholders.get(ph).toLowerCase()); message = new StringBuilder(methods.color(message.toString().replace(ph, placeholders.get(ph))).replace(ph, placeholders.get(ph).toLowerCase()));
} }
return message; return message.toString();
} }
public static void addMissingMessages() { public static void addMissingMessages() {
FileConfiguration messages = Files.MESSAGES.getFile(); FileConfiguration messages = Files.MESSAGES.getFile();
boolean saveFile = false; boolean saveFile = false;
for (Messages message : values()) { for (Messages message : values()) {
if (!messages.contains("Messages." + message.getPath())) { if (!messages.contains("Messages." + message.getPath())) {
saveFile = true; saveFile = true;
if (message.getDefaultMessage() != null) { if (message.getDefaultMessage() != null) {
messages.set("Messages." + message.getPath(), message.getDefaultMessage()); messages.set("Messages." + message.getPath(), message.getDefaultMessage());
} else { } else {
@ -102,23 +111,22 @@ public enum Messages {
} }
} }
} }
if (saveFile) {
Files.MESSAGES.saveFile(); if (saveFile) Files.MESSAGES.saveFile();
}
} }
public String getMessage() { public String getMessage() {
if (isList()) { if (isList()) {
if (exists()) { if (exists()) {
return Methods.color(convertList(Files.MESSAGES.getFile().getStringList("Messages." + path))); return methods.color(convertList(Files.MESSAGES.getFile().getStringList("Messages." + path)));
} else { } else {
return Methods.color(convertList(getDefaultListMessage())); return methods.color(convertList(getDefaultListMessage()));
} }
} else { } else {
if (exists()) { if (exists()) {
return Methods.getPrefix(Files.MESSAGES.getFile().getString("Messages." + path)); return methods.getPrefix(Files.MESSAGES.getFile().getString("Messages." + path));
} else { } else {
return Methods.getPrefix(getDefaultMessage()); return methods.getPrefix(getDefaultMessage());
} }
} }
} }
@ -127,20 +135,18 @@ public enum Messages {
String message; String message;
if (isList()) { if (isList()) {
if (exists()) { if (exists()) {
message = Methods.color(convertList(Files.MESSAGES.getFile().getStringList("Messages." + path), placeholders)); message = methods.color(convertList(Files.MESSAGES.getFile().getStringList("Messages." + path), placeholders));
} else { } else {
message = Methods.color(convertList(getDefaultListMessage(), placeholders)); message = methods.color(convertList(getDefaultListMessage(), placeholders));
} }
} else { } else {
if (exists()) { if (exists()) {
message = Methods.getPrefix(Files.MESSAGES.getFile().getString("Messages." + path)); message = methods.getPrefix(Files.MESSAGES.getFile().getString("Messages." + path));
} else { } else {
message = Methods.getPrefix(getDefaultMessage()); message = methods.getPrefix(getDefaultMessage());
} }
for (String ph : placeholders.keySet()) { for (String ph : placeholders.keySet()) {
if (message.contains(ph)) { if (message.contains(ph)) message = message.replace(ph, placeholders.get(ph)).replace(ph, placeholders.get(ph).toLowerCase());
message = message.replace(ph, placeholders.get(ph)).replace(ph, placeholders.get(ph).toLowerCase());
}
} }
} }
return message; return message;
@ -149,15 +155,15 @@ public enum Messages {
public String getMessageNoPrefix() { public String getMessageNoPrefix() {
if (isList()) { if (isList()) {
if (exists()) { if (exists()) {
return Methods.color(convertList(Files.MESSAGES.getFile().getStringList("Messages." + path))); return methods.color(convertList(Files.MESSAGES.getFile().getStringList("Messages." + path)));
} else { } else {
return Methods.color(convertList(getDefaultListMessage())); return methods.color(convertList(getDefaultListMessage()));
} }
} else { } else {
if (exists()) { if (exists()) {
return Methods.color(Files.MESSAGES.getFile().getString("Messages." + path)); return methods.color(Files.MESSAGES.getFile().getString("Messages." + path));
} else { } else {
return Methods.color(getDefaultMessage()); return methods.color(getDefaultMessage());
} }
} }
} }
@ -166,20 +172,18 @@ public enum Messages {
String message; String message;
if (isList()) { if (isList()) {
if (exists()) { if (exists()) {
message = Methods.color(convertList(Files.MESSAGES.getFile().getStringList("Messages." + path), placeholders)); message = methods.color(convertList(Files.MESSAGES.getFile().getStringList("Messages." + path), placeholders));
} else { } else {
message = Methods.color(convertList(getDefaultListMessage(), placeholders)); message = methods.color(convertList(getDefaultListMessage(), placeholders));
} }
} else { } else {
if (exists()) { if (exists()) {
message = Methods.color(Files.MESSAGES.getFile().getString("Messages." + path)); message = methods.color(Files.MESSAGES.getFile().getString("Messages." + path));
} else { } else {
message = Methods.color(getDefaultMessage()); message = methods.color(getDefaultMessage());
} }
for (String ph : placeholders.keySet()) { for (String ph : placeholders.keySet()) {
if (message.contains(ph)) { if (message.contains(ph)) message = message.replace(ph, placeholders.get(ph)).replace(ph, placeholders.get(ph).toLowerCase());
message = message.replace(ph, placeholders.get(ph)).replace(ph, placeholders.get(ph).toLowerCase());
}
} }
} }
return message; return message;
@ -208,5 +212,4 @@ public enum Messages {
private List<String> getDefaultListMessage() { private List<String> getDefaultListMessage() {
return defaultListMessage; return defaultListMessage;
} }
} }

View File

@ -6,21 +6,18 @@ import org.bukkit.event.HandlerList;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
/** /**
*
* @author BadBones69 * @author BadBones69
* *
* This event is fired when a player buys something from the selling auction house. * This event is fired when a player buys something from the selling auction house.
*
*/ */
public class AuctionBuyEvent extends Event { public class AuctionBuyEvent extends Event {
private static final HandlerList handlers = new HandlerList(); private final HandlerList handlers = new HandlerList();
private Player player; private final Player player;
private long price; private final long price;
private ItemStack item; private final ItemStack item;
/** /**
*
* @param player The player who bought the item. * @param player The player who bought the item.
* @param item The item that was bought. * @param item The item that was bought.
* @param price The price of the item. * @param price The price of the item.
@ -31,10 +28,6 @@ public class AuctionBuyEvent extends Event {
this.price = price; this.price = price;
} }
public static HandlerList getHandlerList() {
return handlers;
}
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
@ -50,5 +43,4 @@ public class AuctionBuyEvent extends Event {
public long getPrice() { public long getPrice() {
return price; return price;
} }
} }

View File

@ -8,23 +8,20 @@ import org.bukkit.event.HandlerList;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
/** /**
*
* @author BadBones69 * @author BadBones69
* *
* This event is fired when a player's item is cancelled. * This event is fired when a player's item is cancelled.
*
*/ */
public class AuctionCancelledEvent extends Event { public class AuctionCancelledEvent extends Event {
private static final HandlerList handlers = new HandlerList(); private final HandlerList handlers = new HandlerList();
private OfflinePlayer offlinePlayer; private OfflinePlayer offlinePlayer;
private Player onlinePlayer; private Player onlinePlayer;
private boolean isOnline; private final boolean isOnline;
private ItemStack item; private final ItemStack item;
private CancelledReason reason; private final CancelledReason reason;
/** /**
*
* @param offlinePlayer The player whose item is cancelled. * @param offlinePlayer The player whose item is cancelled.
* @param item The item that is cancelled. * @param item The item that is cancelled.
*/ */
@ -36,7 +33,6 @@ public class AuctionCancelledEvent extends Event {
} }
/** /**
*
* @param onlinePlayer The player whose item is cancelled. * @param onlinePlayer The player whose item is cancelled.
* @param item The item that is cancelled. * @param item The item that is cancelled.
*/ */
@ -47,10 +43,6 @@ public class AuctionCancelledEvent extends Event {
this.reason = reason; this.reason = reason;
} }
public static HandlerList getHandlerList() {
return handlers;
}
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
@ -74,5 +66,4 @@ public class AuctionCancelledEvent extends Event {
public CancelledReason getReason() { public CancelledReason getReason() {
return reason; return reason;
} }
} }

View File

@ -7,22 +7,19 @@ import org.bukkit.event.HandlerList;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
/** /**
*
* @author BadBones69 * @author BadBones69
* *
* This event is fired when a player item expires. * This event is fired when a player item expires.
*
*/ */
public class AuctionExpireEvent extends Event { public class AuctionExpireEvent extends Event {
private static final HandlerList handlers = new HandlerList(); private final HandlerList handlers = new HandlerList();
private OfflinePlayer offlinePlayer; private OfflinePlayer offlinePlayer;
private Player onlinePlayer; private Player onlinePlayer;
private boolean isOnline; private final boolean isOnline;
private ItemStack item; private final ItemStack item;
/** /**
*
* @param offlinePlayer The player whose item is expiring. * @param offlinePlayer The player whose item is expiring.
* @param item The item that is expiring. * @param item The item that is expiring.
*/ */
@ -33,7 +30,6 @@ public class AuctionExpireEvent extends Event {
} }
/** /**
*
* @param onlinePlayer The player whose item is expiring. * @param onlinePlayer The player whose item is expiring.
* @param item The item that is expiring. * @param item The item that is expiring.
*/ */
@ -43,10 +39,6 @@ public class AuctionExpireEvent extends Event {
this.isOnline = true; this.isOnline = true;
} }
public static HandlerList getHandlerList() {
return handlers;
}
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
@ -66,5 +58,4 @@ public class AuctionExpireEvent extends Event {
public ItemStack getItem() { public ItemStack getItem() {
return item; return item;
} }
} }

View File

@ -1,44 +1,37 @@
package com.badbones69.crazyauctions.api.events; package com.badbones69.crazyauctions.api.events;
import com.badbones69.crazyauctions.api.ShopType; import com.badbones69.crazyauctions.api.enums.ShopCategories;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
/** /**
*
* @author BadBones69 * @author BadBones69
* *
* This event is fired when a new item is listed onto the auction house. * This event is fired when a new item is listed onto the auction house.
*
*/ */
public class AuctionListEvent extends Event { public class AuctionListEvent extends Event {
private static final HandlerList handlers = new HandlerList(); private final HandlerList handlers = new HandlerList();
private Player player; private final Player player;
private long price; private final long price;
private ShopType shop; private final ShopCategories shop;
private ItemStack item; private final ItemStack item;
/** /**
*
* @param player The player who is listing the item. * @param player The player who is listing the item.
* @param shop The shop type the item is being listed to. * @param shop The shop type the item is being listed to.
* @param item The item being listed. * @param item The item being listed.
* @param price The price the item is being listed for. * @param price The price the item is being listed for.
*/ */
public AuctionListEvent(Player player, ShopType shop, ItemStack item, long price) { public AuctionListEvent(Player player, ShopCategories shop, ItemStack item, long price) {
this.player = player; this.player = player;
this.shop = shop; this.shop = shop;
this.item = item; this.item = item;
this.price = price; this.price = price;
} }
public static HandlerList getHandlerList() {
return handlers;
}
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
@ -47,7 +40,7 @@ public class AuctionListEvent extends Event {
return player; return player;
} }
public ShopType getShopType() { public ShopCategories getShopType() {
return shop; return shop;
} }
@ -58,5 +51,4 @@ public class AuctionListEvent extends Event {
public long getPrice() { public long getPrice() {
return price; return price;
} }
} }

View File

@ -6,18 +6,16 @@ import org.bukkit.event.HandlerList;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
/** /**
*
* This event is fired when a player places a new bid onto an item in the auction house. * This event is fired when a player places a new bid onto an item in the auction house.
*/ */
public class AuctionNewBidEvent extends Event { public class AuctionNewBidEvent extends Event {
private static final HandlerList handlers = new HandlerList(); private final HandlerList handlers = new HandlerList();
private Player player; private final Player player;
private long bid; private final long bid;
private ItemStack item; private final ItemStack item;
/** /**
*
* @param player The player who placed the bid. * @param player The player who placed the bid.
* @param item The item that was bid on. * @param item The item that was bid on.
* @param bid The amount of money that was bid. * @param bid The amount of money that was bid.
@ -28,10 +26,6 @@ public class AuctionNewBidEvent extends Event {
this.bid = bid; this.bid = bid;
} }
public static HandlerList getHandlerList() {
return handlers;
}
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
@ -47,5 +41,4 @@ public class AuctionNewBidEvent extends Event {
public long getBid() { public long getBid() {
return bid; return bid;
} }
} }

View File

@ -6,21 +6,18 @@ import org.bukkit.event.HandlerList;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
/** /**
*
* @author BadBones69 * @author BadBones69
* *
* This event is fired when a bidding item's time has run out and so a player wins the item. * This event is fired when a bidding item's time has run out and so a player wins the item.
*
*/ */
public class AuctionWinBidEvent extends Event { public class AuctionWinBidEvent extends Event {
private static final HandlerList handlers = new HandlerList(); private final HandlerList handlers = new HandlerList();
private Player player; private final Player player;
private long bid; private final long bid;
private ItemStack item; private final ItemStack item;
/** /**
*
* @param player The player who won the item. * @param player The player who won the item.
* @param item The item that was won. * @param item The item that was won.
* @param bid The bid that was placed on the item. * @param bid The bid that was placed on the item.
@ -31,10 +28,6 @@ public class AuctionWinBidEvent extends Event {
this.bid = bid; this.bid = bid;
} }
public static HandlerList getHandlerList() {
return handlers;
}
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
@ -50,5 +43,4 @@ public class AuctionWinBidEvent extends Event {
public long getBid() { public long getBid() {
return bid; return bid;
} }
} }

View File

@ -0,0 +1,120 @@
package com.badbones69.crazyauctions.utils.func;
import com.badbones69.crazyauctions.CrazyAuctions;
/**
* @author Badbones69
*/
public enum ServerProtocol {
TOO_OLD(-1),
v1_7_R1(171), v1_7_R2(172), v1_7_R3(173), v1_7_R4(174),
v1_8_R1(181), v1_8_R2(182), v1_8_R3(183),
v1_9_R1(191), v1_9_R2(192),
v1_10_R1(1101),
v1_11_R1(1111),
v1_12_R1(1121),
v1_13_R2(1132),
v1_14_R1(1141),
v1_15_R1(1151),
v1_16_R1(1161), v1_16_R2(1162), v1_16_R3(1163),
v1_17_R1(1171),
v1_18_R1(1181),
v1_18_R2(1182),
v1_19(1191),
TOO_NEW(-2);
private static ServerProtocol currentProtocol;
private static ServerProtocol latest;
private final int versionProtocol;
private static final CrazyAuctions plugin = CrazyAuctions.getPlugin();
ServerProtocol(int versionProtocol) {
this.versionProtocol = versionProtocol;
}
public static ServerProtocol getCurrentProtocol() {
String serVer = plugin.getServer().getClass().getPackage().getName();
int serProt = Integer.parseInt(
serVer.substring(
serVer.lastIndexOf('.') + 1
).replace("_", "").replace("R", "").replace("v", "")
);
for (ServerProtocol protocol : values()) {
if (protocol.versionProtocol == serProt) {
currentProtocol = protocol;
break;
}
}
if (currentProtocol == null) currentProtocol = ServerProtocol.TOO_NEW;
return currentProtocol;
}
public static boolean isLegacy() {
return isOlder(ServerProtocol.v1_18_R1);
}
public static ServerProtocol getLatestProtocol() {
if (latest != null) return latest;
ServerProtocol old = ServerProtocol.TOO_OLD;
for (ServerProtocol protocol : values()) {
if (protocol.compare(old) == 1) {
old = protocol;
}
}
return old;
}
public static boolean isAtLeast(ServerProtocol protocol) {
if (currentProtocol == null) getCurrentProtocol();
int proto = currentProtocol.versionProtocol;
return proto >= protocol.versionProtocol || proto == -2;
}
public static boolean isNewer(ServerProtocol protocol) {
if (currentProtocol == null) getCurrentProtocol();
return currentProtocol.versionProtocol > protocol.versionProtocol || currentProtocol.versionProtocol == -2;
}
public static boolean isSame(ServerProtocol protocol) {
if (currentProtocol == null) getCurrentProtocol();
return currentProtocol.versionProtocol == protocol.versionProtocol;
}
public static boolean isOlder(ServerProtocol protocol) {
if (currentProtocol == null) getCurrentProtocol();
int proto = currentProtocol.versionProtocol;
return proto < protocol.versionProtocol || proto == -1;
}
public int compare(ServerProtocol protocol) {
int result = -1;
int current = versionProtocol;
int check = protocol.versionProtocol;
if (current > check || check == -2) {
result = 1;
} else if (current == check) {
result = 0;
}
return result;
}
}