refactoring & optimization

This commit is contained in:
mfnalex 2021-05-30 22:27:56 +02:00
parent 1aee09b7f1
commit ef16ccc029
15 changed files with 38 additions and 92 deletions

View File

@ -68,12 +68,12 @@ import java.util.*;
public class ChestSortPlugin extends JavaPlugin {
private static double updateCheckInterval = 4 * 60 * 60; // in seconds. We check on startup and every 4 hours
private final boolean hotkeyGUI = true;
private EnderContainersHook enderContainersHook;
private GenericGUIHook genericHook;
private boolean hookCrackShot = false;
private boolean hookInventoryPages = false;
private boolean hookMinepacks = false;
boolean hotkeyGUI = true;
private PlayerVaultsHook playerVaultsHook;
private boolean debug = false;
private ArrayList<String> disabledWorlds;
@ -130,23 +130,6 @@ public class ChestSortPlugin extends JavaPlugin {
// That's no problem
setDisabledWorlds((ArrayList<String>) getConfig().getStringList(Config.DISABLED_WORLDS));
// Config version prior to 5? Then it must have been generated by ChestSort 1.x
/*if (getConfig().getInt("config-version", 0) < 5) {
renameConfigIfTooOld();
// Using old config version, but it's no problem. We just print a warning and
// use the default values later on
} else*/
//if (getConfig().getInt("config-version", 0) != getCurrentConfigVersion()) {
// showOldConfigWarning();
// ConfigUpdater configUpdater = new ConfigUpdater(this);
// configUpdater.updateConfig();
// setUsingMatchingConfig(true);
// createConfig();
//}
ConfigUpdater.updateConfig();
createDirectories();
@ -296,7 +279,9 @@ public class ChestSortPlugin extends JavaPlugin {
return hookMinepacks;
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isHotkeyGUI() {
// TODO: Remove, it's unused
return hotkeyGUI;
}
@ -362,7 +347,8 @@ public class ChestSortPlugin extends JavaPlugin {
setVerbose(getConfig().getBoolean("verbose"));
setLgr(new Logger(this, getConfig().getBoolean("log")));
setMessages(new Messages(this));
//noinspection InstantiationOfUtilityClass
new Messages();
setOrganizer(new ChestSortOrganizer(this));
setSettingsGUI(new SettingsGUI(this));
try {
@ -488,7 +474,7 @@ public class ChestSortPlugin extends JavaPlugin {
// Metrics will need json-simple with 1.14 API.
Metrics bStats = new Metrics(this, 3089);
bStats.addCustomChart(new Metrics.SimplePie("sorting_method", ()->getSortingMethod()));
bStats.addCustomChart(new Metrics.SimplePie("sorting_method", this::getSortingMethod));
bStats.addCustomChart(new Metrics.SimplePie("config_version",
()->Integer.toString(getConfig().getInt("config-version", 0))));
bStats.addCustomChart(
@ -547,7 +533,7 @@ public class ChestSortPlugin extends JavaPlugin {
// Player settings are stored in a file named after the player's UUID
File playerFile = new File(getDataFolder() + File.separator + "playerdata",
p.getUniqueId().toString() + ".yml");
p.getUniqueId() + ".yml");
YamlConfiguration playerConfig = YamlConfiguration.loadConfiguration(playerFile);
playerConfig.addDefault("sortingEnabled", getConfig().getBoolean("sorting-enabled-by-default"));
@ -841,9 +827,8 @@ public class ChestSortPlugin extends JavaPlugin {
void unregisterAllPlayers() {
if (getPerPlayerSettings() != null && getPerPlayerSettings().size() > 0) {
Iterator<String> it = getPerPlayerSettings().keySet().iterator();
while (it.hasNext()) {
Player p = getServer().getPlayer(it.next());
for (String s : getPerPlayerSettings().keySet()) {
Player p = getServer().getPlayer(s);
if (p != null) {
unregisterPlayer(p);
}
@ -878,8 +863,7 @@ public class ChestSortPlugin extends JavaPlugin {
NBTAPI.addNBT(p, "leftClickOutside", String.valueOf(setting.leftClickOutside));
} else {
File playerFile = new File(getDataFolder() + File.separator + "playerdata",
p.getUniqueId().toString() + ".yml");
File playerFile = new File(getDataFolder() + File.separator + "playerdata", p.getUniqueId() + ".yml");
YamlConfiguration playerConfig = YamlConfiguration.loadConfiguration(playerFile);
playerConfig.set("sortingEnabled", setting.sortingEnabled);
playerConfig.set("invSortingEnabled", setting.invSortingEnabled);

View File

@ -20,7 +20,7 @@ public class InvSortCommand implements CommandExecutor {
}
@Override
public boolean onCommand(@NotNull CommandSender sender, Command command, @NotNull String label, String[] args) {
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
Player p = null;
@ -48,8 +48,6 @@ public class InvSortCommand implements CommandExecutor {
args = new String[0];
}
//sender.sendMessage(Messages.MSG_PLAYERSONLY);
//return true;
}
if(p == null) p = (Player) sender;

View File

@ -9,11 +9,8 @@ public class Config {
public static final String DISABLED_WORLDS = "disabled-worlds";
public static final String DEBUG2 = "debug2";
private final ChestSortPlugin main;
public Config(ChestSortPlugin main) {
this.main=main;
main.getConfig().addDefault(HOTKEY_COOLDOWN,0.0);
main.getConfig().addDefault(DEBUG2,false);
}

View File

@ -42,6 +42,7 @@ public final class ConfigUpdater {
* For debugging the config updater only
*/
private static void debug(final Logger logger, final String message) {
//noinspection ConstantConditions
if (false) {
logger.warning(message);
}
@ -183,6 +184,7 @@ public final class ConfigUpdater {
}
} else*/
//noinspection StatementWithEmptyBody
if (defaultLine.startsWith("sorting-hotkeys:") || defaultLine.startsWith("additional-hotkeys:")) {
// dont replace hotkeys root part
} else if (defaultLine.startsWith(" middle-click:")) {

View File

@ -13,8 +13,6 @@ public class Messages {
// When creating pull requests that feature a message to the player, please
// stick to this scheme
public static ChestSortPlugin plugin;
public static String MSG_ACTIVATED, MSG_DEACTIVATED, MSG_INVACTIVATED, MSG_INVDEACTIVATED, MSG_COMMANDMESSAGE, MSG_COMMANDMESSAGE2, MSG_PLAYERSONLY,
MSG_PLAYERINVSORTED, MSG_INVALIDOPTIONS;
@ -24,8 +22,9 @@ public class Messages {
public static String MSG_ERR_HOTKEYSDISABLED;
public Messages(ChestSortPlugin plugin) {
this.plugin = plugin;
public Messages() {
ChestSortPlugin plugin = ChestSortPlugin.getInstance();
MSG_CONTAINER_SORTED = ChatColor.translateAlternateColorCodes('&', plugin.getConfig()
.getString("message-container-sorted","&aContainer sorted!"));

View File

@ -169,6 +169,7 @@ public class ChestSortOrganizer {
return totalEnchants;
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
boolean doesInventoryContain(Inventory inv, Material mat) {
for (ItemStack item : Utils.getStorageContents(inv, plugin.getMcMinorVersion())) {
if (item == null) continue;
@ -350,7 +351,7 @@ public class ChestSortOrganizer {
public Map<String, String> getSortableMap(ItemStack item) {
if (item == null) {
// Empty map for non-item
return new HashMap<String, String>();
return new HashMap<>();
}
char blocksFirst;
@ -376,7 +377,7 @@ public class ChestSortOrganizer {
// Only continue if Method "getBasePotionData" exists
Class<? extends PotionMeta> potionMetaClass = potionMeta.getClass();
try {
if (potionMetaClass.getDeclaredMethod("getBasePotionData", null) != null) {
if (potionMetaClass.getDeclaredMethod("getBasePotionData", (Class<?>) null) != null) {
if (potionMeta.getBasePotionData() != null) {
PotionData pdata = potionMeta.getBasePotionData();
if (pdata != null && pdata.getType() != null && pdata.getType().getEffectType() != null) {
@ -427,7 +428,7 @@ public class ChestSortOrganizer {
// Generate the map of string replacements used to generate a sortableString.
// This map can be edited by ChestSortEvent handlers. See ChestSortEvent.getSortableMaps()
Map<String, String> sortableMap = new HashMap<String, String>();
Map<String, String> sortableMap = new HashMap<>();
sortableMap.put("{itemsFirst}", String.valueOf(itemsFirst));
sortableMap.put("{blocksFirst}", String.valueOf(blocksFirst));
sortableMap.put("{name}", typeName + potionEffect);
@ -467,7 +468,7 @@ public class ChestSortOrganizer {
ChestSortEvent chestSortEvent = new ChestSortEvent(inv);
try {
if (invClass.getMethod("getLocation", null) != null) {
if (invClass.getMethod("getLocation", (Class<?>) null) != null) {
// This whole try/catch fixes MethodNotFoundException when using inv.getLocation in Spigot 1.8.
if (inv.getLocation() != null) {
chestSortEvent.setLocation(inv.getLocation());
@ -487,7 +488,7 @@ public class ChestSortOrganizer {
}
}
chestSortEvent.setSortableMaps(new HashMap<ItemStack, Map<String, String>>());
chestSortEvent.setSortableMaps(new HashMap<>());
for (ItemStack item : inv.getContents()) {
chestSortEvent.getSortableMaps().put(item, getSortableMap(item));
}
@ -517,15 +518,6 @@ public class ChestSortOrganizer {
for (int i = endSlot + 1; i < inv.getSize(); i++) {
items[i] = null;
}
// Get rid of all stuff that contains more than maxStackSize
// We do not need this as ChestSort will keep the "overstacked" stacks intact
/*for(int i = 0; i<endSlot; i++) {
if(inv.getItem(i) != null && inv.getItem(i).getAmount() > inv.getItem(i).getMaxStackSize()) {
//System.out.println("Debug: "+inv.getItem(i).getMaxStackSize());
//items[i] = null;
//unsortableSlots.add(i);
}
}*/
// Check for
// - Minepacks backpacks
// - Inventorypages buttons
@ -628,16 +620,13 @@ public class ChestSortOrganizer {
}
/*public void stuffPlayerInventoryIntoAnother(PlayerInventory source, Inventory destination) {
stuffPlayerInventoryIntoAnother(source,destination,false);
}*/
public void stuffInventoryIntoAnother(Inventory source, Inventory destination, Inventory origSource, boolean onlyMatchingStuff) {
ItemStack[] hotbarStuff = new ItemStack[9];
boolean destinationIsPlayerInventory = true;
if (destination.getHolder() == null || !(destination.getHolder() instanceof Player) || destination.getType() != InventoryType.PLAYER) {
if (destination.getHolder() == null
|| !(destination.getHolder() instanceof Player)
|| destination.getType() != InventoryType.PLAYER) {
destinationIsPlayerInventory = false;
}

View File

@ -9,8 +9,8 @@ import org.bukkit.permissions.PermissionAttachment;
public class ChestSortPermissionsHandler {
final HashMap<UUID,PermissionAttachment> permissions;
final ChestSortPlugin plugin;
private final HashMap<UUID,PermissionAttachment> permissions;
private final ChestSortPlugin plugin;
public ChestSortPermissionsHandler(ChestSortPlugin plugin) {
this.plugin = plugin;

View File

@ -7,7 +7,7 @@ import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.jetbrains.annotations.NotNull;
public class Debugger implements @NotNull Listener {
public class Debugger implements Listener {
private final ChestSortPlugin plugin;

View File

@ -5,7 +5,7 @@ import org.bukkit.inventory.Inventory;
public class CrateReloadedHook {
ChestSortPlugin main;
private final ChestSortPlugin main;
public CrateReloadedHook(ChestSortPlugin main) {
this.main=main;

View File

@ -1,13 +0,0 @@
package de.jeff_media.chestsort.hooks;
import org.bukkit.inventory.ItemStack;
public class CustomItemsHook {
public boolean isCustomItem(ItemStack item) {
return false;
}
}

View File

@ -8,19 +8,17 @@ import java.util.List;
public class GenericGUIHook {
ChestSortPlugin main;
boolean enabled;
private final List<String> guiClasses = Arrays.asList(new String[] {
"me.droreo002.chestshopconfirmation.inventory.ConfirmationInventory"
});
private final ChestSortPlugin main;
//boolean enabled;
private final List<String> guiClasses = Arrays.asList("me.droreo002.chestshopconfirmation.inventory.ConfirmationInventory");
public GenericGUIHook(ChestSortPlugin main, boolean enabled) {
this.main=main;
this.enabled=enabled;
//this.enabled=enabled;
}
public boolean isPluginGUI(Inventory inv) {
if(!enabled) return false;
if(inv.getHolder()!=null && (inv.getHolder().getClass().getName().toLowerCase().contains("gui")
|| inv.getHolder().getClass().getName().toLowerCase().contains("menu"))) {
main.debug("Generic GUI detected by class name containing \"gui\" or \"menu\"");

View File

@ -5,7 +5,7 @@ import org.bukkit.inventory.Inventory;
public class GoldenCratesHook {
ChestSortPlugin main;
private final ChestSortPlugin main;
public GoldenCratesHook(ChestSortPlugin main) {
this.main=main;

View File

@ -5,7 +5,7 @@ import org.bukkit.inventory.Inventory;
public class HeadDatabaseHook {
ChestSortPlugin main;
private final ChestSortPlugin main;
public HeadDatabaseHook(ChestSortPlugin main) {
this.main=main;

View File

@ -43,10 +43,7 @@ public class InventoryPagesHook {
prevName = ChatColor.translateAlternateColorCodes('&', inventoryPagesConfig.getString("items.prev.name"));
nextName = ChatColor.translateAlternateColorCodes('&', inventoryPagesConfig.getString("items.next.name"));
noPageName = ChatColor.translateAlternateColorCodes('&', inventoryPagesConfig.getString("items.noPage.name"));
//plugin.getLogger().info("Prev Button: " + prevSlot + "," + prevMat.name() + "," + prevName);
//plugin.getLogger().info("Next Button: " + nextSlot + "," + nextMat.name() + "," + nextName);
}
public boolean isButton(@NotNull ItemStack item, int slot, @NotNull Inventory inv) {
@ -59,11 +56,6 @@ public class InventoryPagesHook {
return false;
}
// When using &f as color, we manually have to add this to the string because it gets removed by InventoryPages
//if(prevName.startsWith("§f")) prevName = prevName.substring(2);
//if(nextName.startsWith("§f")) nextName = nextName.substring(2);
//if(noPageName.startsWith("§f")) noPageName = noPageName.substring(2);
if(slot == prevSlot ) {
if(item.getType() == prevMat && (ChatColor.stripColor(item.getItemMeta().getDisplayName()).equals(ChatColor.stripColor(prevName)))) {
return true;

View File

@ -5,7 +5,7 @@ import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.entity.Player;
public class Placeholders extends PlaceholderExpansion {
private ChestSortPlugin main;
private final ChestSortPlugin main;
public Placeholders(ChestSortPlugin main){