3
0
Mirror von https://github.com/TheSilentPro/HeadDB.git synchronisiert 2024-12-27 11:20:05 +01:00

patch a lot of code smells and possible bugs (4.2.2)

Dieser Commit ist enthalten in:
Silent 2022-03-18 18:37:38 +01:00
Ursprung f8227081c0
Commit ef90061b70
16 geänderte Dateien mit 165 neuen und 196 gelöschten Zeilen

Datei anzeigen

@ -67,7 +67,7 @@ public class HeadDB extends JavaPlugin {
initMetrics(); initMetrics();
Utils.isLatestVersion(this, 84967, latest -> { Utils.isLatestVersion(this, 84967, latest -> {
if (!latest) { if (!Boolean.TRUE.equals(latest)) {
Log.warning("There is a new update available for HeadDB on spigot!"); Log.warning("There is a new update available for HeadDB on spigot!");
Log.warning("Download: https://www.spigotmc.org/resources/84967"); Log.warning("Download: https://www.spigotmc.org/resources/84967");
} }
@ -112,10 +112,6 @@ public class HeadDB extends JavaPlugin {
private void initMetrics() { private void initMetrics() {
Metrics metrics = new Metrics(this, 9152); Metrics metrics = new Metrics(this, 9152);
if (!metrics.isEnabled()) {
Log.debug("Metrics are disabled.");
return;
}
metrics.addCustomChart(new Metrics.SimplePie("economy_provider", () -> { metrics.addCustomChart(new Metrics.SimplePie("economy_provider", () -> {
if (this.getEconomyProvider() != null) { if (this.getEconomyProvider() != null) {

Datei anzeigen

@ -2,7 +2,6 @@ package tsp.headdb.api;
import org.apache.commons.lang.Validate; import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import tsp.headdb.HeadDB; import tsp.headdb.HeadDB;
import tsp.headdb.implementation.Category; import tsp.headdb.implementation.Category;
@ -14,8 +13,8 @@ import tsp.headdb.storage.PlayerDataFile;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.UUID; import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -29,6 +28,11 @@ public final class HeadAPI {
private HeadAPI() {} private HeadAPI() {}
private static final String VALIDATION_PLAYER_NULL = "Player can not be null!";
private static final String VALIDATION_CATEGORY_NULL = "Category can not be null!";
private static final String VALIDATION_UUID_NULL = "UUID can not be null!";
private static final String VALIDATION_VALUE_NULL = "Value can not be null!";
/** /**
* Main {@link HeadDatabase} that he HeadDB plugin uses. * Main {@link HeadDatabase} that he HeadDB plugin uses.
*/ */
@ -49,7 +53,7 @@ public final class HeadAPI {
* @param player Target player * @param player Target player
*/ */
public static void openDatabase(@Nonnull Player player) { public static void openDatabase(@Nonnull Player player) {
Validate.notNull(player, "Player can not be null!"); Validate.notNull(player, VALIDATION_PLAYER_NULL);
InventoryUtils.openDatabase(player); InventoryUtils.openDatabase(player);
} }
@ -61,8 +65,8 @@ public final class HeadAPI {
* @param category Category to open * @param category Category to open
*/ */
public static void openCategoryDatabase(@Nonnull Player player, @Nonnull Category category) { public static void openCategoryDatabase(@Nonnull Player player, @Nonnull Category category) {
Validate.notNull(player, "Player can not be null!"); Validate.notNull(player, VALIDATION_PLAYER_NULL);
Validate.notNull(category, "Category can not be null!"); Validate.notNull(category, VALIDATION_CATEGORY_NULL);
InventoryUtils.openCategoryDatabase(player, category); InventoryUtils.openCategoryDatabase(player, category);
} }
@ -74,7 +78,7 @@ public final class HeadAPI {
* @param search Search term * @param search Search term
*/ */
public static void openSearchDatabase(@Nonnull Player player, @Nonnull String search) { public static void openSearchDatabase(@Nonnull Player player, @Nonnull String search) {
Validate.notNull(player, "Player can not be null!"); Validate.notNull(player, VALIDATION_PLAYER_NULL);
Validate.notNull(search, "Search can not be null!"); Validate.notNull(search, "Search can not be null!");
InventoryUtils.openSearchDatabase(player, search); InventoryUtils.openSearchDatabase(player, search);
@ -87,7 +91,7 @@ public final class HeadAPI {
* @param tag Tag search term * @param tag Tag search term
*/ */
public static void openTagSearchDatabase(@Nonnull Player player, @Nonnull String tag) { public static void openTagSearchDatabase(@Nonnull Player player, @Nonnull String tag) {
Validate.notNull(player, "Player can not be null!"); Validate.notNull(player, VALIDATION_PLAYER_NULL);
Validate.notNull(tag, "Tag can not be null!"); Validate.notNull(tag, "Tag can not be null!");
InventoryUtils.openTagSearchDatabase(player, tag); InventoryUtils.openTagSearchDatabase(player, tag);
@ -112,7 +116,7 @@ public final class HeadAPI {
*/ */
@Nullable @Nullable
public static Head getHeadByUniqueId(@Nonnull UUID uuid) { public static Head getHeadByUniqueId(@Nonnull UUID uuid) {
Validate.notNull(uuid, "UUID can not be null!"); Validate.notNull(uuid, VALIDATION_UUID_NULL);
return database.getHeadByUniqueId(uuid); return database.getHeadByUniqueId(uuid);
} }
@ -152,7 +156,7 @@ public final class HeadAPI {
*/ */
@Nonnull @Nonnull
public static List<Head> getHeadsByName(@Nonnull Category category, @Nonnull String name) { public static List<Head> getHeadsByName(@Nonnull Category category, @Nonnull String name) {
Validate.notNull(category, "Category can not be null!"); Validate.notNull(category, VALIDATION_CATEGORY_NULL);
Validate.notNull(name, "Name can not be null!"); Validate.notNull(name, "Name can not be null!");
return database.getHeadsByName(category, name); return database.getHeadsByName(category, name);
@ -166,7 +170,7 @@ public final class HeadAPI {
*/ */
@Nullable @Nullable
public static Head getHeadByValue(@Nonnull String value) { public static Head getHeadByValue(@Nonnull String value) {
Validate.notNull(value, "Value can not be null!"); Validate.notNull(value, VALIDATION_VALUE_NULL);
return database.getHeadByValue(value); return database.getHeadByValue(value);
} }
@ -179,7 +183,7 @@ public final class HeadAPI {
*/ */
@Nonnull @Nonnull
public static List<Head> getHeads(@Nonnull Category category) { public static List<Head> getHeads(@Nonnull Category category) {
Validate.notNull(category, "Category can not be null!"); Validate.notNull(category, VALIDATION_CATEGORY_NULL);
return database.getHeads(category); return database.getHeads(category);
} }
@ -201,8 +205,8 @@ public final class HeadAPI {
* @param textureValue The head's texture value * @param textureValue The head's texture value
*/ */
public static void addFavoriteHead(@Nonnull UUID uuid, @Nonnull String textureValue) { public static void addFavoriteHead(@Nonnull UUID uuid, @Nonnull String textureValue) {
Validate.notNull(uuid, "UUID can not be null!"); Validate.notNull(uuid, VALIDATION_UUID_NULL);
Validate.notNull(textureValue, "Value can not be null!"); Validate.notNull(textureValue, VALIDATION_VALUE_NULL);
HeadDB.getInstance().getPlayerData().modifyFavorite(uuid, textureValue, PlayerDataFile.ModificationType.SET); HeadDB.getInstance().getPlayerData().modifyFavorite(uuid, textureValue, PlayerDataFile.ModificationType.SET);
} }
@ -214,8 +218,8 @@ public final class HeadAPI {
* @param textureValue The head's texture value * @param textureValue The head's texture value
*/ */
public static void removeFavoriteHead(@Nonnull UUID uuid, @Nonnull String textureValue) { public static void removeFavoriteHead(@Nonnull UUID uuid, @Nonnull String textureValue) {
Validate.notNull(uuid, "UUID can not be null!"); Validate.notNull(uuid, VALIDATION_UUID_NULL);
Validate.notNull(textureValue, "Value can not be null!"); Validate.notNull(textureValue, VALIDATION_VALUE_NULL);
HeadDB.getInstance().getPlayerData().modifyFavorite(uuid, textureValue, PlayerDataFile.ModificationType.REMOVE); HeadDB.getInstance().getPlayerData().modifyFavorite(uuid, textureValue, PlayerDataFile.ModificationType.REMOVE);
} }
@ -228,12 +232,12 @@ public final class HeadAPI {
*/ */
@Nonnull @Nonnull
public static List<Head> getFavoriteHeads(@Nonnull UUID uuid) { public static List<Head> getFavoriteHeads(@Nonnull UUID uuid) {
Validate.notNull(uuid, "UUID can not be null!"); Validate.notNull(uuid, VALIDATION_UUID_NULL);
return HeadDB.getInstance().getPlayerData().getFavoriteHeadsByTexture(uuid).stream() return HeadDB.getInstance().getPlayerData().getFavoriteHeadsByTexture(uuid).stream()
.map(HeadAPI::getHeadByValue) .map(HeadAPI::getHeadByValue)
.filter(head -> head != null) .filter(Objects::nonNull)
.collect(Collectors.toList()); .toList();
} }
/** /**
@ -248,7 +252,7 @@ public final class HeadAPI {
return HeadDB.getInstance().getPlayerData().getEntries().stream() return HeadDB.getInstance().getPlayerData().getEntries().stream()
.map(entry -> Bukkit.getOfflinePlayer(UUID.fromString(entry))) .map(entry -> Bukkit.getOfflinePlayer(UUID.fromString(entry)))
.map(player -> new LocalHead(player.getUniqueId()).name(player.getName())) .map(player -> new LocalHead(player.getUniqueId()).name(player.getName()))
.collect(Collectors.toList()); .toList();
} }
} }

Datei anzeigen

@ -11,23 +11,21 @@ import tsp.headdb.util.Utils;
public class HeadDBCommand implements CommandExecutor { public class HeadDBCommand implements CommandExecutor {
@Override private void handle(CommandSender sender, String[] args) {
public boolean onCommand(CommandSender sender, Command command, String s, String[] args) {
Localization localization = HeadDB.getInstance().getLocalization(); Localization localization = HeadDB.getInstance().getLocalization();
if (args.length == 0) { if (args.length == 0) {
if (!sender.hasPermission("headdb.open")) { if (!sender.hasPermission("headdb.open")) {
Utils.sendMessage(sender, localization.getMessage("noPermission")); Utils.sendMessage(sender, localization.getMessage("noPermission"));
return true; return;
} }
if (!(sender instanceof Player)) { if (!(sender instanceof Player player)) {
Utils.sendMessage(sender, localization.getMessage("onlyPlayers")); Utils.sendMessage(sender, localization.getMessage("onlyPlayers"));
return true; return;
} }
Player player = (Player) sender;
Utils.sendMessage(player, localization.getMessage("databaseOpen")); Utils.sendMessage(player, localization.getMessage("databaseOpen"));
HeadAPI.openDatabase(player); HeadAPI.openDatabase(player);
return true; return;
} }
String sub = args[0]; String sub = args[0];
@ -48,7 +46,7 @@ public class HeadDBCommand implements CommandExecutor {
if (subCommand != null) { if (subCommand != null) {
subCommand.handle(sender, args); subCommand.handle(sender, args);
return true; return;
} }
Utils.sendMessage(sender, " "); Utils.sendMessage(sender, " ");
@ -62,6 +60,11 @@ public class HeadDBCommand implements CommandExecutor {
Utils.sendMessage(sender, "&7 > &c/hdb update &9(u) &7- Forcefully update the database"); Utils.sendMessage(sender, "&7 > &c/hdb update &9(u) &7- Forcefully update the database");
Utils.sendMessage(sender, "&7 > &c/hdb give &9(g) &c<id> <player> &6[amount] &7- Give player a head"); Utils.sendMessage(sender, "&7 > &c/hdb give &9(g) &c<id> <player> &6[amount] &7- Give player a head");
Utils.sendMessage(sender, " "); Utils.sendMessage(sender, " ");
}
@Override
public boolean onCommand(CommandSender sender, Command command, String s, String[] args) {
handle(sender, args);
return true; return true;
} }

Datei anzeigen

@ -13,11 +13,10 @@ public class SearchCommand implements HeadSubCommand {
Utils.sendMessage(sender, getLocalization().getMessage("noPermission")); Utils.sendMessage(sender, getLocalization().getMessage("noPermission"));
return; return;
} }
if (!(sender instanceof Player)) { if (!(sender instanceof Player player)) {
Utils.sendMessage(sender, getLocalization().getMessage("onlyPlayers")); Utils.sendMessage(sender, getLocalization().getMessage("onlyPlayers"));
return; return;
} }
Player player = (Player) sender;
if (args.length < 2) { if (args.length < 2) {
Utils.sendMessage(player, "&c/hdb search <name>"); Utils.sendMessage(player, "&c/hdb search <name>");
@ -34,7 +33,6 @@ public class SearchCommand implements HeadSubCommand {
String name = builder.toString(); String name = builder.toString();
Utils.sendMessage(sender, "&7Searching for &e" + name); Utils.sendMessage(sender, "&7Searching for &e" + name);
HeadAPI.openSearchDatabase(player, name); HeadAPI.openSearchDatabase(player, name);
return;
} }
} }

Datei anzeigen

@ -19,16 +19,14 @@ public class TagSearchCommand implements HeadSubCommand {
return; return;
} }
if (!(sender instanceof Player)) { if (!(sender instanceof Player player)) {
Utils.sendMessage(sender, getLocalization().getMessage("onlyPlayers")); Utils.sendMessage(sender, getLocalization().getMessage("onlyPlayers"));
return; return;
} }
Player player = (Player) sender;
String tag = args[1]; String tag = args[1];
Utils.sendMessage(sender, "&7Searching for heads with tag &e" + tag); Utils.sendMessage(sender, "&7Searching for heads with tag &e" + tag);
HeadAPI.openTagSearchDatabase(player, tag); HeadAPI.openTagSearchDatabase(player, tag);
return;
} }
} }

Datei anzeigen

@ -34,16 +34,14 @@ public class TreasuryProvider implements BasicEconomyProvider {
EconomySubscriber EconomySubscriber
.<Boolean>asFuture(s -> provider.hasPlayerAccount(player.getUniqueId(), s)) .<Boolean>asFuture(s -> provider.hasPlayerAccount(player.getUniqueId(), s))
.thenCompose(val -> { .thenCompose(val -> {
if (val) { if (Boolean.TRUE.equals(val)) {
return EconomySubscriber.<PlayerAccount>asFuture(s -> provider.retrievePlayerAccount(player.getUniqueId(), s)); return EconomySubscriber.<PlayerAccount>asFuture(s -> provider.retrievePlayerAccount(player.getUniqueId(), s));
} else { } else {
return EconomySubscriber.<PlayerAccount>asFuture(s -> provider.createPlayerAccount(player.getUniqueId(), s)); return EconomySubscriber.<PlayerAccount>asFuture(s -> provider.createPlayerAccount(player.getUniqueId(), s));
} }
}) })
.thenCompose(account -> EconomySubscriber.<BigDecimal>asFuture(s -> account.retrieveBalance(currency, s))) .thenCompose(account -> EconomySubscriber.<BigDecimal>asFuture(s -> account.retrieveBalance(currency, s)))
.whenComplete((bal, ex) -> { .whenComplete((bal, ex) -> result.accept(bal.compareTo(cost) >= 0));
result.accept(bal.compareTo(cost) >= 0);
});
} }
@Override @Override
@ -51,29 +49,27 @@ public class TreasuryProvider implements BasicEconomyProvider {
EconomySubscriber EconomySubscriber
.<Boolean>asFuture(s -> provider.hasPlayerAccount(player.getUniqueId(), s)) .<Boolean>asFuture(s -> provider.hasPlayerAccount(player.getUniqueId(), s))
.thenCompose(val -> { .thenCompose(val -> {
if (val) { if (Boolean.TRUE.equals(val)) {
return EconomySubscriber.<PlayerAccount>asFuture(s -> provider.retrievePlayerAccount(player.getUniqueId(), s)); return EconomySubscriber.<PlayerAccount>asFuture(s -> provider.retrievePlayerAccount(player.getUniqueId(), s));
} else { } else {
return EconomySubscriber.<PlayerAccount>asFuture(s -> provider.createPlayerAccount(player.getUniqueId(), s)); return EconomySubscriber.<PlayerAccount>asFuture(s -> provider.createPlayerAccount(player.getUniqueId(), s));
} }
}).whenComplete((account, ex) -> { }).whenComplete((account, ex) -> account.withdrawBalance(
account.withdrawBalance( amount,
amount, transactionInitiator,
transactionInitiator, currency,
currency, new EconomySubscriber<BigDecimal>() {
new EconomySubscriber<BigDecimal>() { @Override
@Override public void succeed(@NotNull BigDecimal bigDecimal) {
public void succeed(@NotNull BigDecimal bigDecimal) { result.accept(true);
result.accept(true); }
}
@Override @Override
public void fail(@NotNull EconomyException exception) { public void fail(@NotNull EconomyException exception) {
result.accept(false); result.accept(false);
exception.printStackTrace(); Log.error(ex);
} }
}); }));
});
} }
@Override @Override
@ -92,9 +88,10 @@ public class TreasuryProvider implements BasicEconomyProvider {
if (rawCurrency == null || rawCurrency.isEmpty()) { if (rawCurrency == null || rawCurrency.isEmpty()) {
currency = provider.getPrimaryCurrency(); currency = provider.getPrimaryCurrency();
} else { } else {
currency = provider.getCurrencies().stream() provider.getCurrencies().stream()
.filter(currency -> currency.getIdentifier().equalsIgnoreCase(rawCurrency)) .filter(currency -> currency.getIdentifier().equalsIgnoreCase(rawCurrency))
.findFirst().get(); .findFirst()
.ifPresentOrElse(c -> currency = c, () -> Log.error("Could not find currency: " + rawCurrency));
} }
} }

Datei anzeigen

@ -1,12 +1,13 @@
package tsp.headdb.implementation; package tsp.headdb.implementation;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import tsp.headdb.api.HeadAPI; import tsp.headdb.api.HeadAPI;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.HashMap; import java.util.Objects;
import java.util.Map; import java.util.Optional;
/** /**
* Represents a category for heads * Represents a category for heads
@ -29,8 +30,7 @@ public enum Category {
private final String name; private final String name;
private final ChatColor color; private final ChatColor color;
private final int location; private final int location;
private final Map<Category, Head> item = new HashMap<>(); private static final Category[] cache = values();
public static final Category[] cache = values();
Category(String name, ChatColor color, int location) { Category(String name, ChatColor color, int location) {
this.name = name; this.name = name;
@ -56,9 +56,15 @@ public enum Category {
* @return First valid head * @return First valid head
*/ */
public ItemStack getItem() { public ItemStack getItem() {
return HeadAPI.getHeads(this).stream() Optional<Head> result = HeadAPI.getHeads(this).stream()
.filter(head -> head != null) .filter(Objects::nonNull)
.findFirst().get().getMenuItem(); .findFirst();
if (result.isPresent()) {
return result.get().getMenuItem();
} else {
return new ItemStack(Material.PLAYER_HEAD);
}
} }
/** /**
@ -78,4 +84,8 @@ public enum Category {
return null; return null;
} }
public static Category[] getCache() {
return cache;
}
} }

Datei anzeigen

@ -28,7 +28,6 @@ public class Head {
private int id; private int id;
private List<String> tags; private List<String> tags;
private ItemStack menuItem; private ItemStack menuItem;
//Unimplemented private ItemStack itemStack;
public Head() {} public Head() {}
@ -55,7 +54,7 @@ public class Head {
profileField.set(meta, profile); profileField.set(meta, profile);
} catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException ex) { } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException ex) {
Log.error("Could not set skull owner for " + uuid.toString() + " | Stack Trace:"); Log.error("Could not set skull owner for " + uuid.toString() + " | Stack Trace:");
ex.printStackTrace(); Log.error(ex);
} }
meta.setLore(Arrays.asList( meta.setLore(Arrays.asList(
@ -72,24 +71,6 @@ public class Head {
return menuItem; return menuItem;
} }
/* For some reason this causes issues with some heads in categories not having lore
public ItemStack getItemStack() {
if (itemStack == null) {
itemStack = menuItem;
ItemMeta meta = itemStack.getItemMeta();
meta.setDisplayName(HeadDB.getInstance().getLocalization().getMessage("head.name")
.replace("%name%", name)
.replace("%id%", String.valueOf(id))
.replace("%value%", value)
.replace("%tags%", buildTagLore(tags)));
meta.setLore(HeadDB.getInstance().getLocalization().getData().getStringList("head.lore"));
itemStack.setItemMeta(meta);
}
return itemStack;
}
*/
public String getName() { public String getName() {
return name; return name;
} }

Datei anzeigen

@ -19,6 +19,7 @@ import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@ -36,7 +37,7 @@ import javax.annotation.Nonnull;
public class HeadDatabase { public class HeadDatabase {
private final JavaPlugin plugin; private final JavaPlugin plugin;
private final Map<Category, List<Head>> HEADS = new HashMap<>(); private final EnumMap<Category, List<Head>> heads = new EnumMap<>(Category.class);
private long refresh; private long refresh;
private int timeout; private int timeout;
private long updated; private long updated;
@ -49,8 +50,8 @@ public class HeadDatabase {
} }
public Head getHeadByValue(String value) { public Head getHeadByValue(String value) {
List<Head> heads = getHeads(); List<Head> fetched = getHeads();
for (Head head : heads) { for (Head head : fetched) {
if (head.getValue().equals(value)) { if (head.getValue().equals(value)) {
return head; return head;
} }
@ -60,8 +61,8 @@ public class HeadDatabase {
} }
public Head getHeadByID(int id) { public Head getHeadByID(int id) {
List<Head> heads = getHeads(); List<Head> fetched = getHeads();
for (Head head : heads) { for (Head head : fetched) {
if (head.getId() == id) { if (head.getId() == id) {
return head; return head;
} }
@ -71,8 +72,8 @@ public class HeadDatabase {
} }
public Head getHeadByUniqueId(UUID uuid) { public Head getHeadByUniqueId(UUID uuid) {
List<Head> heads = getHeads(); List<Head> fetched = getHeads();
for (Head head : heads) { for (Head head : fetched) {
if (head.getUniqueId().equals(uuid)) { if (head.getUniqueId().equals(uuid)) {
return head; return head;
} }
@ -83,9 +84,9 @@ public class HeadDatabase {
public List<Head> getHeadsByTag(String tag) { public List<Head> getHeadsByTag(String tag) {
List<Head> result = new ArrayList<>(); List<Head> result = new ArrayList<>();
List<Head> heads = getHeads(); List<Head> fetched = getHeads();
tag = tag.toLowerCase(Locale.ROOT); tag = tag.toLowerCase(Locale.ROOT);
for (Head head : heads) { for (Head head : fetched) {
for (String t : head.getTags()) { for (String t : head.getTags()) {
if (t.toLowerCase(Locale.ROOT).contains(tag)) { if (t.toLowerCase(Locale.ROOT).contains(tag)) {
result.add(head); result.add(head);
@ -98,8 +99,8 @@ public class HeadDatabase {
public List<Head> getHeadsByName(Category category, String name) { public List<Head> getHeadsByName(Category category, String name) {
List<Head> result = new ArrayList<>(); List<Head> result = new ArrayList<>();
List<Head> heads = getHeads(category); List<Head> fetched = getHeads(category);
for (Head head : heads) { for (Head head : fetched) {
String hName = ChatColor.stripColor(head.getName().toLowerCase(Locale.ROOT)); String hName = ChatColor.stripColor(head.getName().toLowerCase(Locale.ROOT));
if (hName.contains(ChatColor.stripColor(name.toLowerCase(Locale.ROOT)))) { if (hName.contains(ChatColor.stripColor(name.toLowerCase(Locale.ROOT)))) {
result.add(head); result.add(head);
@ -111,7 +112,7 @@ public class HeadDatabase {
public List<Head> getHeadsByName(String name) { public List<Head> getHeadsByName(String name) {
List<Head> result = new ArrayList<>(); List<Head> result = new ArrayList<>();
for (Category category : Category.values()) { for (Category category : Category.getCache()) {
result.addAll(getHeadsByName(category, name)); result.addAll(getHeadsByName(category, name));
} }
@ -120,7 +121,7 @@ public class HeadDatabase {
@Nonnull @Nonnull
public List<Head> getHeads(Category category) { public List<Head> getHeads(Category category) {
return HEADS.get(category) != null ? Collections.unmodifiableList(HEADS.get(category)) : new ArrayList<>(); return heads.get(category) != null ? Collections.unmodifiableList(heads.get(category)) : new ArrayList<>();
} }
/** /**
@ -130,18 +131,18 @@ public class HeadDatabase {
*/ */
@Nonnull @Nonnull
public List<Head> getHeads() { public List<Head> getHeads() {
List<Head> heads = new ArrayList<>(); List<Head> result = new ArrayList<>();
for (Category category : HEADS.keySet()) { for (Category category : heads.keySet()) {
heads.addAll(getHeads(category)); result.addAll(getHeads(category));
} }
return heads; return result;
} }
public void getHeadsNoCache(Consumer<Map<Category, List<Head>>> resultSet) { public void getHeadsNoCache(Consumer<Map<Category, List<Head>>> resultSet) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, task -> { Bukkit.getScheduler().runTaskAsynchronously(plugin, task -> {
Log.debug("[" + plugin.getName() + "] Updating database... "); Log.debug("[" + plugin.getName() + "] Updating database... ");
Map<Category, List<Head>> result = new HashMap<>(); EnumMap<Category, List<Head>> result = new EnumMap<>(Category.class);
Category[] categories = Category.cache; Category[] categories = Category.getCache();
for (Category category : categories) { for (Category category : categories) {
Log.debug("Caching heads from: " + category.getName()); Log.debug("Caching heads from: " + category.getName());
@ -160,7 +161,7 @@ public class HeadDatabase {
heads = gather("https://heads.pages.dev/archive/" + category.getName() + ".json", category); heads = gather("https://heads.pages.dev/archive/" + category.getName() + ".json", category);
} catch (IOException | ParseException ex) { } catch (IOException | ParseException ex) {
Log.error("Failed to fetch heads for " + category.getName() + "! (OF)"); // OF = Original-Fallback, both failed Log.error("Failed to fetch heads for " + category.getName() + "! (OF)"); // OF = Original-Fallback, both failed
ex.printStackTrace(); Log.error(ex);
} }
} }
} }
@ -185,7 +186,7 @@ public class HeadDatabase {
*/ */
private List<Head> gather(String url, Category category) throws IOException, ParseException { private List<Head> gather(String url, Category category) throws IOException, ParseException {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
List<Head> heads = new ArrayList<>(); List<Head> headList = new ArrayList<>();
JSONParser parser = new JSONParser(); JSONParser parser = new JSONParser();
JSONArray array = (JSONArray) parser.parse(fetch(url)); JSONArray array = (JSONArray) parser.parse(fetch(url));
for (Object o : array) { for (Object o : array) {
@ -207,12 +208,12 @@ public class HeadDatabase {
.category(category); .category(category);
nextId++; nextId++;
heads.add(head); headList.add(head);
} }
long elapsed = (System.currentTimeMillis() - start); long elapsed = (System.currentTimeMillis() - start);
Log.debug(category.getName() + " -> Done! Time: " + elapsed + "ms (" + TimeUnit.MILLISECONDS.toSeconds(elapsed) + "s)"); Log.debug(category.getName() + " -> Done! Time: " + elapsed + "ms (" + TimeUnit.MILLISECONDS.toSeconds(elapsed) + "s)");
return heads; return headList;
} }
/** /**
@ -239,15 +240,15 @@ public class HeadDatabase {
} }
public void update(Consumer<Map<Category, List<Head>>> result) { public void update(Consumer<Map<Category, List<Head>>> result) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, task -> getHeadsNoCache(heads -> { Bukkit.getScheduler().runTaskAsynchronously(plugin, task -> getHeadsNoCache(headsList -> {
if (heads == null) { if (headsList == null) {
Log.error("[" + plugin.getName() + "] Failed to update database! Check above for any errors."); Log.error("[" + plugin.getName() + "] Failed to update database! Check above for any errors.");
result.accept(null); result.accept(null);
return; return;
} }
HEADS.clear(); heads.clear();
HEADS.putAll(heads); heads.putAll(headsList);
result.accept(heads); result.accept(heads);
Bukkit.getPluginManager().callEvent(new DatabaseUpdateEvent(this, heads)); Bukkit.getPluginManager().callEvent(new DatabaseUpdateEvent(this, heads));
})); }));

Datei anzeigen

@ -8,6 +8,7 @@ import org.bukkit.inventory.meta.SkullMeta;
import tsp.headdb.util.Utils; import tsp.headdb.util.Utils;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@ -68,7 +69,7 @@ public class LocalHead extends Head {
@Override @Override
public List<String> getTags() { public List<String> getTags() {
return null; return Collections.emptyList();
} }
@Override @Override

Datei anzeigen

@ -11,10 +11,10 @@ import java.util.function.Consumer;
*/ */
public class Button { public class Button {
private static int counter; private static int counter = 0;
private final int ID = counter++; private static final int id = counter++;
private ItemStack itemStack; private final ItemStack itemStack;
private Consumer<InventoryClickEvent> action; private Consumer<InventoryClickEvent> action;
/** /**
@ -67,15 +67,14 @@ public class Button {
if (this == o) { if (this == o) {
return true; return true;
} }
if (!(o instanceof Button)) { if (!(o instanceof Button button)) {
return false; return false;
} }
Button button = (Button) o; return id == button.id;
return ID == button.ID;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(ID); return Objects.hash(id);
} }
} }

Datei anzeigen

@ -31,6 +31,8 @@ import java.util.function.Consumer;
*/ */
public class InventoryUtils { public class InventoryUtils {
private InventoryUtils() {}
private static final Localization localization = HeadDB.getInstance().getLocalization(); private static final Localization localization = HeadDB.getInstance().getLocalization();
private static final Map<String, Integer> uiLocation = new HashMap<>(); private static final Map<String, Integer> uiLocation = new HashMap<>();
private static final Map<String, ItemStack> uiItem = new HashMap<>(); private static final Map<String, ItemStack> uiItem = new HashMap<>();
@ -179,7 +181,7 @@ public class InventoryUtils {
Inventory inventory = Bukkit.createInventory(null, 54, Inventory inventory = Bukkit.createInventory(null, 54,
replace(localization.getMessage("menu.main"), HeadAPI.getHeads().size(), "Main", "None", player)); replace(localization.getMessage("menu.main"), HeadAPI.getHeads().size(), "Main", "None", player));
for (Category category : Category.cache) { for (Category category : Category.getCache()) {
ItemStack item = getUIItem(category.getName(), category.getItem()); ItemStack item = getUIItem(category.getName(), category.getItem());
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
meta.setDisplayName(Utils.colorize(localization.getMessage("menu.heads." + category.getName()))); meta.setDisplayName(Utils.colorize(localization.getMessage("menu.heads." + category.getName())));
@ -325,9 +327,9 @@ public class InventoryUtils {
// If the cost is higher than zero, attempt to charge for it. // If the cost is higher than zero, attempt to charge for it.
if (cost.compareTo(BigDecimal.ZERO) > 0) { if (cost.compareTo(BigDecimal.ZERO) > 0) {
economyProvider.canPurchase(player, cost, paymentResult -> { economyProvider.canPurchase(player, cost, paymentResult -> {
if (paymentResult) { if (Boolean.TRUE.equals(paymentResult)) {
economyProvider.charge(player, cost, chargeResult -> { economyProvider.charge(player, cost, chargeResult -> {
if (chargeResult) { if (Boolean.TRUE.equals(chargeResult)) {
Utils.sendMessage(player, String.format(localization.getMessage("purchasedHead"), amount, description, cost)); Utils.sendMessage(player, String.format(localization.getMessage("purchasedHead"), amount, description, cost));
Utils.playSound(player, "paid"); Utils.playSound(player, "paid");
result.accept(true); result.accept(true);
@ -353,7 +355,7 @@ public class InventoryUtils {
public static void purchaseHead(Player player, Head head, int amount, String category, String description) { public static void purchaseHead(Player player, Head head, int amount, String category, String description) {
Utils.sendMessage(player, String.format(localization.getMessage("processPayment"), amount, head.getName())); Utils.sendMessage(player, String.format(localization.getMessage("processPayment"), amount, head.getName()));
processPayment(player, amount, category, description, result -> { processPayment(player, amount, category, description, result -> {
if (result) { if (Boolean.TRUE.equals(result)) {
PlayerHeadPurchaseEvent event = new PlayerHeadPurchaseEvent(player, head, getCategoryCost(player, category)); PlayerHeadPurchaseEvent event = new PlayerHeadPurchaseEvent(player, head, getCategoryCost(player, category));
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
if (!event.isCancelled()) { if (!event.isCancelled()) {

Datei anzeigen

@ -241,43 +241,41 @@ public class PagedPane implements InventoryHolder {
inventory.setItem(inventory.getSize() - 2, itemStack); inventory.setItem(inventory.getSize() - 2, itemStack);
} }
{ String name = String.format(
String name = String.format( Locale.ROOT,
Locale.ROOT, "&3&lPage &a&l%d &7/ &c&l%d",
"&3&lPage &a&l%d &7/ &c&l%d", getCurrentPage(), getPageAmount()
getCurrentPage(), getPageAmount() );
); ItemStack itemStack = setMeta(HeadAPI.getHeadByValue("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvY2Q5MWY1MTI2NmVkZGM2MjA3ZjEyYWU4ZDdhNDljNWRiMDQxNWFkYTA0ZGFiOTJiYjc2ODZhZmRiMTdmNGQ0ZSJ9fX0=").getMenuItem(),
ItemStack itemStack = setMeta(HeadAPI.getHeadByValue("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvY2Q5MWY1MTI2NmVkZGM2MjA3ZjEyYWU4ZDdhNDljNWRiMDQxNWFkYTA0ZGFiOTJiYjc2ODZhZmRiMTdmNGQ0ZSJ9fX0=").getMenuItem(), name,
name, "&7Left-Click to go to the &cMain Menu",
"&7Left-Click to go to the &cMain Menu", "&7Right-Click to go to a &6Specific Page");
"&7Right-Click to go to a &6Specific Page"); controlMain = new Button(itemStack, event -> {
controlMain = new Button(itemStack, event -> { if (event.getClick() == ClickType.RIGHT) {
if (event.getClick() == ClickType.RIGHT) { new AnvilGUI.Builder()
new AnvilGUI.Builder() .onComplete((player, text) -> {
.onComplete((player, text) -> { try {
try { int i = Integer.parseInt(text);
int i = Integer.parseInt(text); if (i > getPageAmount()) {
if (i > getPageAmount()) { Utils.sendMessage(player, "&cPage number is out of bounds! Max: &e" + getPageAmount());
Utils.sendMessage(player, "&cPage number is out of bounds! Max: &e" + getPageAmount()); return AnvilGUI.Response.text("&cOut of bounds!");
return AnvilGUI.Response.text("&cOut of bounds!");
}
selectPage(i - 1);
return AnvilGUI.Response.openInventory(this.getInventory());
} catch (NumberFormatException nfe) {
Utils.sendMessage(player, "&cValue must be a number!");
return AnvilGUI.Response.text(Utils.colorize("&cValue must be a number!"));
} }
}) selectPage(i - 1);
.title("Select Page") return AnvilGUI.Response.openInventory(this.getInventory());
.text("Page number...") } catch (NumberFormatException nfe) {
.plugin(HeadDB.getInstance()) Utils.sendMessage(player, "&cValue must be a number!");
.open((Player) event.getWhoClicked()); return AnvilGUI.Response.text(Utils.colorize("&cValue must be a number!"));
} else { }
InventoryUtils.openDatabase((Player) event.getWhoClicked()); })
} .title("Select Page")
}); .text("Page number...")
inventory.setItem(inventory.getSize() - 5, itemStack); .plugin(HeadDB.getInstance())
} .open((Player) event.getWhoClicked());
} else {
InventoryUtils.openDatabase((Player) event.getWhoClicked());
}
});
inventory.setItem(inventory.getSize() - 5, itemStack);
} }
private void fillRow(int rowIndex, ItemStack itemStack, Inventory inventory) { private void fillRow(int rowIndex, ItemStack itemStack, Inventory inventory) {
@ -291,29 +289,11 @@ public class PagedPane implements InventoryHolder {
protected ItemStack setMeta(ItemStack itemStack, String name, String... lore) { protected ItemStack setMeta(ItemStack itemStack, String name, String... lore) {
ItemMeta meta = itemStack.getItemMeta(); ItemMeta meta = itemStack.getItemMeta();
meta.setDisplayName(Utils.colorize(name)); meta.setDisplayName(Utils.colorize(name));
meta.setLore(Arrays.stream(lore).map(this::color).collect(Collectors.toList())); meta.setLore(Arrays.stream(lore).map(this::color).toList());
itemStack.setItemMeta(meta); itemStack.setItemMeta(meta);
return itemStack; return itemStack;
} }
@SuppressWarnings("WeakerAccess")
@Deprecated
protected ItemStack getItemStack(Material type, int durability, String name, String... lore) {
ItemStack itemStack = new ItemStack(type, 1, (short) durability);
ItemMeta itemMeta = itemStack.getItemMeta();
if (name != null) {
itemMeta.setDisplayName(color(name));
}
if (lore != null && lore.length != 0) {
itemMeta.setLore(Arrays.stream(lore).map(this::color).collect(Collectors.toList()));
}
itemStack.setItemMeta(itemMeta);
return itemStack;
}
@SuppressWarnings("WeakerAccess") @SuppressWarnings("WeakerAccess")
protected String color(String input) { protected String color(String input) {
return ChatColor.translateAlternateColorCodes('&', input); return ChatColor.translateAlternateColorCodes('&', input);

Datei anzeigen

@ -20,8 +20,8 @@ public class PagedPaneListener implements Listener {
public void onClick(InventoryClickEvent event) { public void onClick(InventoryClickEvent event) {
InventoryHolder holder = event.getInventory().getHolder(); InventoryHolder holder = event.getInventory().getHolder();
if (holder instanceof PagedPane) { if (holder instanceof PagedPane pane) {
((PagedPane) holder).onClick(event); pane.onClick(event);
} }
} }
} }

Datei anzeigen

@ -30,11 +30,11 @@ public class PlayerDataFile {
public PlayerDataFile(String name) { public PlayerDataFile(String name) {
HeadDB plugin = HeadDB.getInstance(); HeadDB plugin = HeadDB.getInstance();
// This check avoids warning in console // This check avoids warning in console
if (plugin.getResource(name) != null && !new File(plugin.getDataFolder() + "/" + name).exists()) { if (plugin.getResource(name) != null && !new File(plugin.getDataFolder(), name).exists()) {
plugin.saveResource(name, false); plugin.saveResource(name, false);
} }
this.file = new File(plugin.getDataFolder() + "/" + name); this.file = new File(plugin.getDataFolder(), name);
} }
@Nonnull @Nonnull
@ -127,15 +127,12 @@ public class PlayerDataFile {
return; return;
} }
FileWriter writer; try (FileWriter writer = new FileWriter(file)) {
try {
writer = new FileWriter(file);
writer.write(main.toString()); writer.write(main.toString());
writer.close();
Log.debug("Saved data to " + file.getName()); Log.debug("Saved data to " + file.getName());
} catch (IOException e) { } catch (IOException ex) {
Log.error("Failed to save player_data.json contents!"); Log.error("Failed to save player_data.json contents!");
Log.error(e); Log.error(ex);
} }
} }

Datei anzeigen

@ -21,7 +21,9 @@ import java.util.regex.Pattern;
/** /**
* Several utilities used by the plugin * Several utilities used by the plugin
*/ */
public class Utils { public final class Utils {
private Utils() {}
private static final FileConfiguration config = HeadDB.getInstance().getConfig(); private static final FileConfiguration config = HeadDB.getInstance().getConfig();
public static final Pattern UUID_PATTERN = Pattern.compile("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"); public static final Pattern UUID_PATTERN = Pattern.compile("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}");
@ -45,9 +47,9 @@ public class Utils {
connection.setRequestProperty("User-Agent", plugin.getName() + "-VersionChecker"); connection.setRequestProperty("User-Agent", plugin.getName() + "-VersionChecker");
latest.accept(new BufferedReader(new InputStreamReader(connection.getInputStream())).readLine().equals(plugin.getDescription().getVersion())); latest.accept(new BufferedReader(new InputStreamReader(connection.getInputStream())).readLine().equals(plugin.getDescription().getVersion()));
} catch (IOException e) { } catch (IOException ex) {
latest.accept(true); // Assume the version is latest if checking fails latest.accept(true); // Assume the version is latest if checking fails
e.printStackTrace(); Log.error(ex);
} }
}); });
} }