fix page navigation, code cleanup

This commit is contained in:
jascotty2 2019-09-08 08:35:39 -05:00
parent f297037e82
commit 27db525a12
15 changed files with 184 additions and 967 deletions

View File

@ -19,7 +19,6 @@ import com.songoda.epicheads.listeners.LoginListeners;
import com.songoda.epicheads.players.EPlayer;
import com.songoda.epicheads.players.PlayerManager;
import com.songoda.epicheads.settings.Settings;
import com.songoda.epicheads.utils.Metrics;
import com.songoda.epicheads.utils.storage.Storage;
import com.songoda.epicheads.utils.storage.StorageRow;
import com.songoda.epicheads.utils.storage.types.StorageYaml;
@ -41,10 +40,11 @@ public class EpicHeads extends SongodaPlugin {
private static EpicHeads INSTANCE;
private GuiManager guiManager = new GuiManager(this);
private final GuiManager guiManager = new GuiManager(this);
private HeadManager headManager;
private PlayerManager playerManager;
private CommandManager commandManager;
PluginHook itemEconomyHook = PluginHook.addHook(Economy.class, "EpicHeads", com.songoda.epicheads.economy.ItemEconomy.class);
private Storage storage;
@ -55,7 +55,6 @@ public class EpicHeads extends SongodaPlugin {
@Override
public void onPluginLoad() {
INSTANCE = this;
PluginHook.addHook(Economy.class, "EpicHeads", com.songoda.epicheads.economy.ItemEconomy.class);
}
@Override
@ -77,11 +76,16 @@ public class EpicHeads extends SongodaPlugin {
this.setLocale(Settings.LANGUGE_MODE.getString(), false);
// Set economy preference
EconomyManager.getManager().setPreferredHook(Settings.ECONOMY_PLUGIN.getString());
String ecoPreference = Settings.ECONOMY_PLUGIN.getString();
if(ecoPreference.equalsIgnoreCase("item")) {
EconomyManager.getManager().setPreferredHook(itemEconomyHook);
} else {
EconomyManager.getManager().setPreferredHook(ecoPreference);
}
// Register commands
this.commandManager = new CommandManager(this);
this.commandManager.addCommand(new CommandEpicHeads(this))
this.commandManager.addCommand(new CommandEpicHeads(guiManager))
.addSubCommands(
new CommandAdd(this),
new CommandBase64(this),
@ -89,8 +93,8 @@ public class EpicHeads extends SongodaPlugin {
new CommandGiveToken(this),
new CommandHelp(this),
new CommandReload(this),
new CommandSearch(this),
new CommandSettings(this),
new CommandSearch(guiManager),
new CommandSettings(guiManager),
new CommandUrl(this)
);
@ -118,9 +122,6 @@ public class EpicHeads extends SongodaPlugin {
int timeout = Settings.AUTOSAVE.getInt() * 60 * 20;
Bukkit.getScheduler().runTaskTimerAsynchronously(this, this::saveToFile, timeout, timeout);
// Start Metrics
new Metrics(this);
}
private void saveToFile() {
@ -262,10 +263,6 @@ public class EpicHeads extends SongodaPlugin {
return commandManager;
}
public GuiManager getGuiManager() {
return guiManager;
}
public HeadManager getHeadManager() {
return headManager;
}

View File

@ -1,6 +1,7 @@
package com.songoda.epicheads.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.core.gui.GuiManager;
import com.songoda.epicheads.EpicHeads;
import com.songoda.epicheads.gui.GUIOverview;
import org.bukkit.command.CommandSender;
@ -10,16 +11,16 @@ import java.util.List;
public class CommandEpicHeads extends AbstractCommand {
final EpicHeads instance;
final GuiManager guiManager;
public CommandEpicHeads(EpicHeads instance) {
public CommandEpicHeads(GuiManager guiManager) {
super(false, "EpicHeads");
this.instance = instance;
this.guiManager = guiManager;
}
@Override
protected ReturnType runCommand(CommandSender sender, String... args) {
instance.getGuiManager().showGUI((Player) sender, new GUIOverview(instance, (Player) sender));
guiManager.showGUI((Player) sender, new GUIOverview((Player) sender));
return ReturnType.SUCCESS;
}

View File

@ -1,6 +1,7 @@
package com.songoda.epicheads.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.core.gui.GuiManager;
import com.songoda.epicheads.EpicHeads;
import com.songoda.epicheads.gui.GUIHeads;
import org.bukkit.command.CommandSender;
@ -10,16 +11,16 @@ import java.util.List;
public class CommandSearch extends AbstractCommand {
final EpicHeads instance;
final GuiManager guiManager;
public CommandSearch(EpicHeads instance) {
public CommandSearch(GuiManager guiManager) {
super(true, "search");
this.instance = instance;
this.guiManager = guiManager;
}
@Override
protected AbstractCommand.ReturnType runCommand(CommandSender sender, String... args) {
GUIHeads.doSearch(instance, (Player) sender);
GUIHeads.doSearch(EpicHeads.getInstance(), null, guiManager, (Player) sender);
return ReturnType.SUCCESS;
}

View File

@ -2,6 +2,7 @@ package com.songoda.epicheads.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.core.configuration.editor.PluginConfigGui;
import com.songoda.core.gui.GuiManager;
import com.songoda.epicheads.EpicHeads;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@ -10,16 +11,16 @@ import java.util.List;
public class CommandSettings extends AbstractCommand {
final EpicHeads instance;
final GuiManager guiManager;
public CommandSettings(EpicHeads instance) {
public CommandSettings(GuiManager guiManager) {
super(true, "settings");
this.instance = instance;
this.guiManager = guiManager;
}
@Override
protected ReturnType runCommand(CommandSender sender, String... args) {
instance.getGuiManager().showGUI((Player) sender, new PluginConfigGui(instance));
guiManager.showGUI((Player) sender, new PluginConfigGui(EpicHeads.getInstance()));
return ReturnType.SUCCESS;
}

View File

@ -2,6 +2,7 @@ package com.songoda.epicheads.gui;
import com.songoda.core.compatibility.LegacyMaterials;
import com.songoda.core.gui.Gui;
import com.songoda.core.gui.GuiManager;
import com.songoda.core.gui.GuiUtils;
import com.songoda.core.hooks.EconomyManager;
import com.songoda.core.input.ChatPrompt;
@ -29,9 +30,6 @@ public class GUIHeads extends Gui {
private final Player player;
private List<Head> heads;
private int page = 0;
private int maxPage;
private String query;
private final QueryTypes type;
@ -47,7 +45,10 @@ public class GUIHeads extends Gui {
.sorted(Comparator.comparingInt(head -> (favorites.contains(head.getURL()) ? 0 : 1)))
.collect(Collectors.toList());
updateTitle();
this.setDefaultItem(null);
this.setRows(6);
this.setOnPage((event) -> showPage());
showPage();
}
private void updateTitle() {
@ -75,67 +76,56 @@ public class GUIHeads extends Gui {
break;
}
this.maxPage = (int) Math.floor(numHeads / 45.0);
pages = (int) Math.floor(numHeads / 45.0);
this.setDefaultItem(null);
this.setRows(6);
this.setTitle(name + " (" + numHeads + ") " + plugin.getLocale().getMessage("general.word.page") + " " + (page + 1) + "/" + (maxPage + 1));
showPage();
this.setTitle(name + " (" + numHeads + ") " + plugin.getLocale().getMessage("general.word.page") + " " + (page) + "/" + (pages));
}
void showPage() {
List<Head> heads = this.heads.stream().skip(page * 45).limit(45)
updateTitle();
List<Head> pageHeads = this.heads.stream().skip((page - 1) * (rows - 1) * 9).limit((rows - 1) * 9)
.collect(Collectors.toList());
if (page - 2 > 0) {
ItemStack arrow = GuiUtils.createButtonItem(LegacyMaterials.ARROW,
ChatColor.RED.toString() + plugin.getLocale().getMessage("general.word.page") + " " + (page - 2));
arrow.setAmount(page - 2);
setButton(0, arrow,
(event) -> {
page -= 3;
updateTitle();
});
if (page - 3 >= 1) {
setButton(0, GuiUtils.createButtonItem(LegacyMaterials.ARROW, page - 3,
ChatColor.RED.toString() + plugin.getLocale().getMessage("general.word.page") + " " + (page - 3)),
(event) -> changePage(-3));
} else {
clearActions(0);
setItem(0, null);
}
if (page - 1 > 0) {
ItemStack arrow = GuiUtils.createButtonItem(LegacyMaterials.ARROW,
ChatColor.RED.toString() + plugin.getLocale().getMessage("general.word.page") + " " + (page - 1));
arrow.setAmount(page - 1);
setButton(1, arrow,
(event) -> {
page -= 2;
updateTitle();
});
if (page - 2 >= 1) {
setButton(1, GuiUtils.createButtonItem(LegacyMaterials.ARROW, page - 2,
ChatColor.RED.toString() + plugin.getLocale().getMessage("general.word.page") + " " + (page - 2)),
(event) -> changePage(-2));
} else {
clearActions(1);
setItem(1, null);
}
if (page != 0) {
ItemStack arrow = GuiUtils.createButtonItem(LegacyMaterials.ARROW,
ChatColor.RED.toString() + plugin.getLocale().getMessage("general.word.page") + " " + page);
arrow.setAmount(page);
setButton(2, arrow,
(event) -> {
page--;
updateTitle();
});
if (page > 1) {
setButton(2, GuiUtils.createButtonItem(LegacyMaterials.ARROW, page - 1,
ChatColor.RED.toString() + plugin.getLocale().getMessage("general.word.page") + " " + (page - 1)),
(event) -> changePage(-1));
} else {
clearActions(2);
setItem(2, null);
}
setButton(3, GuiUtils.createButtonItem(LegacyMaterials.COMPASS,
plugin.getLocale().getMessage("gui.heads.search").getMessage()),
(event) -> doSearch(plugin, event.player));
(event) -> doSearch(plugin, this, guiManager, event.player));
ItemStack map = GuiUtils.createButtonItem(LegacyMaterials.MAP,
plugin.getLocale().getMessage("gui.heads.categories").getMessage());
map.setAmount(page + 1);
setButton(4, map, (event) -> plugin.getGuiManager().showGUI(player, new GUIOverview(plugin, event.player)));
setButton(4, GuiUtils.createButtonItem(LegacyMaterials.MAP, page,
plugin.getLocale().getMessage("gui.heads.categories").getMessage()), (event) -> guiManager.showGUI(player, new GUIOverview(event.player)));
if (heads.size() > 1)
if (pageHeads.size() > 1)
setButton(5, GuiUtils.createButtonItem(LegacyMaterials.COMPASS,
plugin.getLocale().getMessage("gui.heads.refine").getMessage()),
(event) -> {
plugin.getLocale().getMessage("general.search.refine").sendPrefixedMessage(event.player);
ChatPrompt chatPrompt = ChatPrompt.showPrompt(plugin, event.player, promptEvent -> {
exit();
ChatPrompt.showPrompt(plugin, event.player, plugin.getLocale().getMessage("general.search.refine").getPrefixedMessage(), promptEvent -> {
this.page = 0;
this.heads = this.heads.stream().filter(head -> head.getName().toLowerCase()
.contains(promptEvent.getMessage().toLowerCase())).collect(Collectors.toList());
@ -143,73 +133,64 @@ public class GUIHeads extends Gui {
this.query = promptEvent.getMessage();
else
this.query += ", " + promptEvent.getMessage();
}).setOnClose(() -> {
showPage();
guiManager.showGUI(event.player, this);
}).setOnCancel(() -> {
event.player.sendMessage(plugin.getLocale().getMessage("general.search.canceled").getPrefixedMessage());
});
chatPrompt.setOnClose(this::updateTitle);
});
if (page != maxPage) {
ItemStack arrow = GuiUtils.createButtonItem(LegacyMaterials.ARROW,
ChatColor.RED.toString() + plugin.getLocale().getMessage("general.word.page") + " " + (page + 2));
arrow.setAmount(page + 2);
setButton(6, arrow,
(event) -> {
page++;
updateTitle();
});
if (page != pages) {
setButton(6, GuiUtils.createButtonItem(LegacyMaterials.ARROW, page + 1,
ChatColor.RED.toString() + plugin.getLocale().getMessage("general.word.page") + " " + (page + 1)),
(event) -> changePage(+1));
} else {
clearActions(6);
setItem(6, null);
}
if (page + 1 < maxPage) {
ItemStack arrow = GuiUtils.createButtonItem(LegacyMaterials.ARROW,
ChatColor.RED.toString() + plugin.getLocale().getMessage("general.word.page") + " " + (page + 3));
arrow.setAmount(page + 3);
setButton(7, arrow,
(event) -> {
page += 2;
updateTitle();
});
if (page + 2 <= pages) {
setButton(7, GuiUtils.createButtonItem(LegacyMaterials.ARROW, page + 2,
ChatColor.RED.toString() + plugin.getLocale().getMessage("general.word.page") + " " + (page + 2)),
(event) -> changePage(+2));
} else {
clearActions(7);
setItem(7, null);
}
if (page + 2 < maxPage) {
ItemStack arrow = GuiUtils.createButtonItem(LegacyMaterials.ARROW,
ChatColor.RED.toString() + plugin.getLocale().getMessage("general.word.page") + " " + (page + 4));
arrow.setAmount(page + 4);
setButton(8, arrow,
(event) -> {
page += 3;
updateTitle();
});
if (page + 3 <= pages) {
setButton(8, GuiUtils.createButtonItem(LegacyMaterials.ARROW, page + 3,
ChatColor.RED.toString() + plugin.getLocale().getMessage("general.word.page") + " " + (page + 3)),
(event) -> changePage(+3));
} else {
clearActions(8);
setItem(8, null);
}
List<String> favorites = plugin.getPlayerManager().getPlayer(player).getFavorites();
for (int i = 0; i < heads.size(); i++) {
Head head = heads.get(i);
double cost = Settings.HEAD_COST.getDouble();
boolean free = player.hasPermission("epicheads.bypasscost")
|| (Settings.FREE_IN_CREATIVE.getBoolean() && player.getGameMode() == GameMode.CREATIVE);
for (int i = 0; i < pageHeads.size(); i++) {
Head head = pageHeads.get(i);
if (head.getName() == null) continue;
boolean free = player.hasPermission("epicheads.bypasscost")
|| (Settings.FREE_IN_CREATIVE.getBoolean() && player.getGameMode() == GameMode.CREATIVE);
ItemStack item = head.asItemStack(favorites.contains(head.getURL()), free);
double cost = Settings.HEAD_COST.getDouble();
setButton(i + 9, item, (event) -> {
if (event.clickType == ClickType.SHIFT_LEFT || event.clickType == ClickType.SHIFT_RIGHT) {
EPlayer ePlayer = plugin.getPlayerManager().getPlayer(player);
if (!ePlayer.getFavorites().contains(head.getURL()))
ePlayer.addFavorite(head.getURL());
else
boolean isFav = ePlayer.getFavorites().contains(head.getURL());
if (isFav)
ePlayer.removeFavorite(head.getURL());
updateTitle();
else
ePlayer.addFavorite(head.getURL());
updateItem(event.slot, head.getHeadItemName(!isFav), head.getHeadItemLore(free));
return;
}
ItemMeta meta = item.getItemMeta();
meta.setLore(new ArrayList<>());
item.setItemMeta(meta);
if (!free) {
if (EconomyManager.isEnabled()) {
if (EconomyManager.hasBalance(player, cost)) {
@ -223,23 +204,32 @@ public class GUIHeads extends Gui {
return;
}
}
player.getInventory().addItem(item);
ItemStack headItem = item.clone();
ItemMeta meta = headItem.getItemMeta();
meta.setLore(new ArrayList<>());
headItem.setItemMeta(meta);
player.getInventory().addItem(headItem);
});
}
}
public static void doSearch(EpicHeads plugin, Player player) {
plugin.getLocale().getMessage("general.search.global").sendPrefixedMessage(player);
ChatPrompt.showPrompt(plugin, player, event -> {
List<Head> heads = plugin.getHeadManager().getHeads().stream()
.filter(head -> head.getName().toLowerCase().contains(event.getMessage().toLowerCase()))
public static void doSearch(EpicHeads plugin, Gui activeGui, GuiManager guiManager, Player player) {
if (activeGui != null)
activeGui.exit();
ChatPrompt.showPrompt(plugin, player, plugin.getLocale().getMessage("general.search.global").getPrefixedMessage(), response -> {
List<Head> searchHeads = plugin.getHeadManager().getHeads().stream()
.filter(head -> head.getName().toLowerCase().contains(response.getMessage().toLowerCase()))
.collect(Collectors.toList());
Bukkit.getScheduler().scheduleSyncDelayedTask(EpicHeads.getInstance(), () ->
plugin.getGuiManager().showGUI(player, new GUIHeads(plugin, player, event.getMessage(), QueryTypes.SEARCH, heads)), 0L);
Bukkit.getScheduler().scheduleSyncDelayedTask(EpicHeads.getInstance(), ()
-> guiManager.showGUI(player, new GUIHeads(plugin, player, response.getMessage(), QueryTypes.SEARCH, searchHeads)), 0L);
}).setOnCancel(() -> {
player.sendMessage(plugin.getLocale().getMessage("general.search.canceled").getPrefixedMessage());
});
}
public enum QueryTypes {
public static enum QueryTypes {
SEARCH, CATEGORY, FAVORITES, PACK
}
}

View File

@ -11,7 +11,6 @@ import com.songoda.epicheads.utils.Methods;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
@ -20,10 +19,9 @@ public class GUIOverview extends Gui {
private final EpicHeads plugin;
private final Player player;
private int page = 0;
public GUIOverview(EpicHeads plugin, Player player) {
this.plugin = plugin;
public GUIOverview(Player player) {
this.plugin = EpicHeads.getInstance();
this.player = player;
this.setDefaultItem(null);
@ -31,21 +29,21 @@ public class GUIOverview extends Gui {
this.setTitle(plugin.getLocale().getMessage("gui.overview.title")
.processPlaceholder("count", plugin.getHeadManager().getHeads().size())
.getMessage());
this.setPrevPage(rows - 1, 1, GuiUtils.createButtonItem(LegacyMaterials.ARROW,
plugin.getLocale().getMessage("gui.general.previous").getMessage()));
this.setNextPage(rows - 1, 7, GuiUtils.createButtonItem(LegacyMaterials.ARROW,
plugin.getLocale().getMessage("gui.general.next").getMessage()));
this.setOnPage((event) -> showPage());
showPage();
}
void showPage() {
ArrayList<String> lore = new ArrayList<>();
String[] parts = plugin.getLocale().getMessage("gui.overview.favoriteslore").getMessage().split("\\|");
for (String line : parts)
lore.add(Methods.formatText(line));
setButton(4, GuiUtils.createButtonItem(LegacyMaterials.GOLDEN_APPLE,
plugin.getLocale().getMessage("gui.overview.viewfavorites").getMessage(), lore),
(event) -> plugin.getGuiManager().showGUI(player, new GUIHeads(plugin, player, null, GUIHeads.QueryTypes.FAVORITES,
plugin.getLocale().getMessage("gui.overview.viewfavorites").getMessage(),
plugin.getLocale().getMessage("gui.overview.favoriteslore").getMessage().split("\\|")),
(event) -> guiManager.showGUI(player, new GUIHeads(plugin, player, null, GUIHeads.QueryTypes.FAVORITES,
plugin.getPlayerManager().getPlayer(player).getFavoritesAsHeads())));
ItemStack glass2 = GuiUtils.getBorderItem(Settings.GLASS_TYPE_2.getMaterial());
ItemStack glass3 = GuiUtils.getBorderItem(Settings.GLASS_TYPE_3.getMaterial());
@ -55,32 +53,16 @@ public class GUIOverview extends Gui {
GuiUtils.mirrorFill(this, 0, 2, true, true, glass3);
int numTemplates = plugin.getHeadManager().getCategories().size();
int maxPage = (int) Math.floor(numTemplates / 21.0);
pages = (int) Math.floor(numTemplates / 21.0);
List<Category> categories = plugin.getHeadManager().getCategories().stream().skip(page * 21).limit(21)
List<Category> categories = plugin.getHeadManager().getCategories().stream().skip((page - 1) * (rows - 1) * 9).limit((rows - 1) * 9)
.collect(Collectors.toList());
if (page != 0)
setButton(37, GuiUtils.createButtonItem(LegacyMaterials.ARROW,
plugin.getLocale().getMessage("gui.general.previous").getMessage()),
(event) -> {
page--;
showPage();
});
if (page != maxPage)
setButton(43, GuiUtils.createButtonItem(LegacyMaterials.ARROW,
plugin.getLocale().getMessage("gui.general.next").getMessage()),
(event) -> {
page++;
showPage();
});
int add = 0;
for (int i = 0; i < categories.size(); i++) {
if (i + add == 7 || i + add == 16) add = add + 2;
Category category = plugin.getHeadManager().getCategories().get((page * 21) + i);
Category category = categories.get(i);
List<Head> heads = category.isLatestPack() ? plugin.getHeadManager().getLatestPack() : plugin.getHeadManager().getHeadsByCategory(category);
@ -88,7 +70,7 @@ public class GUIOverview extends Gui {
if (!player.hasPermission("epicheads.category." + category.getName().replace(" ", "_"))) continue;
setButton(i + 10 + add, GuiUtils.createButtonItem(Methods.addTexture(new ItemStack(LegacyMaterials.PLAYER_HEAD.getMaterial(), 1, (byte) 3), firstHead.getURL()),
setButton(i + 10 + add, GuiUtils.createButtonItem(Methods.addTexture(LegacyMaterials.PLAYER_HEAD.getItem(), firstHead.getURL()),
plugin.getLocale().getMessage("gui.overview.headname")
.processPlaceholder("name", Color.getRandomColor() + category.getName())
.getMessage(),
@ -98,29 +80,22 @@ public class GUIOverview extends Gui {
.processPlaceholder("count", String.format("%,d", category.getCount()))
.getMessage()),
(event) ->
plugin.getGuiManager().showGUI(player, new GUIHeads(plugin, player, category.isLatestPack() ? category.getName() : null,
guiManager.showGUI(player, new GUIHeads(plugin, player, category.isLatestPack() ? category.getName() : null,
category.isLatestPack() ? GUIHeads.QueryTypes.PACK : GUIHeads.QueryTypes.CATEGORY, heads)));
}
setButton(Settings.DISCORD.getBoolean() ? 39 : 40, GuiUtils.createButtonItem(LegacyMaterials.COMPASS,
plugin.getLocale().getMessage("gui.overview.search").getMessage()),
(event) -> GUIHeads.doSearch(plugin, event.player));
(event) -> GUIHeads.doSearch(plugin, this, guiManager, event.player));
if (Settings.DISCORD.getBoolean()) {
ArrayList<String> lore2 = new ArrayList<>();
String[] parts2 = plugin.getLocale().getMessage("gui.overview.discordlore")
.getMessage().split("\\|");
for (String line : parts2)
lore2.add(Methods.formatText(line));
setButton(41, GuiUtils.createButtonItem(Methods.addTexture(new ItemStack(LegacyMaterials.PLAYER_HEAD.getMaterial(), 1, (byte) 3),
setButton(41, GuiUtils.createButtonItem(Methods.addTexture(LegacyMaterials.PLAYER_HEAD.getItem(),
"a3b183b148b9b4e2b158334aff3b5bb6c2c2dbbc4d67f76a7be856687a2b623"),
plugin.getLocale().getMessage("gui.overview.discord").getMessage(),
lore2),
plugin.getLocale().getMessage("gui.overview.discordlore").getMessage().split("\\|")),
(event) -> {
plugin.getLocale().newMessage("&9https://discord.gg/A9TRJQb").sendPrefixedMessage(player);
player.closeInventory();
exit();
});
}
}

View File

@ -1,6 +1,5 @@
package com.songoda.epicheads.head;
import com.songoda.core.compatibility.LegacyMaterials;
import com.songoda.epicheads.EpicHeads;
import com.songoda.epicheads.settings.Settings;
@ -63,12 +62,24 @@ public class Head {
}
public ItemStack asItemStack(boolean favorite, boolean free) {
EpicHeads plugin = EpicHeads.getInstance();
ItemStack item = Methods.addTexture(new ItemStack(LegacyMaterials.PLAYER_HEAD.getMaterial(), 1, (byte) 3), this.URL);
ItemStack item = Methods.addTexture(LegacyMaterials.PLAYER_HEAD.getItem(), this.URL);
double cost = Settings.HEAD_COST.getDouble();
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(Methods.formatText((favorite ? "&6⭐ " : "") + "&9" + name));
if(meta != null) {
meta.setDisplayName(getHeadItemName(favorite));
meta.setLore(getHeadItemLore(free));
item.setItemMeta(meta);
}
return item;
}
public String getHeadItemName(boolean favorite) {
return Methods.formatText((favorite ? "&6⭐ " : "") + "&9" + name);
}
public List<String> getHeadItemLore(boolean free) {
EpicHeads plugin = EpicHeads.getInstance();
double cost = Settings.HEAD_COST.getDouble();
List<String> lore = new ArrayList<>();
if (this.staffPicked == 1)
lore.add(plugin.getLocale().getMessage("general.head.staffpicked").getMessage());
@ -77,10 +88,7 @@ public class Head {
if (!free)
lore.add(plugin.getLocale().getMessage("general.head.cost")
.processPlaceholder("cost", cost).getMessage());
meta.setLore(lore);
item.setItemMeta(meta);
return item;
return lore;
}
@Override

View File

@ -39,7 +39,7 @@ public class DeathListeners implements Listener {
String encodededStr = Methods.getEncodedTexture((Player) event.getEntity());
if (encodededStr == null) {
itemNew = new ItemStack(LegacyMaterials.PLAYER_HEAD.getMaterial(), 1, (byte) 3);
itemNew = LegacyMaterials.PLAYER_HEAD.getItem();
ItemMeta meta = itemNew.getItemMeta();
meta.setDisplayName(Methods.formatText("&9" + ((Player) event.getEntity()).getDisplayName()));

View File

@ -26,7 +26,7 @@ public class ItemListeners implements Listener {
public void itemSpawnEvent(ItemSpawnEvent event) {
ItemStack item = event.getEntity().getItemStack();
if (item.getType() != LegacyMaterials.PLAYER_HEAD.getMaterial()) return;
if (!LegacyMaterials.PLAYER_HEAD.matches(item)) return;
String encodededStr = Methods.getEncodedTexture(item);

View File

@ -1,67 +0,0 @@
package com.songoda.epicheads.utils;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
/**
* ConfigWrapper made by @clip
*/
public class ConfigWrapper {
private final JavaPlugin plugin;
private final String folderName, fileName;
private FileConfiguration config;
private File configFile;
public ConfigWrapper(final JavaPlugin instance, final String folderName, final String fileName) {
this.plugin = instance;
this.folderName = folderName;
this.fileName = fileName;
}
public void createNewFile(final String message, final String header) {
reloadConfig();
saveConfig();
loadConfig(header);
if (message != null) {
plugin.getLogger().info(message);
}
}
public FileConfiguration getConfig() {
if (config == null) {
reloadConfig();
}
return config;
}
public void loadConfig(final String header) {
config.options().header(header);
config.options().copyDefaults(true);
saveConfig();
}
public void reloadConfig() {
if (configFile == null) {
configFile = new File(plugin.getDataFolder() + folderName, fileName);
}
config = YamlConfiguration.loadConfiguration(configFile);
}
public void saveConfig() {
if (config == null || configFile == null) {
return;
}
try {
getConfig().save(configFile);
} catch (final IOException ex) {
plugin.getLogger().log(Level.SEVERE, "Could not save config to " + configFile, ex);
}
}
}

View File

@ -7,14 +7,12 @@ import org.bukkit.inventory.ItemStack;
public class ItemEconomy extends Economy {
public boolean isItem(ItemStack itemStack) {
if (itemStack == null)
return false;
return itemStack.isSimilar(Methods.createToken(1));
}
private int convertAmount(double amount) {
return (int) Math.ceil(amount);
}
@ -32,7 +30,6 @@ public class ItemEconomy extends Economy {
return false;
}
@Override
public boolean withdrawBalance(OfflinePlayer player, double cost) {
int amount = convertAmount(cost);

View File

@ -1,695 +0,0 @@
package com.songoda.epicheads.utils;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
/**
* bStats collects some data for plugin authors.
* <p>
* Check out https://bStats.org/ to learn more about bStats!
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class Metrics {
static {
// You can use the property to disable the check in your test environment
if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) {
// Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D
final String defaultPackage = new String(
new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'});
final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
// We want to make sure nobody just copy & pastes the example and use the wrong package names
if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) {
throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
}
}
}
// The version of this bStats class
public static final int B_STATS_VERSION = 1;
// The url to which the data is sent
private static final String URL = "https://bStats.org/submitData/bukkit";
// Is bStats enabled on this server?
private boolean enabled;
// Should failed requests be logged?
private static boolean logFailedRequests;
// Should the sent data be logged?
private static boolean logSentData;
// Should the response text be logged?
private static boolean logResponseStatusText;
// The uuid of the server
private static String serverUUID;
// The plugin
private final Plugin plugin;
// A list with all custom charts
private final List<CustomChart> charts = new ArrayList<>();
/**
* Class constructor.
*
* @param plugin The plugin which stats should be submitted.
*/
public Metrics(Plugin plugin) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null!");
}
this.plugin = plugin;
// Get the config file
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
File configFile = new File(bStatsFolder, "config.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
// Check if the config file exists
if (!config.isSet("serverUuid")) {
// Add default values
config.addDefault("enabled", true);
// Every server gets it's unique random id.
config.addDefault("serverUuid", UUID.randomUUID().toString());
// Should failed request be logged?
config.addDefault("logFailedRequests", false);
// Should the sent data be logged?
config.addDefault("logSentData", false);
// Should the response text be logged?
config.addDefault("logResponseStatusText", false);
// Inform the server owners about bStats
config.options().header(
"bStats collects some data for plugin authors like how many servers are using their plugins.\n" +
"To honor their work, you should not disable it.\n" +
"This has nearly no effect on the server performance!\n" +
"Check out https://bStats.org/ to learn more :)"
).copyDefaults(true);
try {
config.save(configFile);
} catch (IOException ignored) { }
}
// Load the data
enabled = config.getBoolean("enabled", true);
serverUUID = config.getString("serverUuid");
logFailedRequests = config.getBoolean("logFailedRequests", false);
logSentData = config.getBoolean("logSentData", false);
logResponseStatusText = config.getBoolean("logResponseStatusText", false);
if (enabled) {
boolean found = false;
// Search for all other bStats Metrics classes to see if we are the first one
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
found = true; // We aren't the first
break;
} catch (NoSuchFieldException ignored) { }
}
// Register our service
Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal);
if (!found) {
// We are the first!
startSubmitting();
}
}
}
/**
* Checks if bStats is enabled.
*
* @return Whether bStats is enabled or not.
*/
public boolean isEnabled() {
return enabled;
}
/**
* Adds a custom chart.
*
* @param chart The chart to add.
*/
public void addCustomChart(CustomChart chart) {
if (chart == null) {
throw new IllegalArgumentException("Chart cannot be null!");
}
charts.add(chart);
}
/**
* Starts the Scheduler which submits our data every 30 minutes.
*/
private void startSubmitting() {
final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (!plugin.isEnabled()) { // Plugin was disabled
timer.cancel();
return;
}
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
Bukkit.getScheduler().runTask(plugin, () -> submitData());
}
}, 1000 * 60 * 5, 1000 * 60 * 30);
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
// WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
// WARNING: Just don't do it!
}
/**
* Gets the plugin specific data.
* This method is called using Reflection.
*
* @return The plugin specific data.
*/
public JSONObject getPluginData() {
JSONObject data = new JSONObject();
String pluginName = plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion();
data.put("pluginName", pluginName); // Append the name of the plugin
data.put("pluginVersion", pluginVersion); // Append the version of the plugin
JSONArray customCharts = new JSONArray();
for (CustomChart customChart : charts) {
// Add the data of the custom charts
JSONObject chart = customChart.getRequestJsonObject();
if (chart == null) { // If the chart is null, we skip it
continue;
}
customCharts.add(chart);
}
data.put("customCharts", customCharts);
return data;
}
/**
* Gets the server specific data.
*
* @return The server specific data.
*/
private JSONObject getServerData() {
// Minecraft specific data
int playerAmount;
try {
// Around MC 1.8 the return type was changed to a collection from an array,
// This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
} catch (Exception e) {
playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
}
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
String bukkitVersion = Bukkit.getVersion();
// OS/Java specific data
String javaVersion = System.getProperty("java.version");
String osName = System.getProperty("os.name");
String osArch = System.getProperty("os.arch");
String osVersion = System.getProperty("os.version");
int coreCount = Runtime.getRuntime().availableProcessors();
JSONObject data = new JSONObject();
data.put("serverUUID", serverUUID);
data.put("playerAmount", playerAmount);
data.put("onlineMode", onlineMode);
data.put("bukkitVersion", bukkitVersion);
data.put("javaVersion", javaVersion);
data.put("osName", osName);
data.put("osArch", osArch);
data.put("osVersion", osVersion);
data.put("coreCount", coreCount);
return data;
}
/**
* Collects the data and sends it afterwards.
*/
private void submitData() {
final JSONObject data = getServerData();
JSONArray pluginData = new JSONArray();
// Search for all other bStats Metrics classes to get their plugin data
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
try {
pluginData.add(provider.getService().getMethod("getPluginData").invoke(provider.getProvider()));
} catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { }
}
} catch (NoSuchFieldException ignored) { }
}
data.put("plugins", pluginData);
// Create a new thread for the connection to the bStats server
new Thread(new Runnable() {
@Override
public void run() {
try {
// Send the data
sendData(plugin, data);
} catch (Exception e) {
// Something went wrong! :(
if (logFailedRequests) {
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
}
}
}
}).start();
}
/**
* Sends the data to the bStats server.
*
* @param plugin Any plugin. It's just used to get a logger instance.
* @param data The data to send.
* @throws Exception If the request failed.
*/
private static void sendData(Plugin plugin, JSONObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException("This method must not be called from the main thread!");
}
if (logSentData) {
plugin.getLogger().info("Sending data to bStats: " + data.toString());
}
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
// Send data
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(compressedData);
outputStream.flush();
outputStream.close();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
bufferedReader.close();
if (logResponseStatusText) {
plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString());
}
}
/**
* Gzips the given String.
*
* @param str The string to gzip.
* @return The gzipped String.
* @throws IOException If the compression failed.
*/
private static byte[] compress(final String str) throws IOException {
if (str == null) {
return null;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
gzip.write(str.getBytes(StandardCharsets.UTF_8));
gzip.close();
return outputStream.toByteArray();
}
/**
* Represents a custom chart.
*/
public static abstract class CustomChart {
// The id of the chart
final String chartId;
/**
* Class constructor.
*
* @param chartId The id of the chart.
*/
CustomChart(String chartId) {
if (chartId == null || chartId.isEmpty()) {
throw new IllegalArgumentException("ChartId cannot be null or empty!");
}
this.chartId = chartId;
}
private JSONObject getRequestJsonObject() {
JSONObject chart = new JSONObject();
chart.put("chartId", chartId);
try {
JSONObject data = getChartData();
if (data == null) {
// If the data is null we don't send the chart.
return null;
}
chart.put("data", data);
} catch (Throwable t) {
if (logFailedRequests) {
Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
}
return null;
}
return chart;
}
protected abstract JSONObject getChartData() throws Exception;
}
/**
* Represents a custom simple pie.
*/
public static class SimplePie extends CustomChart {
private final Callable<String> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimplePie(String chartId, Callable<String> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
String value = callable.call();
if (value == null || value.isEmpty()) {
// Null = skip the chart
return null;
}
data.put("value", value);
return data;
}
}
/**
* Represents a custom advanced pie.
*/
public static class AdvancedPie extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.put(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom drilldown pie.
*/
public static class DrilldownPie extends CustomChart {
private final Callable<Map<String, Map<String, Integer>>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) {
super(chartId);
this.callable = callable;
}
@Override
public JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Map<String, Integer>> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean reallyAllSkipped = true;
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
JSONObject value = new JSONObject();
boolean allSkipped = true;
for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
value.put(valueEntry.getKey(), valueEntry.getValue());
allSkipped = false;
}
if (!allSkipped) {
reallyAllSkipped = false;
values.put(entryValues.getKey(), value);
}
}
if (reallyAllSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom single line chart.
*/
public static class SingleLineChart extends CustomChart {
private final Callable<Integer> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SingleLineChart(String chartId, Callable<Integer> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
int value = callable.call();
if (value == 0) {
// Null = skip the chart
return null;
}
data.put("value", value);
return data;
}
}
/**
* Represents a custom multi line chart.
*/
public static class MultiLineChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.put(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom simple bar chart.
*/
public static class SimpleBarChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
JSONArray categoryValues = new JSONArray();
categoryValues.add(entry.getValue());
values.put(entry.getKey(), categoryValues);
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom advanced bar chart.
*/
public static class AdvancedBarChart extends CustomChart {
private final Callable<Map<String, int[]>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, int[]> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, int[]> entry : map.entrySet()) {
if (entry.getValue().length == 0) {
continue; // Skip this invalid
}
allSkipped = false;
JSONArray categoryValues = new JSONArray();
for (int categoryValue : entry.getValue()) {
categoryValues.add(categoryValue);
}
values.put(entry.getKey(), categoryValues);
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
}

View File

@ -1,23 +1,21 @@
package com.songoda.epicheads.utils.storage;
import com.songoda.core.configuration.Config;
import com.songoda.epicheads.EpicHeads;
import com.songoda.epicheads.head.Head;
import com.songoda.epicheads.players.EPlayer;
import com.songoda.epicheads.utils.ConfigWrapper;
import java.util.List;
public abstract class Storage {
protected final EpicHeads instance;
protected final ConfigWrapper dataFile;
protected final Config dataFile;
public Storage(EpicHeads instance) {
this.instance = instance;
this.dataFile = new ConfigWrapper(instance, "", "data.yml");
this.dataFile.createNewFile(null, "EpicSpawners Data File");
this.dataFile.getConfig().options().copyDefaults(true);
this.dataFile.saveConfig();
this.dataFile = (new Config(instance, "", "data.yml"))
.setAutosave(true);
}
public abstract boolean containsGroup(String group);

View File

@ -6,9 +6,19 @@ import com.songoda.epicheads.utils.storage.StorageItem;
import com.songoda.epicheads.utils.storage.StorageRow;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.MemorySection;
import java.io.*;
import java.util.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class StorageYaml extends Storage {
@ -21,21 +31,21 @@ public class StorageYaml extends Storage {
@Override
public boolean containsGroup(String group) {
return dataFile.getConfig().contains("data." + group);
return dataFile.contains("data." + group);
}
@Override
public List<StorageRow> getRowsByGroup(String group) {
List<StorageRow> rows = new ArrayList<>();
ConfigurationSection currentSection = dataFile.getConfig().getConfigurationSection("data." + group);
ConfigurationSection currentSection = dataFile.getConfigurationSection("data." + group);
for (String key : currentSection.getKeys(false)) {
Map<String, StorageItem> items = new HashMap<>();
ConfigurationSection currentSection2 = dataFile.getConfig().getConfigurationSection("data." + group + "." + key);
ConfigurationSection currentSection2 = dataFile.getConfigurationSection("data." + group + "." + key);
for (String key2 : currentSection2.getKeys(false)) {
String path = "data." + group + "." + key + "." + key2;
items.put(key2, new StorageItem(dataFile.getConfig().get(path) instanceof MemorySection
? convertToInLineList(path) : dataFile.getConfig().get(path)));
items.put(key2, new StorageItem(dataFile.get(path) instanceof MemorySection
? convertToInLineList(path) : dataFile.get(path)));
}
if (items.isEmpty()) continue;
StorageRow row = new StorageRow(key, items);
@ -46,8 +56,8 @@ public class StorageYaml extends Storage {
private String convertToInLineList(String path) {
StringBuilder converted = new StringBuilder();
for (String key : dataFile.getConfig().getConfigurationSection(path).getKeys(false)) {
converted.append(key).append(":").append(dataFile.getConfig().getInt(path + "." + key)).append(";");
for (String key : dataFile.getConfigurationSection(path).getKeys(false)) {
converted.append(key).append(":").append(dataFile.getInt(path + "." + key)).append(";");
}
return converted.toString();
}
@ -85,19 +95,19 @@ public class StorageYaml extends Storage {
if (toSave.containsKey(entry.getKey())) {
Object newValue = toSave.get(entry.getKey());
if (!entry.getValue().equals(newValue)) {
dataFile.getConfig().set(entry.getKey(), newValue);
dataFile.set(entry.getKey(), newValue);
}
toSave.remove(entry.getKey());
} else {
dataFile.getConfig().set(entry.getKey(), null);
dataFile.set(entry.getKey(), null);
}
}
for (Map.Entry<String, Object> entry : toSave.entrySet()) {
dataFile.getConfig().set(entry.getKey(), entry.getValue());
dataFile.set(entry.getKey(), entry.getValue());
}
dataFile.saveConfig();
dataFile.save();
} catch (NullPointerException e) {
e.printStackTrace();
}
@ -125,7 +135,7 @@ public class StorageYaml extends Storage {
@Override
public void closeConnection() {
dataFile.saveConfig();
dataFile.saveChanges();
}
private static void copyFile(File source, File dest) throws IOException {

View File

@ -10,6 +10,7 @@ general.phrase.latestpack = "Latest Pack"
general.search.global = "&6Enter your search query."
general.search.refine = "&6Enter a search term to refine your search."
general.search.nonefound = "&cNo heads found.."
general.search.canceled = "&cSearch canceled."
general.head.staffpicked = "&8Staff Favorite"
general.head.id = "&8ID: &7%id%"