From 4cc354eed5c897556351ef7f6d38a5dc37a594a6 Mon Sep 17 00:00:00 2001 From: tastybento Date: Sat, 12 Oct 2024 12:00:58 -0700 Subject: [PATCH 01/23] Update to new codemc repo and version up to 2.6.1 --- pom.xml | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/pom.xml b/pom.xml index e49d241f5..6328f605d 100644 --- a/pom.xml +++ b/pom.xml @@ -52,12 +52,8 @@ codemc-snapshots - https://repo.codemc.org/repository/maven-snapshots + https://repo.codemc.org/repository/tastybento/ - - codemc-releases - https://repo.codemc.org/repository/maven-releases - @@ -88,7 +84,7 @@ -LOCAL - 2.6.0 + 2.6.1 bentobox-world https://sonarcloud.io ${project.basedir}/lib @@ -155,7 +151,7 @@ codemc-repo - https://repo.codemc.org/repository/maven-public + https://repo.codemc.io/repository/tastybento/ dynmap-repo From 58690f203bc912154d3a50204f1d6df7479b257b Mon Sep 17 00:00:00 2001 From: tastybento Date: Sat, 19 Oct 2024 10:48:45 -0700 Subject: [PATCH 02/23] WIP --- .../bentobox/api/panels/TemplatedPanel.java | 3 +- .../panels/customizable/AbstractPanel.java | 140 +++++++++++ .../customizable/IslandCreationPanel.java | 117 ++------- .../panels/customizable/LanguagePanel.java | 236 ++++++------------ .../panels/customizable/SettingsPanel.java | 59 +++++ 5 files changed, 297 insertions(+), 258 deletions(-) create mode 100644 src/main/java/world/bentobox/bentobox/panels/customizable/AbstractPanel.java create mode 100644 src/main/java/world/bentobox/bentobox/panels/customizable/SettingsPanel.java diff --git a/src/main/java/world/bentobox/bentobox/api/panels/TemplatedPanel.java b/src/main/java/world/bentobox/bentobox/api/panels/TemplatedPanel.java index 6310fa144..8afc57802 100644 --- a/src/main/java/world/bentobox/bentobox/api/panels/TemplatedPanel.java +++ b/src/main/java/world/bentobox/bentobox/api/panels/TemplatedPanel.java @@ -362,9 +362,8 @@ ItemSlot nextItemSlot() { * this button is present. * * @return Map that links button type to amount in the gui. - * @deprecated Use {@link #amount(String)} instead. + * Use {@link #amount(String)} instead. */ - @Deprecated public Map amountMap() { return this.parentPanel.typeSlotMap; } diff --git a/src/main/java/world/bentobox/bentobox/panels/customizable/AbstractPanel.java b/src/main/java/world/bentobox/bentobox/panels/customizable/AbstractPanel.java new file mode 100644 index 000000000..fb266a784 --- /dev/null +++ b/src/main/java/world/bentobox/bentobox/panels/customizable/AbstractPanel.java @@ -0,0 +1,140 @@ +package world.bentobox.bentobox.panels.customizable; + +import java.io.File; + +import org.bukkit.event.inventory.ClickType; + +import world.bentobox.bentobox.BentoBox; +import world.bentobox.bentobox.api.addons.GameModeAddon; +import world.bentobox.bentobox.api.commands.CompositeCommand; +import world.bentobox.bentobox.api.panels.PanelItem; +import world.bentobox.bentobox.api.panels.TemplatedPanel; +import world.bentobox.bentobox.api.panels.reader.ItemTemplateRecord; +import world.bentobox.bentobox.api.user.User; + +/** + * @author tastybento + */ +public abstract class AbstractPanel { + + // --------------------------------------------------------------------- + // Section: Constants + // --------------------------------------------------------------------- + + /** + * This constant is used for button to indicate that it is Language type. + */ + public static final String LOCALE = "LOCALE"; + + /** + * This constant is used for button to indicate that it is previous page type. + */ + public static final String PREVIOUS = "PREVIOUS"; + + /** + * This constant is used for button to indicate that it is next page type. + */ + public static final String NEXT = "NEXT"; + + /** + * This constant is used for indicating that pages should contain numbering. + */ + public static final String INDEXING = "indexing"; + + /** + * This constant stores value for SELECT action that is used in panels. + */ + public static final String SELECT_ACTION = "SELECT"; + + /** + * This constant stores value for COMMANDS action that is used in panels. + */ + public static final String COMMANDS_ACTION = "COMMANDS"; + + /** + * This constant stores value for AUTHORS label that is used in panels. + */ + public static final String AUTHORS = "[authors]"; + + /** + * This constant stores value for SELECTED label that is used in panels. + */ + public static final String SELECTED = "[selected]"; + + /** + * This variable allows to access plugin object. + */ + final BentoBox plugin; + + /** + * This variable stores main command that was triggered. + */ + final CompositeCommand command; + + /** + * This variable holds user who opens panel. Without it panel cannot be opened. + */ + final User user; + + /** + * This variable holds world where panel is opened. Without it panel cannot be opened. + */ + String mainLabel; + + /** + * This variable holds current pageIndex for multi-page island choosing. + */ + int pageIndex; + + public AbstractPanel(CompositeCommand command, User user) { + plugin = command.getPlugin(); + this.command = command; + this.user = user; + this.pageIndex = 0; // Start with the first page by default + } + + // Abstract methods for creating next and previous buttons + protected abstract PanelItem createNextButton(ItemTemplateRecord template, TemplatedPanel.ItemSlot slot); + + protected abstract PanelItem createPreviousButton(ItemTemplateRecord template, TemplatedPanel.ItemSlot slot); + + // Abstract build method to allow each panel to define its own layout + protected abstract void build(); + + // Default method for pagination, can be overridden by subclasses if needed + protected boolean hasNextPage(int elementListSize, int itemsPerPage) { + return (pageIndex + 1) * itemsPerPage < elementListSize; + } + + protected boolean hasPreviousPage() { + return pageIndex > 0; + } + + // Method to handle the click event on next/previous buttons + protected boolean handlePageChange(ItemTemplateRecord.ActionRecords action, ClickType clickType, + String actionType) { + if ((clickType == action.clickType() || action.clickType() == ClickType.UNKNOWN) + && actionType.equalsIgnoreCase(action.actionType())) { + if (actionType.equalsIgnoreCase("NEXT")) { + this.pageIndex++; + } else if (actionType.equalsIgnoreCase("PREVIOUS")) { + this.pageIndex--; + } + build(); + return true; + } + return false; + } + + /** + * This method returns if panel with the requested name is located in GameModeAddon folder. + * @param addon GameModeAddon that need to be checked. + * @param name Name of the panel. + * @return {@code true} if panel exists, {@code false} otherwise. + */ + protected boolean doesCustomPanelExists(GameModeAddon addon, String name) { + return addon.getDataFolder().exists() && new File(addon.getDataFolder(), "panels").exists() + && new File(addon.getDataFolder(), "panels" + File.separator + name + ".yml").exists(); + } + +} diff --git a/src/main/java/world/bentobox/bentobox/panels/customizable/IslandCreationPanel.java b/src/main/java/world/bentobox/bentobox/panels/customizable/IslandCreationPanel.java index a15e77571..ce493c310 100644 --- a/src/main/java/world/bentobox/bentobox/panels/customizable/IslandCreationPanel.java +++ b/src/main/java/world/bentobox/bentobox/panels/customizable/IslandCreationPanel.java @@ -22,8 +22,6 @@ import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; -import world.bentobox.bentobox.BentoBox; -import world.bentobox.bentobox.api.addons.GameModeAddon; import world.bentobox.bentobox.api.commands.CompositeCommand; import world.bentobox.bentobox.api.localization.TextVariables; import world.bentobox.bentobox.api.panels.PanelItem; @@ -41,7 +39,7 @@ * If file with such name is located at gamemode panels directory, then that file will be used. * Otherwise, file in BentoBox/panels is used. */ -public class IslandCreationPanel +public class IslandCreationPanel extends AbstractPanel { // --------------------------------------------------------------------- // Section: Constants @@ -51,37 +49,10 @@ public class IslandCreationPanel * This constant is used for button to indicate that it is Blueprint Bundle type. */ private static final String BUNDLES = "BUNDLE"; - - /** - * This constant is used for button to indicate that it is previous page type. - */ - private static final String PREVIOUS = "PREVIOUS"; - - /** - * This constant is used for button to indicate that it is next page type. - */ - private static final String NEXT = "NEXT"; - - /** - * This constant is used for indicating that pages should contain numbering. - */ - private static final String INDEXING = "indexing"; - - /** - * This constant stores value for SELECT action that is used in panels. - */ - private static final String SELECT_ACTION = "SELECT"; - - /** - * This constant stores value for COMMAND action that is used in panels. - */ - private static final String COMMANDS_ACTION = "COMMANDS"; - /** * This constant stores value for ERROR message that will be displayed upon failing to run creation commands. */ private static final String ISLAND_CREATION_COMMANDS = "ISLAND_CREATION_COMMANDS"; - /** * Button reference */ @@ -91,35 +62,11 @@ public class IslandCreationPanel // Section: Variables // --------------------------------------------------------------------- - /** - * This variable allows to access plugin object. - */ - private final BentoBox plugin; - - /** - * This variable stores main command that was triggered. - */ - private final CompositeCommand mainCommand; - - /** - * This variable holds user who opens panel. Without it panel cannot be opened. - */ - private final User user; - - /** - * This variable holds world where panel is opened. Without it panel cannot be opened. - */ - private final String mainLabel; - /** * This variable stores filtered elements. */ private final List elementList; - /** - * This variable holds current pageIndex for multi-page island choosing. - */ - private int pageIndex; /** * The world that this command applies to @@ -147,8 +94,7 @@ public class IslandCreationPanel private IslandCreationPanel(@NonNull CompositeCommand command, @NonNull User user, @NonNull String label, boolean reset) { - this.plugin = BentoBox.getInstance(); - this.user = user; + super(command, user); this.mainLabel = label; this.world = command.getWorld(); this.reset = reset; @@ -159,7 +105,6 @@ private IslandCreationPanel(@NonNull CompositeCommand command, .hasPermission(command.getPermissionPrefix() + "island.create." + bundle.getUniqueId())) .toList(); - this.mainCommand = command; } @@ -172,7 +117,8 @@ private IslandCreationPanel(@NonNull CompositeCommand command, * Build method manages current panel opening. It uses BentoBox PanelAPI that is easy to use and users can get nice * panels. */ - private void build() + @Override + protected void build() { // Do not open gui if there is no magic sticks. if (this.elementList.isEmpty()) @@ -187,10 +133,10 @@ private void build() TemplatedPanelBuilder panelBuilder = new TemplatedPanelBuilder(); // Set main template. - if (this.doesCustomPanelExists(this.mainCommand.getAddon(), "island_creation_panel")) + if (this.doesCustomPanelExists(this.command.getAddon(), "island_creation_panel")) { // Addon has its own island creation panel. Use it. - panelBuilder.template("island_creation_panel", new File(this.mainCommand.getAddon().getDataFolder(), "panels")); + panelBuilder.template("island_creation_panel", new File(this.command.getAddon().getDataFolder(), "panels")); } else { @@ -212,21 +158,6 @@ private void build() panelBuilder.build(); } - - /** - * This method returns if panel with the requested name is located in GameModeAddon folder. - * @param addon GameModeAddon that need to be checked. - * @param name Name of the panel. - * @return {@code true} if panel exists, {@code false} otherwise. - */ - private boolean doesCustomPanelExists(GameModeAddon addon, String name) - { - return addon.getDataFolder().exists() && - new File(addon.getDataFolder(), "panels").exists() - && new File(addon.getDataFolder(), "panels" + File.separator + name + ".yml").exists(); - } - - // --------------------------------------------------------------------- // Section: Buttons // --------------------------------------------------------------------- @@ -239,8 +170,9 @@ private boolean doesCustomPanelExists(GameModeAddon addon, String name) * @param slot the slot * @return the panel item */ + @Override @Nullable - private PanelItem createNextButton(@NonNull ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) + protected PanelItem createNextButton(@NonNull ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) { int size = this.elementList.size(); @@ -269,12 +201,12 @@ private PanelItem createNextButton(@NonNull ItemTemplateRecord template, Templat if (template.title() != null) { - builder.name(this.user.getTranslation(this.mainCommand.getWorld(), template.title())); + builder.name(this.user.getTranslation(this.command.getWorld(), template.title())); } if (template.description() != null) { - builder.description(this.user.getTranslation(this.mainCommand.getWorld(), template.description(), + builder.description(this.user.getTranslation(this.command.getWorld(), template.description(), TextVariables.NUMBER, String.valueOf(nextPageIndex))); } @@ -299,7 +231,7 @@ private PanelItem createNextButton(@NonNull ItemTemplateRecord template, Templat // Collect tooltips. List tooltips = template.actions().stream(). filter(action -> action.tooltip() != null) - .map(action -> this.user.getTranslation(this.mainCommand.getWorld(), action.tooltip())) + .map(action -> this.user.getTranslation(this.command.getWorld(), action.tooltip())) .filter(text -> !text.isBlank()) .collect(Collectors.toCollection(() -> new ArrayList<>(template.actions().size()))); @@ -323,7 +255,8 @@ private PanelItem createNextButton(@NonNull ItemTemplateRecord template, Templat * @return the panel item */ @Nullable - private PanelItem createPreviousButton(@NonNull ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) + @Override + protected PanelItem createPreviousButton(@NonNull ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) { if (this.pageIndex == 0) { @@ -349,12 +282,12 @@ private PanelItem createPreviousButton(@NonNull ItemTemplateRecord template, Tem if (template.title() != null) { - builder.name(this.user.getTranslation(this.mainCommand.getWorld(), template.title())); + builder.name(this.user.getTranslation(this.command.getWorld(), template.title())); } if (template.description() != null) { - builder.description(this.user.getTranslation(this.mainCommand.getWorld(), template.description(), + builder.description(this.user.getTranslation(this.command.getWorld(), template.description(), TextVariables.NUMBER, String.valueOf(previousPageIndex))); } @@ -379,7 +312,7 @@ private PanelItem createPreviousButton(@NonNull ItemTemplateRecord template, Tem // Collect tooltips. List tooltips = template.actions().stream(). filter(action -> action.tooltip() != null) - .map(action -> this.user.getTranslation(this.mainCommand.getWorld(), action.tooltip())) + .map(action -> this.user.getTranslation(this.command.getWorld(), action.tooltip())) .filter(text -> !text.isBlank()) .collect(Collectors.toCollection(() -> new ArrayList<>(template.actions().size()))); @@ -467,7 +400,7 @@ private PanelItem createBundleButton(ItemTemplateRecord template, BlueprintBundl if (template.title() != null) { - builder.name(this.user.getTranslation(this.mainCommand.getWorld(), template.title(), + builder.name(this.user.getTranslation(this.command.getWorld(), template.title(), TextVariables.NAME, bundle.getDisplayName())); } else @@ -478,7 +411,7 @@ private PanelItem createBundleButton(ItemTemplateRecord template, BlueprintBundl if (template.description() != null) { - builder.description(this.user.getTranslation(this.mainCommand.getWorld(), template.description(), + builder.description(this.user.getTranslation(this.command.getWorld(), template.description(), TextVariables.DESCRIPTION, String.join("\n", bundle.getDescription()))); } else @@ -524,13 +457,13 @@ private PanelItem createBundleButton(ItemTemplateRecord template, BlueprintBundl { if (SELECT_ACTION.equalsIgnoreCase(action.actionType())) { user.closeInventory(); - this.mainCommand.execute(user, this.mainLabel, + this.command.execute(user, this.mainLabel, Collections.singletonList(bundle.getUniqueId())); } else if (COMMANDS_ACTION.equalsIgnoreCase(action.actionType())) { Util.runCommands(user, Arrays.stream(action.content() .replaceAll(Pattern.quote(TextVariables.LABEL), - this.mainCommand.getTopLabel()) + this.command.getTopLabel()) .split("\n")).toList(), ISLAND_CREATION_COMMANDS); } @@ -543,7 +476,7 @@ private PanelItem createBundleButton(ItemTemplateRecord template, BlueprintBundl // Collect tooltips. List tooltips = actions.stream().filter(action -> action.tooltip() != null) - .map(action -> this.user.getTranslation(this.mainCommand.getWorld(), action.tooltip())) + .map(action -> this.user.getTranslation(this.command.getWorld(), action.tooltip())) .filter(text -> !text.isBlank()) .collect(Collectors.toCollection(() -> new ArrayList<>(actions.size()))); @@ -557,12 +490,10 @@ private PanelItem createBundleButton(ItemTemplateRecord template, BlueprintBundl return builder.build(); } - // --------------------------------------------------------------------- // Section: Static methods // --------------------------------------------------------------------- - /** * This method is used to open Panel outside this class. It will be much easier to open panel with single method * call then initializing new object. @@ -572,11 +503,9 @@ private PanelItem createBundleButton(ItemTemplateRecord template, BlueprintBundl * @param user User who opens panel * @param reset true if this is an island reset */ - public static void openPanel(@NonNull CompositeCommand command, - @NonNull User user, @NonNull String label, boolean reset) - { + public static void openPanel(@NonNull CompositeCommand command, @NonNull User user, @NonNull String label, + boolean reset) { new IslandCreationPanel(command, user, label, reset).build(); } - } diff --git a/src/main/java/world/bentobox/bentobox/panels/customizable/LanguagePanel.java b/src/main/java/world/bentobox/bentobox/panels/customizable/LanguagePanel.java index ba84e4c60..32b879b49 100644 --- a/src/main/java/world/bentobox/bentobox/panels/customizable/LanguagePanel.java +++ b/src/main/java/world/bentobox/bentobox/panels/customizable/LanguagePanel.java @@ -1,6 +1,7 @@ // // Created by BONNe // Copyright - 2022 +// Updated by tastybento // @@ -23,8 +24,6 @@ import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; -import world.bentobox.bentobox.BentoBox; -import world.bentobox.bentobox.api.addons.GameModeAddon; import world.bentobox.bentobox.api.commands.CompositeCommand; import world.bentobox.bentobox.api.localization.BentoBoxLocale; import world.bentobox.bentobox.api.localization.TextVariables; @@ -42,8 +41,17 @@ * If file with such name is located at gamemode panels directory, then that file will be used. * Otherwise, file in BentoBox/panels is used. */ -public class LanguagePanel +public class LanguagePanel extends AbstractPanel { + // --------------------------------------------------------------------- + // Section: Variables + // --------------------------------------------------------------------- + + /** + * This variable stores filtered elements. + */ + private final List elementList; + // --------------------------------------------------------------------- // Section: Constructor // --------------------------------------------------------------------- @@ -55,13 +63,24 @@ public class LanguagePanel * @param command The main addon command. * @param user User who opens panel */ - private LanguagePanel(@NonNull CompositeCommand command, @NonNull User user) - { - this.plugin = BentoBox.getInstance(); - this.mainCommand = command; - this.user = user; + public LanguagePanel(CompositeCommand command, User user) { + super(command, user); + this.elementList = plugin.getLocalesManager().getAvailableLocales(true); + } - this.elementList = BentoBox.getInstance().getLocalesManager().getAvailableLocales(true); + // --------------------------------------------------------------------- + // Section: Static methods + // --------------------------------------------------------------------- + + /** + * This method is used to open Panel outside this class. It will be much easier to open panel with single method + * call then initializing new object. + * + * @param command The main addon command. + * @param user User who opens panel + */ + public static void openPanel(@NonNull CompositeCommand command, @NonNull User user) { + new LanguagePanel(command, user).build(); } @@ -74,14 +93,15 @@ private LanguagePanel(@NonNull CompositeCommand command, @NonNull User user) * Build method manages current panel opening. It uses BentoBox PanelAPI that is easy to use and users can get nice * panels. */ - private void build() + @Override + protected void build() { // Do not open gui if there is no magic sticks. if (this.elementList.isEmpty()) { this.plugin.logError("There are no available locales for selection!"); this.user.sendMessage("no-locales", - TextVariables.GAMEMODE, this.plugin.getDescription().getName()); + TextVariables.GAMEMODE, this.plugin.getDescription().getName()); return; } @@ -89,10 +109,10 @@ private void build() TemplatedPanelBuilder panelBuilder = new TemplatedPanelBuilder(); // Set main template. - if (this.doesCustomPanelExists(this.mainCommand.getAddon(), "language_panel")) + if (this.doesCustomPanelExists(this.command.getAddon(), "language_panel")) { // Addon has its own island creation panel. Use it. - panelBuilder.template("language_panel", new File(this.mainCommand.getAddon().getDataFolder(), "panels")); + panelBuilder.template("language_panel", new File(this.command.getAddon().getDataFolder(), "panels")); } else { @@ -115,20 +135,6 @@ private void build() } - /** - * This method returns if panel with the requested name is located in GameModeAddon folder. - * @param addon GameModeAddon that need to be checked. - * @param name Name of the panel. - * @return {@code true} if panel exists, {@code false} otherwise. - */ - private boolean doesCustomPanelExists(GameModeAddon addon, String name) - { - return addon.getDataFolder().exists() && - new File(addon.getDataFolder(), "panels").exists() && - new File(addon.getDataFolder(), "panels" + File.separator + name + ".yml").exists(); - } - - // --------------------------------------------------------------------- // Section: Buttons // --------------------------------------------------------------------- @@ -141,13 +147,14 @@ private boolean doesCustomPanelExists(GameModeAddon addon, String name) * @param slot the slot * @return the panel item */ + @Override @Nullable - private PanelItem createNextButton(@NonNull ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) + protected PanelItem createNextButton(@NonNull ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) { int size = this.elementList.size(); if (size <= slot.amountMap().getOrDefault(LOCALE, 1) || - 1.0 * size / slot.amountMap().getOrDefault(LOCALE, 1) <= this.pageIndex + 1) + 1.0 * size / slot.amountMap().getOrDefault(LOCALE, 1) <= this.pageIndex + 1) { // There are no next elements return null; @@ -177,7 +184,7 @@ private PanelItem createNextButton(@NonNull ItemTemplateRecord template, Templat if (template.description() != null) { builder.description(this.user.getTranslation(template.description(), - TextVariables.NUMBER, String.valueOf(nextPageIndex))); + TextVariables.NUMBER, String.valueOf(nextPageIndex))); } // Add ClickHandler @@ -185,7 +192,7 @@ private PanelItem createNextButton(@NonNull ItemTemplateRecord template, Templat { template.actions().forEach(action -> { if ((clickType == action.clickType() || - action.clickType() == ClickType.UNKNOWN) && NEXT.equalsIgnoreCase(action.actionType())) + action.clickType() == ClickType.UNKNOWN) && NEXT.equalsIgnoreCase(action.actionType())) { // Next button ignores click type currently. this.pageIndex++; @@ -200,10 +207,9 @@ private PanelItem createNextButton(@NonNull ItemTemplateRecord template, Templat // Collect tooltips. List tooltips = template.actions().stream(). - filter(action -> action.tooltip() != null). - map(action -> this.user.getTranslation( action.tooltip())). - filter(text -> !text.isBlank()). - collect(Collectors.toCollection(() -> new ArrayList<>(template.actions().size()))); + filter(action -> action.tooltip() != null).map(action -> this.user.getTranslation(action.tooltip())) + .filter(text -> !text.isBlank()) + .collect(Collectors.toCollection(() -> new ArrayList<>(template.actions().size()))); // Add tooltips. if (!tooltips.isEmpty()) @@ -224,8 +230,9 @@ private PanelItem createNextButton(@NonNull ItemTemplateRecord template, Templat * @param slot the slot * @return the panel item */ + @Override @Nullable - private PanelItem createPreviousButton(@NonNull ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) + protected PanelItem createPreviousButton(@NonNull ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) { if (this.pageIndex == 0) { @@ -251,13 +258,13 @@ private PanelItem createPreviousButton(@NonNull ItemTemplateRecord template, Tem if (template.title() != null) { - builder.name(this.user.getTranslation(this.mainCommand.getWorld(), template.title())); + builder.name(this.user.getTranslation(this.command.getWorld(), template.title())); } if (template.description() != null) { - builder.description(this.user.getTranslation(this.mainCommand.getWorld(), template.description(), - TextVariables.NUMBER, String.valueOf(previousPageIndex))); + builder.description(this.user.getTranslation(this.command.getWorld(), template.description(), + TextVariables.NUMBER, String.valueOf(previousPageIndex))); } // Add ClickHandler @@ -266,7 +273,7 @@ private PanelItem createPreviousButton(@NonNull ItemTemplateRecord template, Tem { template.actions().forEach(action -> { if ((clickType == action.clickType() || - action.clickType() == ClickType.UNKNOWN) && PREVIOUS.equalsIgnoreCase(action.actionType())) + action.clickType() == ClickType.UNKNOWN) && PREVIOUS.equalsIgnoreCase(action.actionType())) { // Next button ignores click type currently. this.pageIndex--; @@ -281,10 +288,10 @@ private PanelItem createPreviousButton(@NonNull ItemTemplateRecord template, Tem // Collect tooltips. List tooltips = template.actions().stream(). - filter(action -> action.tooltip() != null). - map(action -> this.user.getTranslation(this.mainCommand.getWorld(), action.tooltip())). - filter(text -> !text.isBlank()). - collect(Collectors.toCollection(() -> new ArrayList<>(template.actions().size()))); + filter(action -> action.tooltip() != null) + .map(action -> this.user.getTranslation(this.command.getWorld(), action.tooltip())) + .filter(text -> !text.isBlank()) + .collect(Collectors.toCollection(() -> new ArrayList<>(template.actions().size()))); // Add tooltips. if (!tooltips.isEmpty()) @@ -330,9 +337,8 @@ private PanelItem createLocaleButton(ItemTemplateRecord template, TemplatedPanel { // Try to find locale with requested ID. if not found, use already collected locale. locale = this.elementList.stream(). - filter(localeID -> localeID.toLanguageTag().equals(template.dataMap().get("lang_id"))). - findFirst(). - orElse(locale); + filter(localeID -> localeID.toLanguageTag().equals(template.dataMap().get("lang_id"))).findFirst() + .orElse(locale); } return this.createLocaleButton(template, locale); @@ -371,18 +377,18 @@ private PanelItem createLocaleButton(ItemTemplateRecord template, Locale locale) else { builder.icon(Objects.requireNonNullElseGet(language.getBanner(), - () -> new ItemStack(Material.WHITE_BANNER, 1))); + () -> new ItemStack(Material.WHITE_BANNER, 1))); } if (template.title() != null) { - builder.name(this.user.getTranslation(this.mainCommand.getWorld(), template.title(), - TextVariables.NAME, WordUtils.capitalize(locale.getDisplayName(this.user.getLocale())))); + builder.name(this.user.getTranslation(this.command.getWorld(), template.title(), + TextVariables.NAME, WordUtils.capitalize(locale.getDisplayName(this.user.getLocale())))); } else { builder.name(this.user.getTranslation(reference + "name", - TextVariables.NAME, WordUtils.capitalize(locale.getDisplayName(this.user.getLocale())))); + TextVariables.NAME, WordUtils.capitalize(locale.getDisplayName(this.user.getLocale())))); } final StringBuilder authors = new StringBuilder(); @@ -405,28 +411,25 @@ private PanelItem createLocaleButton(ItemTemplateRecord template, Locale locale) if (template.description() != null) { descriptionText = this.user.getTranslationOrNothing(template.description(), - AUTHORS, authors.toString(), - SELECTED, selected.toString()); + AUTHORS, authors.toString(), SELECTED, selected.toString()); } else { descriptionText = this.user.getTranslationOrNothing(reference + "description", - AUTHORS, authors.toString(), - SELECTED, selected.toString()); + AUTHORS, authors.toString(), SELECTED, selected.toString()); } descriptionText = descriptionText.replaceAll("(?m)^[ \\t]*\\r?\\n", ""). - replaceAll("(? actions = template.actions().stream(). - filter(action -> !this.user.getLocale().equals(locale) && - (SELECT_ACTION.equalsIgnoreCase(action.actionType()) || - COMMANDS_ACTION.equalsIgnoreCase(action.actionType()))). - toList(); + filter(action -> !this.user.getLocale().equals(locale) + && (SELECT_ACTION.equalsIgnoreCase(action.actionType()) + || COMMANDS_ACTION.equalsIgnoreCase(action.actionType()))) + .toList(); // Add ClickHandler builder.clickHandler((panel, user, clickType, i) -> @@ -438,7 +441,7 @@ private PanelItem createLocaleButton(ItemTemplateRecord template, Locale locale) { this.plugin.getPlayers().setLocale(this.user.getUniqueId(), locale.toLanguageTag()); this.user.sendMessage("language.edited", "[lang]", - WordUtils.capitalize(locale.getDisplayName(this.user.getLocale()))); + WordUtils.capitalize(locale.getDisplayName(this.user.getLocale()))); // Rebuild panel this.build(); @@ -446,11 +449,11 @@ private PanelItem createLocaleButton(ItemTemplateRecord template, Locale locale) else if (COMMANDS_ACTION.equalsIgnoreCase(action.actionType())) { Util.runCommands(user, - Arrays.stream(action.content(). - replaceAll(Pattern.quote(TextVariables.LABEL), this.mainCommand.getTopLabel()). - split("\n")). + Arrays.stream(action.content() + .replaceAll(Pattern.quote(TextVariables.LABEL), this.command.getTopLabel()) + .split("\n")). toList(), - "CHANGE_LOCALE_COMMANDS"); + "CHANGE_LOCALE_COMMANDS"); } } }); @@ -461,10 +464,10 @@ else if (COMMANDS_ACTION.equalsIgnoreCase(action.actionType())) // Collect tooltips. List tooltips = actions.stream(). - filter(action -> action.tooltip() != null). - map(action -> this.user.getTranslation(this.mainCommand.getWorld(), action.tooltip())). - filter(text -> !text.isBlank()). - collect(Collectors.toCollection(() -> new ArrayList<>(actions.size()))); + filter(action -> action.tooltip() != null) + .map(action -> this.user.getTranslation(this.command.getWorld(), action.tooltip())) + .filter(text -> !text.isBlank()) + .collect(Collectors.toCollection(() -> new ArrayList<>(actions.size()))); // Add tooltips. if (!tooltips.isEmpty()) @@ -478,97 +481,6 @@ else if (COMMANDS_ACTION.equalsIgnoreCase(action.actionType())) } - // --------------------------------------------------------------------- - // Section: Static methods - // --------------------------------------------------------------------- - - - /** - * This method is used to open Panel outside this class. It will be much easier to open panel with single method - * call then initializing new object. - * - * @param command The main addon command. - * @param user User who opens panel - */ - public static void openPanel(@NonNull CompositeCommand command, @NonNull User user) - { - new LanguagePanel(command, user).build(); - } - - -// --------------------------------------------------------------------- -// Section: Constants -// --------------------------------------------------------------------- - - - /** - * This constant is used for button to indicate that it is Language type. - */ - private static final String LOCALE = "LOCALE"; - - /** - * This constant is used for button to indicate that it is previous page type. - */ - private static final String PREVIOUS = "PREVIOUS"; - - /** - * This constant is used for button to indicate that it is next page type. - */ - private static final String NEXT = "NEXT"; - - /** - * This constant is used for indicating that pages should contain numbering. - */ - private static final String INDEXING = "indexing"; - - /** - * This constant stores value for SELECT action that is used in panels. - */ - private static final String SELECT_ACTION = "SELECT"; - - /** - * This constant stores value for COMMANDS action that is used in panels. - */ - private static final String COMMANDS_ACTION = "COMMANDS"; - - /** - * This constant stores value for AUTHORS label that is used in panels. - */ - public static final String AUTHORS = "[authors]"; - - /** - * This constant stores value for SELECTED label that is used in panels. - */ - public static final String SELECTED = "[selected]"; - - -// --------------------------------------------------------------------- -// Section: Variables -// --------------------------------------------------------------------- - - - /** - * This variable allows to access plugin object. - */ - private final BentoBox plugin; - - /** - * This variable stores the main command object. - */ - private final CompositeCommand mainCommand; +} - /** - * This variable holds user who opens panel. Without it panel cannot be opened. - */ - private final User user; - /** - * This variable stores filtered elements. - */ - private final List elementList; - - /** - * This variable holds current pageIndex for multi-page island choosing. - */ - private int pageIndex; -} diff --git a/src/main/java/world/bentobox/bentobox/panels/customizable/SettingsPanel.java b/src/main/java/world/bentobox/bentobox/panels/customizable/SettingsPanel.java new file mode 100644 index 000000000..32c4ba91b --- /dev/null +++ b/src/main/java/world/bentobox/bentobox/panels/customizable/SettingsPanel.java @@ -0,0 +1,59 @@ +/** + * + */ +package world.bentobox.bentobox.panels.customizable; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.bukkit.World; + +import world.bentobox.bentobox.BentoBox; +import world.bentobox.bentobox.api.commands.CompositeCommand; +import world.bentobox.bentobox.api.flags.Flag; +import world.bentobox.bentobox.api.panels.PanelItem; +import world.bentobox.bentobox.api.panels.TabbedPanel; +import world.bentobox.bentobox.api.panels.TemplatedPanel.ItemSlot; +import world.bentobox.bentobox.api.panels.reader.ItemTemplateRecord; +import world.bentobox.bentobox.api.user.User; +import world.bentobox.bentobox.database.objects.Island; + +/** + * + */ +public class SettingsPanel extends AbstractPanel { + + protected static final String PROTECTION_PANEL = "protection.panel."; + private static final String CLICK_TO_SWITCH = PROTECTION_PANEL + "mode.click-to-switch"; + protected Flag.Type type; + protected World world; + protected Island island; + protected TabbedPanel parent; + + private Map currentMode = new HashMap<>(); + + public SettingsPanel(CompositeCommand command, User user) { + super(command, user); + // TODO Auto-generated constructor stub + } + + @Override + protected void build() { + // TODO Auto-generated method stub + + } + + @Override + protected PanelItem createNextButton(ItemTemplateRecord arg0, ItemSlot arg1) { + // TODO Auto-generated method stub + return null; + } + + @Override + protected PanelItem createPreviousButton(ItemTemplateRecord arg0, ItemSlot arg1) { + // TODO Auto-generated method stub + return null; + } + +} From ca9c81e47b0a38deb153508786d1bb2c08082843 Mon Sep 17 00:00:00 2001 From: tastybento Date: Sat, 19 Oct 2024 10:51:24 -0700 Subject: [PATCH 03/23] Revert "Update to new codemc repo and version up to 2.6.1" This reverts commit 4cc354eed5c897556351ef7f6d38a5dc37a594a6. --- pom.xml | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 6328f605d..e49d241f5 100644 --- a/pom.xml +++ b/pom.xml @@ -52,8 +52,12 @@ codemc-snapshots - https://repo.codemc.org/repository/tastybento/ + https://repo.codemc.org/repository/maven-snapshots + + codemc-releases + https://repo.codemc.org/repository/maven-releases + @@ -84,7 +88,7 @@ -LOCAL - 2.6.1 + 2.6.0 bentobox-world https://sonarcloud.io ${project.basedir}/lib @@ -151,7 +155,7 @@ codemc-repo - https://repo.codemc.io/repository/tastybento/ + https://repo.codemc.org/repository/maven-public dynmap-repo From e0a3f48aed9a1ed16d63a6e1ef4eadd94cd9bbd8 Mon Sep 17 00:00:00 2001 From: tastybento Date: Sun, 20 Oct 2024 16:29:32 -0700 Subject: [PATCH 04/23] Adds an island home panel. #2531 Also enhances the customizable panel API by making templates load dynamically when requested. --- .../world/bentobox/bentobox/BentoBox.java | 12 - .../api/commands/CompositeCommand.java | 2 +- .../api/commands/island/IslandGoCommand.java | 11 +- .../commands/island/IslandHomesCommand.java | 30 +- .../api/panels/reader/TemplateReader.java | 24 +- .../panels/customizable/IslandHomesPanel.java | 419 ++++++++++++++++++ src/main/resources/locales/en-US.yml | 6 + .../resources/panels/island_homes_panel.yml | 69 +++ 8 files changed, 526 insertions(+), 47 deletions(-) create mode 100644 src/main/java/world/bentobox/bentobox/panels/customizable/IslandHomesPanel.java create mode 100644 src/main/resources/panels/island_homes_panel.yml diff --git a/src/main/java/world/bentobox/bentobox/BentoBox.java b/src/main/java/world/bentobox/bentobox/BentoBox.java index 650d5e4a5..b0ad73046 100644 --- a/src/main/java/world/bentobox/bentobox/BentoBox.java +++ b/src/main/java/world/bentobox/bentobox/BentoBox.java @@ -1,7 +1,5 @@ package world.bentobox.bentobox; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.List; import java.util.Optional; @@ -466,16 +464,6 @@ public boolean loadSettings() { return false; } - log("Saving default panels..."); - if (!Files.exists(Path.of(this.getDataFolder().getPath(), "panels", "island_creation_panel.yml"))) { - log("Saving default island_creation_panel..."); - this.saveResource("panels/island_creation_panel.yml", false); - } - - if (!Files.exists(Path.of(this.getDataFolder().getPath(), "panels", "language_panel.yml"))) { - log("Saving default language_panel..."); - this.saveResource("panels/language_panel.yml", false); - } return true; } diff --git a/src/main/java/world/bentobox/bentobox/api/commands/CompositeCommand.java b/src/main/java/world/bentobox/bentobox/api/commands/CompositeCommand.java index 4d0a8146e..c75d67c80 100644 --- a/src/main/java/world/bentobox/bentobox/api/commands/CompositeCommand.java +++ b/src/main/java/world/bentobox/bentobox/api/commands/CompositeCommand.java @@ -346,7 +346,7 @@ private CompositeCommand getCommandFromArgs(String[] args) { * * @return IslandsManager */ - protected IslandsManager getIslands() { + public IslandsManager getIslands() { return plugin.getIslands(); } diff --git a/src/main/java/world/bentobox/bentobox/api/commands/island/IslandGoCommand.java b/src/main/java/world/bentobox/bentobox/api/commands/island/IslandGoCommand.java index cfe3f6c8e..0eeccbcbe 100644 --- a/src/main/java/world/bentobox/bentobox/api/commands/island/IslandGoCommand.java +++ b/src/main/java/world/bentobox/bentobox/api/commands/island/IslandGoCommand.java @@ -61,9 +61,9 @@ public boolean canExecute(User user, String label, List args) { @Override public boolean execute(User user, String label, List args) { + Map names = getNameIslandMap(user); // Check if the home is known if (!args.isEmpty()) { - Map names = getNameIslandMap(user); final String name = String.join(" ", args); if (!names.containsKey(name)) { // Failed home name check @@ -113,7 +113,11 @@ public Optional> tabComplete(User user, String alias, List } - private record IslandInfo(Island island, boolean islandName) {} + /** + * Record of islands and the name to type + */ + private record IslandInfo(Island island, boolean islandName) { + } private Map getNameIslandMap(User user) { Map islandMap = new HashMap<>(); @@ -129,7 +133,8 @@ private Map getNameIslandMap(User user) { islandMap.put(text, new IslandInfo(island, true)); } // Add homes. Homes do not need an island specified - island.getHomes().keySet().forEach(n -> islandMap.put(n, new IslandInfo(island, false))); + island.getHomes().keySet().stream().filter(n -> !n.isBlank()) + .forEach(n -> islandMap.put(n, new IslandInfo(island, false))); } return islandMap; diff --git a/src/main/java/world/bentobox/bentobox/api/commands/island/IslandHomesCommand.java b/src/main/java/world/bentobox/bentobox/api/commands/island/IslandHomesCommand.java index 33b077c5f..b9298664a 100644 --- a/src/main/java/world/bentobox/bentobox/api/commands/island/IslandHomesCommand.java +++ b/src/main/java/world/bentobox/bentobox/api/commands/island/IslandHomesCommand.java @@ -1,19 +1,12 @@ package world.bentobox.bentobox.api.commands.island; -import java.util.ArrayList; import java.util.List; -import java.util.Optional; import world.bentobox.bentobox.api.commands.CompositeCommand; -import world.bentobox.bentobox.api.commands.ConfirmableCommand; -import world.bentobox.bentobox.api.localization.TextVariables; import world.bentobox.bentobox.api.user.User; -import world.bentobox.bentobox.database.objects.Island; -import world.bentobox.bentobox.util.Util; +import world.bentobox.bentobox.panels.customizable.IslandHomesPanel; -public class IslandHomesCommand extends ConfirmableCommand { - - private List islands; +public class IslandHomesCommand extends CompositeCommand { public IslandHomesCommand(CompositeCommand islandCommand) { super(islandCommand, "homes"); @@ -28,9 +21,8 @@ public void setup() { @Override public boolean canExecute(User user, String label, List args) { - islands = getIslands().getIslands(getWorld(), user); // Check island - if (islands.isEmpty()) { + if (getIslands().getIslands(getWorld(), user).isEmpty()) { user.sendMessage("general.errors.no-island"); return false; } @@ -39,22 +31,8 @@ public boolean canExecute(User user, String label, List args) { @Override public boolean execute(User user, String label, List args) { - user.sendMessage("commands.island.sethome.homes-are"); - islands.forEach(island -> - island.getHomes().keySet().stream().filter(s -> !s.isEmpty()) - .forEach(s -> user.sendMessage("commands.island.sethome.home-list-syntax", TextVariables.NAME, s))); + IslandHomesPanel.openPanel(this, user); return true; } - @Override - public Optional> tabComplete(User user, String alias, List args) { - String lastArg = !args.isEmpty() ? args.get(args.size()-1) : ""; - List result = new ArrayList<>(); - for (Island island : getIslands().getIslands(getWorld(), user.getUniqueId())) { - result.addAll(island.getHomes().keySet()); - } - return Optional.of(Util.tabLimit(result, lastArg)); - - } - } diff --git a/src/main/java/world/bentobox/bentobox/api/panels/reader/TemplateReader.java b/src/main/java/world/bentobox/bentobox/api/panels/reader/TemplateReader.java index 524f0f260..ce837602d 100644 --- a/src/main/java/world/bentobox/bentobox/api/panels/reader/TemplateReader.java +++ b/src/main/java/world/bentobox/bentobox/api/panels/reader/TemplateReader.java @@ -90,15 +90,29 @@ public static PanelTemplateRecord readTemplatePanel(@NonNull String panelName, @ } File file = new File(panelLocation, templateName.endsWith(YML) ? templateName : templateName + YML); - + String absolutePath = file.getAbsolutePath(); if (!file.exists()) { - BentoBox.getInstance().logError(file.getAbsolutePath() + " does not exist for panel template"); - // Return as file does not exist. - return null; + // Try to get it from the JAR + + String keyword = "panels/"; + + // Find the index of the keyword "panels/" + int index = absolutePath.indexOf(keyword); + + // If the keyword is found, extract the substring starting from that index + if (index != -1) { + BentoBox.getInstance().saveResource(absolutePath.substring(index), false); + file = new File(panelLocation, templateName.endsWith(YML) ? templateName : templateName + YML); + } else { + BentoBox.getInstance().logError(file.getAbsolutePath() + " does not exist for panel template"); + // Return as file does not exist. + return null; + } + } - final String panelKey = file.getAbsolutePath() + ":" + panelName; + final String panelKey = absolutePath + ":" + panelName; // Check if panel is already crafted. if (TemplateReader.loadedPanels.containsKey(panelKey)) diff --git a/src/main/java/world/bentobox/bentobox/panels/customizable/IslandHomesPanel.java b/src/main/java/world/bentobox/bentobox/panels/customizable/IslandHomesPanel.java new file mode 100644 index 000000000..c760a21d8 --- /dev/null +++ b/src/main/java/world/bentobox/bentobox/panels/customizable/IslandHomesPanel.java @@ -0,0 +1,419 @@ +package world.bentobox.bentobox.panels.customizable; + + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.inventory.ItemStack; +import org.eclipse.jdt.annotation.NonNull; +import org.eclipse.jdt.annotation.Nullable; + +import world.bentobox.bentobox.api.commands.CompositeCommand; +import world.bentobox.bentobox.api.commands.island.IslandGoCommand; +import world.bentobox.bentobox.api.localization.TextVariables; +import world.bentobox.bentobox.api.panels.PanelItem; +import world.bentobox.bentobox.api.panels.TemplatedPanel; +import world.bentobox.bentobox.api.panels.builders.PanelItemBuilder; +import world.bentobox.bentobox.api.panels.builders.TemplatedPanelBuilder; +import world.bentobox.bentobox.api.panels.reader.ItemTemplateRecord; +import world.bentobox.bentobox.api.user.User; +import world.bentobox.bentobox.database.objects.Island; + + +/** + * Panel for island homes command + */ +public class IslandHomesPanel extends AbstractPanel +{ + + private static final String ISLAND = "ISLAND"; + + + /** + * This variable stores filtered elements. + */ + private final Map islandMap; + private final Map order = new HashMap<>(); + + + /** + * The world that this command applies to + */ + private final World world; + + private final IslandGoCommand goCommand; + + // --------------------------------------------------------------------- + // Section: Constructor + // --------------------------------------------------------------------- + + + /** + * This is internal constructor. It is used internally in current class to avoid creating objects everywhere. + * + * @param command CompositeCommand + * @param user User who opens panel + * @param islandMap map of island names and IslandInfo + */ + private IslandHomesPanel(@NonNull CompositeCommand command, @NonNull User user) + { + super(command, user); + this.world = command.getWorld(); + this.islandMap = this.getNameIslandMap(user); + int index = 0; + for (String name : islandMap.keySet()) { + order.put(index++, name); + } + goCommand = (IslandGoCommand) command.getParent().getSubCommand("go").orElse(null); + } + + + // --------------------------------------------------------------------- + // Section: Methods + // --------------------------------------------------------------------- + + + /** + * Build method manages current panel opening. It uses BentoBox PanelAPI that is easy to use and users can get nice + * panels. + */ + @Override + protected void build() + { + // Do not open gui if there are no islands + if (this.islandMap.isEmpty()) + { + user.sendMessage("general.errors.no-island"); + return; + } + + // Start building panel. + TemplatedPanelBuilder panelBuilder = new TemplatedPanelBuilder(); + + // Set main template. + if (this.doesCustomPanelExists(this.command.getAddon(), "island_homes_panel")) + { + // Addon has its own island homes panel. Use it. + panelBuilder.template("island_homes_panel", new File(this.command.getAddon().getDataFolder(), "panels")); + } + else + { + // Use default island creation panel. + panelBuilder.template("island_homes_panel", new File(this.plugin.getDataFolder(), "panels")); + } + + panelBuilder.user(this.user); + panelBuilder.world(world); + + // Register button builders + panelBuilder.registerTypeBuilder(ISLAND, this::createIslandButton); + + // Register next and previous builders + panelBuilder.registerTypeBuilder(NEXT, this::createNextButton); + panelBuilder.registerTypeBuilder(PREVIOUS, this::createPreviousButton); + + // Register unknown type builder. + panelBuilder.build(); + } + + // --------------------------------------------------------------------- + // Section: Buttons + // --------------------------------------------------------------------- + + + /** + * Create next button panel item. + * + * @param template the template + * @param slot the slot + * @return the panel item + */ + @Override + @Nullable + protected PanelItem createNextButton(@NonNull ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) + { + int size = this.islandMap.size(); + + if (size <= slot.amountMap().getOrDefault(ISLAND, 1) + || 1.0 * size / slot.amountMap().getOrDefault(ISLAND, 1) <= this.pageIndex + 1) + { + // There are no next elements + return null; + } + + int nextPageIndex = this.pageIndex + 2; + + PanelItemBuilder builder = new PanelItemBuilder(); + + if (template.icon() != null) + { + ItemStack clone = template.icon().clone(); + + if ((boolean) template.dataMap().getOrDefault(INDEXING, false)) + { + clone.setAmount(nextPageIndex); + } + + builder.icon(clone); + } + + if (template.title() != null) + { + builder.name(this.user.getTranslation(this.command.getWorld(), template.title())); + } + + if (template.description() != null) + { + builder.description(this.user.getTranslation(this.command.getWorld(), template.description(), + TextVariables.NUMBER, String.valueOf(nextPageIndex))); + } + + // Add ClickHandler + builder.clickHandler((panel, user, clickType, i) -> + { + template.actions().forEach(action -> { + if ((clickType == action.clickType() || + action.clickType() == ClickType.UNKNOWN) && NEXT.equalsIgnoreCase(action.actionType())) + { + // Next button ignores click type currently. + this.pageIndex++; + this.build(); + } + + }); + + // Always return true. + return true; + }); + + // Collect tooltips. + List tooltips = template.actions().stream(). + filter(action -> action.tooltip() != null) + .map(action -> this.user.getTranslation(this.command.getWorld(), action.tooltip())) + .filter(text -> !text.isBlank()) + .collect(Collectors.toCollection(() -> new ArrayList<>(template.actions().size()))); + + // Add tooltips. + if (!tooltips.isEmpty()) + { + // Empty line and tooltips. + builder.description(""); + builder.description(tooltips); + } + + return builder.build(); + } + + + /** + * Create previous button panel item. + * + * @param template the template + * @param slot the slot + * @return the panel item + */ + @Nullable + @Override + protected PanelItem createPreviousButton(@NonNull ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) + { + if (this.pageIndex == 0) + { + // There are no next elements + return null; + } + + int previousPageIndex = this.pageIndex; + + PanelItemBuilder builder = new PanelItemBuilder(); + + if (template.icon() != null) + { + ItemStack clone = template.icon().clone(); + + if ((boolean) template.dataMap().getOrDefault(INDEXING, false)) + { + clone.setAmount(previousPageIndex); + } + + builder.icon(clone); + } + + if (template.title() != null) + { + builder.name(this.user.getTranslation(this.command.getWorld(), template.title())); + } + + if (template.description() != null) + { + builder.description(this.user.getTranslation(this.command.getWorld(), template.description(), + TextVariables.NUMBER, String.valueOf(previousPageIndex))); + } + + // Add ClickHandler + builder.clickHandler((panel, user, clickType, i) -> + { + template.actions().forEach(action -> { + if ((clickType == action.clickType() || + action.clickType() == ClickType.UNKNOWN) && PREVIOUS.equalsIgnoreCase(action.actionType())) + { + // Next button ignores click type currently. + this.pageIndex--; + this.build(); + } + + }); + + // Always return true. + return true; + }); + + // Collect tooltips. + List tooltips = template.actions().stream(). + filter(action -> action.tooltip() != null) + .map(action -> this.user.getTranslation(this.command.getWorld(), action.tooltip())) + .filter(text -> !text.isBlank()) + .collect(Collectors.toCollection(() -> new ArrayList<>(template.actions().size()))); + + // Add tooltips. + if (!tooltips.isEmpty()) + { + // Empty line and tooltips. + builder.description(""); + builder.description(tooltips); + } + + return builder.build(); + } + + + /** + * This method creates and returns island button. + * + * @return PanelItem that represents island button. + */ + @Nullable + private PanelItem createIslandButton(ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) + { + if (this.islandMap.isEmpty()) + { + // Does not contain any islands. + return null; + } + + int index = this.pageIndex * slot.amountMap().getOrDefault(ISLAND, 1) + slot.slot(); + if (index >= this.islandMap.size()) + { + // Out of index. + return null; + } + return this.createIslandButtonDetail(template, slot); + } + + + /** + * This method creates bundle button. + * + * @return PanelItem that allows to select bundle button + */ + private PanelItem createIslandButtonDetail(ItemTemplateRecord template, TemplatedPanel.ItemSlot slot) + { + // Get settings for island. + PanelItemBuilder builder = new PanelItemBuilder(); + + if (template.icon() != null) + { + builder.icon(template.icon().clone()); + } + else + { + builder.icon(Material.GRASS_BLOCK); + } + + if (template.title() != null) + { + builder.name(this.user.getTranslation(this.command.getWorld(), template.title(), + TextVariables.NAME, order.get(slot.slot()))); + } + else + { + builder.name(this.user.getTranslation("panels.island_homes.buttons.name", TextVariables.NAME, + order.get(slot.slot()))); + } + + // Add ClickHandler + builder.clickHandler((panel, user, clickType, i) -> { + template.actions().forEach(action -> { + if (goCommand != null) { + String name = order.get(slot.slot()); + user.closeInventory(); + if (goCommand.canExecute(user, "", List.of(name))) { + goCommand.execute(user, "", List.of(name)); + } + } + }); + + // Always return true. + return true; + }); + + return builder.build(); + } + + /** + * Record of islands and the name to type + */ + private record IslandInfo(Island island, boolean islandName) { + } + + /** + * This is duplicate code from the Go command. + * @param user user + * @return name and island info + */ + private Map getNameIslandMap(User user) { + Map islandMap = new HashMap<>(); + int index = 0; + for (Island island : command.getIslands().getIslands(command.getWorld(), user.getUniqueId())) { + index++; + if (island.getName() != null && !island.getName().isBlank()) { + // Name has been set + islandMap.put(island.getName(), new IslandInfo(island, true)); + } else { + // Name has not been set + String text = user.getTranslation("protection.flags.ENTER_EXIT_MESSAGES.island", TextVariables.NAME, + user.getName(), TextVariables.DISPLAY_NAME, user.getDisplayName()) + " " + index; + islandMap.put(text, new IslandInfo(island, true)); + } + // Add homes. Homes do not need an island specified + island.getHomes().keySet().stream().filter(n -> !n.isBlank()) + .forEach(n -> islandMap.put(n, new IslandInfo(island, false))); + } + + return islandMap; + + } + + // --------------------------------------------------------------------- + // Section: Static methods + // --------------------------------------------------------------------- + + /** + * This method is used to open Panel outside this class. It will be much easier to open panel with single method + * call then initializing new object. + * + * @param command CompositeCommand object + * @param user User who opens panel + */ + public static void openPanel(@NonNull CompositeCommand command, @NonNull User user) { + new IslandHomesPanel(command, user).build(); + } + + +} diff --git a/src/main/resources/locales/en-US.yml b/src/main/resources/locales/en-US.yml index 97134b403..e89e21a49 100644 --- a/src/main/resources/locales/en-US.yml +++ b/src/main/resources/locales/en-US.yml @@ -1906,6 +1906,12 @@ panel: # This section contains values for BentoBox panels. panels: + # The section of translations used in Island Homes Panel + island_homes: + title: "&2&l Your island homes" + buttons: + # This button is used for displaying islands to teleport to + name: "&l [name]" # The section of translations used in Island Creation Panel island_creation: title: "&2&l Pick an island" diff --git a/src/main/resources/panels/island_homes_panel.yml b/src/main/resources/panels/island_homes_panel.yml new file mode 100644 index 000000000..1b0d6327b --- /dev/null +++ b/src/main/resources/panels/island_homes_panel.yml @@ -0,0 +1,69 @@ +# This is default island homes panel. It is used in all situations when gamemode addon does not have specified their +# of panel. +island_homes_panel: + title: panels.island_go.title # The title of panel or link to the localization location. + type: INVENTORY # The type of inventory: INVENTORY, DROPPER, HOPPER + background: # The item that will be displayed in empty spots. This section can be removed. + icon: BLACK_STAINED_GLASS_PANE # The icon of background item + title: "&b&r" # Empty text # The text of background item + border: # The item that will be displayed around the inventory. This section can be removed. + icon: BLACK_STAINED_GLASS_PANE # The icon of background item + title: "&b&r" # Empty text # The text of background item + force-shown: [] # Allow to specify (1-6, 1-3, 1) which rows must be showed regardless of empty elements. + content: # Allow to define buttons in your panel. + 2: + 2: island_button # String values are expected to be `reusables` that are defined at the end of this file. + 3: island_button + 4: island_button + 5: island_button + 6: island_button + 7: island_button + 8: island_button + 3: + 1: + icon: tipped_arrow{CustomPotionColor:11546150} # The icon for button + title: panels.buttons.previous.name # The name of button, or link to the localization. + description: panels.buttons.previous.description # The description of button, or link to the localization. + data: + type: PREVIOUS # Indicates what button is doing. Available values depends on panel + indexing: true # Parameter for button. + actions: # List of actions that button can do. Available values depends on button + previous: + click-type: UNKNOWN # UNKNOWN means that any click type is respected. + tooltip: panels.tips.click-to-previous # Tooltips are always generated an empty line bellow description/title. Not required. + 2: island_button + 3: island_button + 4: island_button + 5: island_button + 6: island_button + 7: island_button + 8: island_button + 9: + icon: tipped_arrow{CustomPotionColor:8439583} + title: panels.buttons.next.name + description: panels.buttons.next.description + data: + type: NEXT + indexing: true + actions: + next: + click-type: UNKNOWN + tooltip: panels.tips.click-to-next + 4: + 2: island_button + 3: island_button + 4: island_button + 5: island_button + 6: island_button + 7: island_button + 8: island_button + reusable: # List of reoccurring buttons in the panels. + island_button: # The ID of the button + # icon: GRASS_BLOCK + title: panels.island_homes.buttons.name + data: + type: ISLAND + actions: + select: + click-type: UNKNOWN + tooltip: panels.tips.click-to-choose \ No newline at end of file From 6766c0f9063def97a933c9afa81460f6af449cda Mon Sep 17 00:00:00 2001 From: tastybento Date: Sun, 20 Oct 2024 17:10:10 -0700 Subject: [PATCH 05/23] Store the island sizes in the grid to avoid database loadings #2534 --- .../bentobox/managers/IslandsManager.java | 4 + .../bentobox/managers/island/IslandCache.java | 17 ++++ .../bentobox/managers/island/IslandGrid.java | 77 +++++++++++++------ .../panels/customizable/SettingsPanel.java | 59 -------------- 4 files changed, 74 insertions(+), 83 deletions(-) delete mode 100644 src/main/java/world/bentobox/bentobox/panels/customizable/SettingsPanel.java diff --git a/src/main/java/world/bentobox/bentobox/managers/IslandsManager.java b/src/main/java/world/bentobox/bentobox/managers/IslandsManager.java index f3cfaf0fc..464ad9602 100644 --- a/src/main/java/world/bentobox/bentobox/managers/IslandsManager.java +++ b/src/main/java/world/bentobox/bentobox/managers/IslandsManager.java @@ -442,6 +442,10 @@ public Optional getIslandAt(@NonNull Location location) { : Optional.empty(); } + public boolean isIslandAd(@NonNull Location location) { + return plugin.getIWM().inWorld(location) ? islandCache.isIslandAt(location) : false; + } + /** * Returns an unmodifiable collection of all existing islands * (even those who may be unowned). diff --git a/src/main/java/world/bentobox/bentobox/managers/island/IslandCache.java b/src/main/java/world/bentobox/bentobox/managers/island/IslandCache.java index b5f3f5413..a1c0c6859 100644 --- a/src/main/java/world/bentobox/bentobox/managers/island/IslandCache.java +++ b/src/main/java/world/bentobox/bentobox/managers/island/IslandCache.java @@ -257,6 +257,23 @@ public void setPrimaryIsland(@NonNull UUID uuid, @NonNull Island island) { } } + /** + * Returns if there is island at the location. This includes + * the full island space, not just the protected area. + * Does not cause a database load of the island. + * + * @param location the location + * @return true if there is an island there + */ + @Nullable + public boolean isIslandAt(@NonNull Location location) { + World w = Util.getWorld(location.getWorld()); + if (w == null || !grids.containsKey(w)) { + return false; + } + return grids.get(w).isIslandAt(location.getBlockX(), location.getBlockZ()); + } + /** * Returns the island at the location or null if there is none. This includes * the full island space, not just the protected area diff --git a/src/main/java/world/bentobox/bentobox/managers/island/IslandGrid.java b/src/main/java/world/bentobox/bentobox/managers/island/IslandGrid.java index 11a76c367..82120a986 100644 --- a/src/main/java/world/bentobox/bentobox/managers/island/IslandGrid.java +++ b/src/main/java/world/bentobox/bentobox/managers/island/IslandGrid.java @@ -3,6 +3,8 @@ import java.util.Map.Entry; import java.util.TreeMap; +import org.eclipse.jdt.annotation.Nullable; + import world.bentobox.bentobox.database.objects.Island; /** @@ -11,7 +13,11 @@ * */ class IslandGrid { - private final TreeMap> grid = new TreeMap<>(); + + private record IslandData(String id, int minX, int minZ, int range) { + } + + private final TreeMap> grid = new TreeMap<>(); private final IslandCache im; /** @@ -29,10 +35,13 @@ public IslandGrid(IslandCache im) { */ public boolean addToGrid(Island island) { // Check if we know about this island already - if (grid.containsKey(island.getMinX())) { - TreeMap zEntry = grid.get(island.getMinX()); - if (zEntry.containsKey(island.getMinZ())) { - if (island.getUniqueId().equals(zEntry.get(island.getMinZ()))) { + int minX = island.getMinX(); + int minZ = island.getMinZ(); + IslandData islandData = new IslandData(island.getUniqueId(), minZ, minZ, island.getRange()); + if (grid.containsKey(minX)) { + TreeMap zEntry = grid.get(minX); + if (zEntry.containsKey(minZ)) { + if (island.getUniqueId().equals(zEntry.get(minZ).id())) { // If it is the same island then it's okay return true; } @@ -40,14 +49,14 @@ public boolean addToGrid(Island island) { return false; } else { // Add island - zEntry.put(island.getMinZ(), island.getUniqueId()); - grid.put(island.getMinX(), zEntry); + zEntry.put(minZ, islandData); + grid.put(minX, zEntry); } } else { // Add island - TreeMap zEntry = new TreeMap<>(); - zEntry.put(island.getMinZ(), island.getUniqueId()); - grid.put(island.getMinX(), zEntry); + TreeMap zEntry = new TreeMap<>(); + zEntry.put(minZ, islandData); + grid.put(minX, zEntry); } return true; } @@ -60,7 +69,7 @@ public boolean addToGrid(Island island) { public boolean removeFromGrid(Island island) { String id = island.getUniqueId(); boolean removed = grid.values().stream() - .anyMatch(innerMap -> innerMap.values().removeIf(innerValue -> innerValue.equals(id))); + .anyMatch(innerMap -> innerMap.values().removeIf(innerValue -> innerValue.id().equals(id))); grid.values().removeIf(TreeMap::isEmpty); @@ -70,35 +79,55 @@ public boolean removeFromGrid(Island island) { /** * Retrieves the island located at the specified x and z coordinates, covering both the protected area * and the full island space. Returns null if no island exists at the given location. + * This will load the island from the database if it is not in the cache. * * @param x the x coordinate of the location * @param z the z coordinate of the location * @return the Island at the specified location, or null if no island is found */ public Island getIslandAt(int x, int z) { + String id = getIslandStringAt(x, z); + if (id == null) { + return null; + } + + // Retrieve the island using the id found - loading from database if required + return im.getIslandById(id); + } + + /** + * Checks if an island is at this coordinate or not + * @param x coord + * @param z coord + * @return true if there is an island registered in the grid + */ + public boolean isIslandAt(int x, int z) { + return getIslandStringAt(x, z) != null; + } + + /** + * Get the island ID string for an island at this coordinates, or null if none. + * @param x coord + * @param z coord + * @return Unique Island ID string, or null if there is no island here. + */ + public @Nullable String getIslandStringAt(int x, int z) { // Attempt to find the closest x-coordinate entry that does not exceed 'x' - Entry> xEntry = grid.floorEntry(x); + Entry> xEntry = grid.floorEntry(x); if (xEntry == null) { return null; // No x-coordinate entry found, return null } // Attempt to find the closest z-coordinate entry that does not exceed 'z' within the found x-coordinate - Entry zEntry = xEntry.getValue().floorEntry(z); + Entry zEntry = xEntry.getValue().floorEntry(z); if (zEntry == null) { return null; // No z-coordinate entry found, return null } - - // Retrieve the island using the id found in the z-coordinate entry - Island island = im.getIslandById(zEntry.getValue()); - if (island == null) { - return null; // No island found by the id, return null - } // Check if the specified coordinates are within the island space - if (island.inIslandSpace(x, z)) { - return island; // Coordinates are within island space, return the island + if (x >= zEntry.getValue().minX() && x < zEntry.getValue().minX() + zEntry.getValue().range() * 2 + && z >= zEntry.getValue().minZ() && z < zEntry.getValue().minZ() + zEntry.getValue().range() * 2) { + return zEntry.getValue().id(); } - - // Coordinates are outside the island space, return null return null; } @@ -107,7 +136,7 @@ public Island getIslandAt(int x, int z) { */ public long getSize() { long count = 0; - for (TreeMap innerMap : grid.values()) { + for (TreeMap innerMap : grid.values()) { count += innerMap.size(); } return count; diff --git a/src/main/java/world/bentobox/bentobox/panels/customizable/SettingsPanel.java b/src/main/java/world/bentobox/bentobox/panels/customizable/SettingsPanel.java deleted file mode 100644 index 32c4ba91b..000000000 --- a/src/main/java/world/bentobox/bentobox/panels/customizable/SettingsPanel.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * - */ -package world.bentobox.bentobox.panels.customizable; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.bukkit.World; - -import world.bentobox.bentobox.BentoBox; -import world.bentobox.bentobox.api.commands.CompositeCommand; -import world.bentobox.bentobox.api.flags.Flag; -import world.bentobox.bentobox.api.panels.PanelItem; -import world.bentobox.bentobox.api.panels.TabbedPanel; -import world.bentobox.bentobox.api.panels.TemplatedPanel.ItemSlot; -import world.bentobox.bentobox.api.panels.reader.ItemTemplateRecord; -import world.bentobox.bentobox.api.user.User; -import world.bentobox.bentobox.database.objects.Island; - -/** - * - */ -public class SettingsPanel extends AbstractPanel { - - protected static final String PROTECTION_PANEL = "protection.panel."; - private static final String CLICK_TO_SWITCH = PROTECTION_PANEL + "mode.click-to-switch"; - protected Flag.Type type; - protected World world; - protected Island island; - protected TabbedPanel parent; - - private Map currentMode = new HashMap<>(); - - public SettingsPanel(CompositeCommand command, User user) { - super(command, user); - // TODO Auto-generated constructor stub - } - - @Override - protected void build() { - // TODO Auto-generated method stub - - } - - @Override - protected PanelItem createNextButton(ItemTemplateRecord arg0, ItemSlot arg1) { - // TODO Auto-generated method stub - return null; - } - - @Override - protected PanelItem createPreviousButton(ItemTemplateRecord arg0, ItemSlot arg1) { - // TODO Auto-generated method stub - return null; - } - -} From f9c34e5df676f897434d1c5d8895efdce8729968 Mon Sep 17 00:00:00 2001 From: tastybento Date: Sun, 20 Oct 2024 17:57:59 -0700 Subject: [PATCH 06/23] Test fixes --- .../api/commands/island/IslandHomesCommandTest.java | 6 ------ .../panels/customizable/IslandCreationPanelTest.java | 1 + .../bentobox/panels/customizable/LanguagePanelTest.java | 3 +-- 3 files changed, 2 insertions(+), 8 deletions(-) diff --git a/src/test/java/world/bentobox/bentobox/api/commands/island/IslandHomesCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/island/IslandHomesCommandTest.java index a5702fcb9..9d32760f9 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/island/IslandHomesCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/island/IslandHomesCommandTest.java @@ -8,7 +8,6 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -39,7 +38,6 @@ import world.bentobox.bentobox.BentoBox; import world.bentobox.bentobox.Settings; import world.bentobox.bentobox.api.commands.CompositeCommand; -import world.bentobox.bentobox.api.localization.TextVariables; import world.bentobox.bentobox.api.user.User; import world.bentobox.bentobox.database.objects.Island; import world.bentobox.bentobox.managers.CommandsManager; @@ -200,12 +198,8 @@ public void testCanExecute() { */ @Test public void testExecuteUserStringListOfString() { - when(im.getIslands(world, user)).thenReturn(List.of(island)); IslandHomesCommand isc = new IslandHomesCommand(ic); - assertTrue(isc.canExecute(user, "island", Collections.emptyList())); assertTrue(isc.execute(user, "island", Collections.emptyList())); - verify(user).sendMessage("commands.island.sethome.homes-are"); - verify(user, times(4)).sendMessage(eq("commands.island.sethome.home-list-syntax"), eq(TextVariables.NAME), anyString()); } } diff --git a/src/test/java/world/bentobox/bentobox/panels/customizable/IslandCreationPanelTest.java b/src/test/java/world/bentobox/bentobox/panels/customizable/IslandCreationPanelTest.java index 9931a7642..0f8bb9433 100644 --- a/src/test/java/world/bentobox/bentobox/panels/customizable/IslandCreationPanelTest.java +++ b/src/test/java/world/bentobox/bentobox/panels/customizable/IslandCreationPanelTest.java @@ -139,6 +139,7 @@ public void setUp() throws Exception { when(ic.getAddon()).thenReturn(addon); World world = mock(World.class); when(ic.getWorld()).thenReturn(world); + when(ic.getPlugin()).thenReturn(plugin); // No island for player to begin with (set it later in the tests) when(im.hasIsland(any(), eq(uuid))).thenReturn(false); diff --git a/src/test/java/world/bentobox/bentobox/panels/customizable/LanguagePanelTest.java b/src/test/java/world/bentobox/bentobox/panels/customizable/LanguagePanelTest.java index 94adc7e89..2a2ad5526 100644 --- a/src/test/java/world/bentobox/bentobox/panels/customizable/LanguagePanelTest.java +++ b/src/test/java/world/bentobox/bentobox/panels/customizable/LanguagePanelTest.java @@ -108,6 +108,7 @@ public void setUp() throws Exception { GameModeAddon addon = mock(GameModeAddon.class); when(command.getAddon()).thenReturn(addon); + when(command.getPlugin()).thenReturn(plugin); when(addon.getDataFolder()).thenReturn(resourcePath.toFile()); World world = mock(World.class); @@ -139,8 +140,6 @@ public void setUp() throws Exception { } - /** - */ @After public void tearDown() { User.clearUsers(); From 3d696e10d567be3917ae1ba9d63a419bc599a22a Mon Sep 17 00:00:00 2001 From: tastybento Date: Sun, 20 Oct 2024 20:32:49 -0700 Subject: [PATCH 07/23] Avoid loading islands unless necessary --- pom.xml | 2 +- .../world/bentobox/bentobox/managers/IslandsManager.java | 2 +- .../island/DefaultNewIslandLocationStrategy.java | 4 +++- .../bentobox/bentobox/managers/island/IslandGrid.java | 8 ++++---- .../bentobox/managers/island/IslandCacheTest.java | 9 ++++----- 5 files changed, 13 insertions(+), 12 deletions(-) diff --git a/pom.xml b/pom.xml index e49d241f5..88aac5660 100644 --- a/pom.xml +++ b/pom.xml @@ -88,7 +88,7 @@ -LOCAL - 2.6.0 + 2.7.0 bentobox-world https://sonarcloud.io ${project.basedir}/lib diff --git a/src/main/java/world/bentobox/bentobox/managers/IslandsManager.java b/src/main/java/world/bentobox/bentobox/managers/IslandsManager.java index 464ad9602..b85781153 100644 --- a/src/main/java/world/bentobox/bentobox/managers/IslandsManager.java +++ b/src/main/java/world/bentobox/bentobox/managers/IslandsManager.java @@ -442,7 +442,7 @@ public Optional getIslandAt(@NonNull Location location) { : Optional.empty(); } - public boolean isIslandAd(@NonNull Location location) { + public boolean isIslandAt(@NonNull Location location) { return plugin.getIWM().inWorld(location) ? islandCache.isIslandAt(location) : false; } diff --git a/src/main/java/world/bentobox/bentobox/managers/island/DefaultNewIslandLocationStrategy.java b/src/main/java/world/bentobox/bentobox/managers/island/DefaultNewIslandLocationStrategy.java index 46994fac7..fc5ecab3b 100644 --- a/src/main/java/world/bentobox/bentobox/managers/island/DefaultNewIslandLocationStrategy.java +++ b/src/main/java/world/bentobox/bentobox/managers/island/DefaultNewIslandLocationStrategy.java @@ -74,7 +74,9 @@ public Location getNextLocation(World world) { */ protected Result isIsland(Location location) { // Quick check - if (plugin.getIslands().getIslandAt(location).isPresent()) return Result.ISLAND_FOUND; + if (plugin.getIslands().isIslandAt(location)) { + return Result.ISLAND_FOUND; + } World world = location.getWorld(); diff --git a/src/main/java/world/bentobox/bentobox/managers/island/IslandGrid.java b/src/main/java/world/bentobox/bentobox/managers/island/IslandGrid.java index 82120a986..8afed14a2 100644 --- a/src/main/java/world/bentobox/bentobox/managers/island/IslandGrid.java +++ b/src/main/java/world/bentobox/bentobox/managers/island/IslandGrid.java @@ -37,7 +37,7 @@ public boolean addToGrid(Island island) { // Check if we know about this island already int minX = island.getMinX(); int minZ = island.getMinZ(); - IslandData islandData = new IslandData(island.getUniqueId(), minZ, minZ, island.getRange()); + IslandData islandData = new IslandData(island.getUniqueId(), minX, minZ, island.getRange()); if (grid.containsKey(minX)) { TreeMap zEntry = grid.get(minX); if (zEntry.containsKey(minZ)) { @@ -99,7 +99,7 @@ public Island getIslandAt(int x, int z) { * Checks if an island is at this coordinate or not * @param x coord * @param z coord - * @return true if there is an island registered in the grid + * @return true if there is an island registered here in the grid */ public boolean isIslandAt(int x, int z) { return getIslandStringAt(x, z) != null; @@ -124,8 +124,8 @@ public boolean isIslandAt(int x, int z) { return null; // No z-coordinate entry found, return null } // Check if the specified coordinates are within the island space - if (x >= zEntry.getValue().minX() && x < zEntry.getValue().minX() + zEntry.getValue().range() * 2 - && z >= zEntry.getValue().minZ() && z < zEntry.getValue().minZ() + zEntry.getValue().range() * 2) { + if (x >= zEntry.getValue().minX() && x < (zEntry.getValue().minX() + zEntry.getValue().range() * 2) + && z >= zEntry.getValue().minZ() && z < (zEntry.getValue().minZ() + zEntry.getValue().range() * 2)) { return zEntry.getValue().id(); } return null; diff --git a/src/test/java/world/bentobox/bentobox/managers/island/IslandCacheTest.java b/src/test/java/world/bentobox/bentobox/managers/island/IslandCacheTest.java index 787459983..b9a1c283f 100644 --- a/src/test/java/world/bentobox/bentobox/managers/island/IslandCacheTest.java +++ b/src/test/java/world/bentobox/bentobox/managers/island/IslandCacheTest.java @@ -137,6 +137,7 @@ public void setUp() throws Exception { when(island.getMemberSet()).thenReturn(members.build()); when(island.getMinX()).thenReturn(-200); when(island.getMinZ()).thenReturn(-200); + when(island.getRange()).thenReturn(400); // database must be mocked here db = mock(Database.class); @@ -234,12 +235,10 @@ public void testGetIslandAtLocation() throws InstantiationException, IllegalAcce Location location2 = mock(Location.class); when(location2.getWorld()).thenReturn(world); - when(location2.getBlockX()).thenReturn(10); - when(location2.getBlockY()).thenReturn(10); - when(location2.getBlockZ()).thenReturn(10); + when(location2.getBlockX()).thenReturn(10000); + when(location2.getBlockY()).thenReturn(100); + when(location2.getBlockZ()).thenReturn(10000); - assertEquals(island, ic.getIslandAt(location2)); - when(island.inIslandSpace(any(Integer.class), any(Integer.class))).thenReturn(false); assertNull(ic.getIslandAt(location2)); } From 57b8a517f011a04a7312aecd9fcc6f38f74b8878 Mon Sep 17 00:00:00 2001 From: tastybento Date: Mon, 21 Oct 2024 17:41:07 -0700 Subject: [PATCH 08/23] Fix panel title --- src/main/resources/panels/island_homes_panel.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/panels/island_homes_panel.yml b/src/main/resources/panels/island_homes_panel.yml index 1b0d6327b..c1d7a93e2 100644 --- a/src/main/resources/panels/island_homes_panel.yml +++ b/src/main/resources/panels/island_homes_panel.yml @@ -1,7 +1,7 @@ # This is default island homes panel. It is used in all situations when gamemode addon does not have specified their # of panel. island_homes_panel: - title: panels.island_go.title # The title of panel or link to the localization location. + title: panels.island_homes.title # The title of panel or link to the localization location. type: INVENTORY # The type of inventory: INVENTORY, DROPPER, HOPPER background: # The item that will be displayed in empty spots. This section can be removed. icon: BLACK_STAINED_GLASS_PANE # The icon of background item From 68ede87bb927cde10227f2ec27857211d8a14fe7 Mon Sep 17 00:00:00 2001 From: tastybento Date: Tue, 22 Oct 2024 22:33:17 -0700 Subject: [PATCH 09/23] Do not use isAir() because it cannot be mocked. --- .../world/bentobox/bentobox/database/objects/Island.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/world/bentobox/bentobox/database/objects/Island.java b/src/main/java/world/bentobox/bentobox/database/objects/Island.java index c9b585a9b..e55c6a0ea 100644 --- a/src/main/java/world/bentobox/bentobox/database/objects/Island.java +++ b/src/main/java/world/bentobox/bentobox/database/objects/Island.java @@ -19,6 +19,7 @@ import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; +import org.bukkit.Material; import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.entity.Player; @@ -1512,7 +1513,7 @@ public void setGameMode(String gameMode) { */ public boolean hasNetherIsland() { World nether = BentoBox.getInstance().getIWM().getNetherWorld(getWorld()); - return nether != null && !getCenter().toVector().toLocation(nether).getBlock().getType().isAir(); + return nether != null && (getCenter().toVector().toLocation(nether).getBlock().getType() != Material.AIR); } /** @@ -1536,7 +1537,7 @@ public boolean isNetherIslandEnabled() { */ public boolean hasEndIsland() { World end = BentoBox.getInstance().getIWM().getEndWorld(getWorld()); - return end != null && !getCenter().toVector().toLocation(end).getBlock().getType().isAir(); + return end != null && (getCenter().toVector().toLocation(end).getBlock().getType() != Material.AIR); } /** From 6a638a550f39f892575ebd7ab0d8227a3b885606 Mon Sep 17 00:00:00 2001 From: tastybento Date: Tue, 22 Oct 2024 22:50:04 -0700 Subject: [PATCH 10/23] Test fixed by removing line. --- .../api/commands/admin/AdminSettingsCommandTest.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminSettingsCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminSettingsCommandTest.java index d4e73e4a4..2ee85d39d 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminSettingsCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminSettingsCommandTest.java @@ -5,7 +5,6 @@ import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -23,7 +22,6 @@ import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.entity.Player; -import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemFactory; import org.bukkit.inventory.meta.ItemMeta; @@ -167,8 +165,7 @@ public void setUp() throws Exception { when(itemFactory.getItemMeta(any())).thenReturn(bannerMeta); when(Bukkit.getItemFactory()).thenReturn(itemFactory); Inventory inventory = mock(Inventory.class); - when(Bukkit.createInventory(eq(null), Mockito.anyInt(), any())).thenReturn(inventory); - when(Bukkit.createInventory(eq(null), any(InventoryType.class), any())).thenReturn(inventory); + when(Bukkit.createInventory(any(), Mockito.anyInt(), anyString())).thenReturn(inventory); // Flags manager when(Bukkit.getPluginManager()).thenReturn(pluginManager); FlagsManager fm = new FlagsManager(plugin); From c994dbdd3df277f32a68be0db9670ce0919b0337 Mon Sep 17 00:00:00 2001 From: tastybento Date: Tue, 22 Oct 2024 22:51:49 -0700 Subject: [PATCH 11/23] Fix by removing mock --- .../bentobox/api/panels/builders/PanelBuilderTest.java | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/test/java/world/bentobox/bentobox/api/panels/builders/PanelBuilderTest.java b/src/test/java/world/bentobox/bentobox/api/panels/builders/PanelBuilderTest.java index 03d9f1d8c..29f0a7b1c 100644 --- a/src/test/java/world/bentobox/bentobox/api/panels/builders/PanelBuilderTest.java +++ b/src/test/java/world/bentobox/bentobox/api/panels/builders/PanelBuilderTest.java @@ -1,16 +1,11 @@ -/** - * - */ package world.bentobox.bentobox.api.panels.builders; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import org.bukkit.Bukkit; -import org.bukkit.inventory.Inventory; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -35,8 +30,6 @@ @PrepareForTest({Bukkit.class}) public class PanelBuilderTest { - /** - */ @Before public void setUp() throws Exception { PowerMockito.mockStatic(Bukkit.class, Mockito.RETURNS_MOCKS); @@ -44,9 +37,6 @@ public void setUp() throws Exception { BentoBox plugin = mock(BentoBox.class); Whitebox.setInternalState(BentoBox.class, "instance", plugin); - Inventory inv = mock(Inventory.class); - when(Bukkit.createInventory(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(inv); - } @After From 618a86b464ed6f2a5be2621af7a6aea5e91004ed Mon Sep 17 00:00:00 2001 From: tastybento Date: Wed, 23 Oct 2024 14:09:57 -0700 Subject: [PATCH 12/23] Fix hex codes conversion. Using the spigot chat API requires conversion from legacy codes. --- src/main/java/world/bentobox/bentobox/api/user/User.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/world/bentobox/bentobox/api/user/User.java b/src/main/java/world/bentobox/bentobox/api/user/User.java index 64278ed29..6ce478236 100644 --- a/src/main/java/world/bentobox/bentobox/api/user/User.java +++ b/src/main/java/world/bentobox/bentobox/api/user/User.java @@ -616,6 +616,7 @@ public void sendMessage(String reference, String... variables) { * @param message The message to send, containing inline commands in square brackets. */ public void sendRawMessage(String message) { + BentoBox.getInstance().logDebug(message); // Create a base TextComponent for the message TextComponent baseComponent = new TextComponent(); @@ -632,7 +633,7 @@ public void sendRawMessage(String message) { // Add any text before the current match if (matcher.start() > lastMatchEnd) { String beforeMatch = message.substring(lastMatchEnd, matcher.start()); - baseComponent.addExtra(new TextComponent(beforeMatch)); + baseComponent.addExtra(TextComponent.fromLegacy(beforeMatch)); } // Check if it's a recognized command or an unknown bracketed text @@ -658,12 +659,12 @@ public void sendRawMessage(String message) { break; default: // Unrecognized command; preserve it in the output text - baseComponent.addExtra(new TextComponent(matcher.group(0))); + baseComponent.addExtra(TextComponent.fromLegacy(matcher.group(0))); } } else if (matcher.group(3) != null) { // Unrecognized bracketed text; preserve it in the output - baseComponent.addExtra(new TextComponent("[[" + matcher.group(3) + "]]")); + baseComponent.addExtra(TextComponent.fromLegacy("[[" + matcher.group(3) + "]]")); } // Update the last match end position @@ -673,7 +674,7 @@ public void sendRawMessage(String message) { // Add any remaining text after the last match if (lastMatchEnd < message.length()) { String remainingText = message.substring(lastMatchEnd); - baseComponent.addExtra(new TextComponent(remainingText)); + baseComponent.addExtra(TextComponent.fromLegacy(remainingText)); } // Apply the first encountered ClickEvent and HoverEvent to the entire message From fdd8b7f894cf2aaa55d0f3cc1b9d884543b1ae28 Mon Sep 17 00:00:00 2001 From: tastybento Date: Wed, 23 Oct 2024 14:35:18 -0700 Subject: [PATCH 13/23] Fix test --- src/test/java/world/bentobox/bentobox/AbstractCommonSetup.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/world/bentobox/bentobox/AbstractCommonSetup.java b/src/test/java/world/bentobox/bentobox/AbstractCommonSetup.java index 11adee0ad..d81205f35 100644 --- a/src/test/java/world/bentobox/bentobox/AbstractCommonSetup.java +++ b/src/test/java/world/bentobox/bentobox/AbstractCommonSetup.java @@ -280,7 +280,7 @@ public void checkSpigotMessage(String expectedMessage, int expectedOccurrences) List capturedMessages = captor.getAllValues(); // Count the number of occurrences of the expectedMessage in the captured messages - long actualOccurrences = capturedMessages.stream().map(component -> component.toPlainText()) // Convert each TextComponent to plain text + long actualOccurrences = capturedMessages.stream().map(component -> component.toLegacyText()) // Convert each TextComponent to plain text .filter(messageText -> messageText.contains(expectedMessage)) // Check if the message contains the expected text .count(); // Count how many times the expected message appears From 03888f811df04d241ded7e61ae4c56109bd97449 Mon Sep 17 00:00:00 2001 From: tastybento Date: Wed, 23 Oct 2024 20:22:13 -0700 Subject: [PATCH 14/23] WIP --- pom.xml | 2 +- .../bentobox/database/objects/Players.java | 18 +++++++ .../bentobox/listeners/JoinLeaveListener.java | 3 ++ .../bentobox/managers/PlayersManager.java | 28 +++++++++++ .../PasteHandlerImpl.java | 8 +++ .../WorldRegeneratorImpl.java | 8 +++ .../bentobox/AbstractCommonSetup.java | 7 ++- .../dataobjects/BlueprintEntityTest.java | 7 ++- .../listeners/PanelListenerManagerTest.java | 49 ++++++++++++++++++- .../protection/BreakBlocksListenerTest.java | 2 +- .../worldsettings/CreeperListenerTest.java | 8 +-- .../bentobox/util/ItemParserTest.java | 6 +++ 12 files changed, 136 insertions(+), 10 deletions(-) create mode 100644 src/main/java/world/bentobox/bentobox/nms/v1_21_2_R0_1_SNAPSHOT/PasteHandlerImpl.java create mode 100644 src/main/java/world/bentobox/bentobox/nms/v1_21_2_R0_1_SNAPSHOT/WorldRegeneratorImpl.java diff --git a/pom.xml b/pom.xml index 88aac5660..2a0f34f0a 100644 --- a/pom.xml +++ b/pom.xml @@ -73,7 +73,7 @@ 42.2.18 5.0.1 - 1.20.5-R0.1-SNAPSHOT + 1.21.2-R0.1-SNAPSHOT 1.20.6-R0.1-SNAPSHOT diff --git a/src/main/java/world/bentobox/bentobox/database/objects/Players.java b/src/main/java/world/bentobox/bentobox/database/objects/Players.java index 883072d7c..3a447332d 100644 --- a/src/main/java/world/bentobox/bentobox/database/objects/Players.java +++ b/src/main/java/world/bentobox/bentobox/database/objects/Players.java @@ -10,6 +10,7 @@ import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.entity.Player; +import org.eclipse.jdt.annotation.Nullable; import com.google.gson.annotations.Expose; @@ -37,6 +38,8 @@ public class Players implements DataObject, MetaDataAble { private String locale = ""; @Expose private Map deaths = new HashMap<>(); + @Expose + private Long lastLogin; /** * This variable stores set of worlds where user inventory must be cleared. @@ -292,5 +295,20 @@ public void setMetaData(Map metaData) { this.metaData = metaData; } + /** + * @return the lastLogin, Unix timestamp, or null if never logged in since this was tracked + * @since 2.6.0 + */ + @Nullable + public Long getLastLogin() { + return lastLogin; + } + + /** + * @param lastLogin the lastLogin to set + */ + public void setLastLogin(Long lastLogin) { + this.lastLogin = lastLogin; + } } diff --git a/src/main/java/world/bentobox/bentobox/listeners/JoinLeaveListener.java b/src/main/java/world/bentobox/bentobox/listeners/JoinLeaveListener.java index eac3174e4..cb88fda96 100644 --- a/src/main/java/world/bentobox/bentobox/listeners/JoinLeaveListener.java +++ b/src/main/java/world/bentobox/bentobox/listeners/JoinLeaveListener.java @@ -64,6 +64,9 @@ public void onPlayerJoin(final PlayerJoinEvent event) { // don't exist players.getPlayer(playerUUID); + // Set the login + players.setLoginTimeStamp(user); + // Reset island resets if required plugin.getIWM().getOverWorlds().stream() .filter(w -> event.getPlayer().getLastPlayed() < plugin.getIWM().getResetEpoch(w)) diff --git a/src/main/java/world/bentobox/bentobox/managers/PlayersManager.java b/src/main/java/world/bentobox/bentobox/managers/PlayersManager.java index a92f4c2e9..9f9d1f0d3 100644 --- a/src/main/java/world/bentobox/bentobox/managers/PlayersManager.java +++ b/src/main/java/world/bentobox/bentobox/managers/PlayersManager.java @@ -420,4 +420,32 @@ public CompletableFuture savePlayer(UUID uuid) { return CompletableFuture.completedFuture(false); } + /** + * Records when the user last logged in. Called by the joinleave listener + * @param user user + */ + public void setLoginTimeStamp(User user) { + if (user.isPlayer() && user.isOnline()) { + Players p = this.getPlayer(user.getUniqueId()); + if (p != null) { + p.setLastLogin(System.currentTimeMillis()); + this.savePlayer(user.getUniqueId()); + } + } + } + + /** + * Get the last login time stamp for this player + * @param uuid player's UUID + * @return timestamp or null if unknown or not recorded yet + */ + @Nullable + public Long getLastLoginTimestamp(UUID uuid) { + Players p = this.getPlayer(uuid); + if (p != null) { + return p.getLastLogin(); + } + return null; + } + } diff --git a/src/main/java/world/bentobox/bentobox/nms/v1_21_2_R0_1_SNAPSHOT/PasteHandlerImpl.java b/src/main/java/world/bentobox/bentobox/nms/v1_21_2_R0_1_SNAPSHOT/PasteHandlerImpl.java new file mode 100644 index 000000000..1a2cb4315 --- /dev/null +++ b/src/main/java/world/bentobox/bentobox/nms/v1_21_2_R0_1_SNAPSHOT/PasteHandlerImpl.java @@ -0,0 +1,8 @@ +package world.bentobox.bentobox.nms.v1_21_2_R0_1_SNAPSHOT; + +/** + * Same as 1.21 + */ +public class PasteHandlerImpl extends world.bentobox.bentobox.nms.v1_21_R0_1_SNAPSHOT.PasteHandlerImpl { + // Do nothing special +} diff --git a/src/main/java/world/bentobox/bentobox/nms/v1_21_2_R0_1_SNAPSHOT/WorldRegeneratorImpl.java b/src/main/java/world/bentobox/bentobox/nms/v1_21_2_R0_1_SNAPSHOT/WorldRegeneratorImpl.java new file mode 100644 index 000000000..a8e048d5a --- /dev/null +++ b/src/main/java/world/bentobox/bentobox/nms/v1_21_2_R0_1_SNAPSHOT/WorldRegeneratorImpl.java @@ -0,0 +1,8 @@ +package world.bentobox.bentobox.nms.v1_21_2_R0_1_SNAPSHOT; + +/** + * Same as 1.21 + */ +public class WorldRegeneratorImpl extends world.bentobox.bentobox.nms.v1_21_R0_1_SNAPSHOT.WorldRegeneratorImpl { + // Do nothing special + } diff --git a/src/test/java/world/bentobox/bentobox/AbstractCommonSetup.java b/src/test/java/world/bentobox/bentobox/AbstractCommonSetup.java index 11adee0ad..8d9eb0894 100644 --- a/src/test/java/world/bentobox/bentobox/AbstractCommonSetup.java +++ b/src/test/java/world/bentobox/bentobox/AbstractCommonSetup.java @@ -20,6 +20,8 @@ import org.bukkit.Tag; import org.bukkit.World; import org.bukkit.block.Block; +import org.bukkit.damage.DamageSource; +import org.bukkit.damage.DamageType; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Player.Spigot; @@ -298,13 +300,14 @@ public void checkSpigotMessage(String expectedMessage, int expectedOccurrences) */ public EntityExplodeEvent getExplodeEvent(Entity entity, Location l, List list) { //return new EntityExplodeEvent(entity, l, list, 0, null); - return new EntityExplodeEvent(entity, l, list, 0); + return new EntityExplodeEvent(entity, l, list, 0, null); } public PlayerDeathEvent getPlayerDeathEvent(Player player, List drops, int droppedExp, int newExp, int newTotalExp, int newLevel, @Nullable String deathMessage) { //return new PlayerDeathEvent(player, null, drops, droppedExp, newExp, newTotalExp, newLevel, deathMessage); - return new PlayerDeathEvent(player, drops, droppedExp, newExp, newTotalExp, newLevel, deathMessage); + return new PlayerDeathEvent(player, DamageSource.builder(DamageType.GENERIC).build(), drops, droppedExp, newExp, + newTotalExp, newLevel, deathMessage); } } diff --git a/src/test/java/world/bentobox/bentobox/blueprints/dataobjects/BlueprintEntityTest.java b/src/test/java/world/bentobox/bentobox/blueprints/dataobjects/BlueprintEntityTest.java index ed2bb7e9d..9fa3ba0bd 100644 --- a/src/test/java/world/bentobox/bentobox/blueprints/dataobjects/BlueprintEntityTest.java +++ b/src/test/java/world/bentobox/bentobox/blueprints/dataobjects/BlueprintEntityTest.java @@ -8,6 +8,8 @@ import org.bukkit.DyeColor; import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; import org.bukkit.entity.ChestedHorse; import org.bukkit.entity.Cow; import org.bukkit.entity.EntityType; @@ -21,6 +23,7 @@ import org.junit.After; import org.junit.Assert; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; @@ -34,6 +37,7 @@ * */ @RunWith(PowerMockRunner.class) +@Ignore("Cannot mock Villager Professions anynore") public class BlueprintEntityTest { @Mock @@ -55,7 +59,8 @@ public class BlueprintEntityTest { */ @Before public void setUp() throws Exception { - when(villager.getProfession()).thenReturn(Profession.LIBRARIAN); + when(villager.getProfession()) + .thenReturn(Registry.VILLAGER_PROFESSION.get(NamespacedKey.minecraft("librarian"))); when(villager.getVillagerExperience()).thenReturn(100); when(villager.getVillagerLevel()).thenReturn(2); when(villager.getVillagerType()).thenReturn(Villager.Type.PLAINS); diff --git a/src/test/java/world/bentobox/bentobox/listeners/PanelListenerManagerTest.java b/src/test/java/world/bentobox/bentobox/listeners/PanelListenerManagerTest.java index 365c2f735..5e249e731 100644 --- a/src/test/java/world/bentobox/bentobox/listeners/PanelListenerManagerTest.java +++ b/src/test/java/world/bentobox/bentobox/listeners/PanelListenerManagerTest.java @@ -126,7 +126,7 @@ public void setUp() throws Exception { PanelListenerManager.getOpenPanels().clear(); } - class MyView extends InventoryView { + class MyView implements InventoryView { private final Inventory top; private final String name; @@ -195,6 +195,53 @@ public ItemStack getItem(int slot) { return null; } + @Override + public void setCursor(ItemStack item) { + // TODO Auto-generated method stub + + } + + @Override + public ItemStack getCursor() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Inventory getInventory(int rawSlot) { + // TODO Auto-generated method stub + return null; + } + + @Override + public int convertSlot(int rawSlot) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public SlotType getSlotType(int slot) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void close() { + // TODO Auto-generated method stub + + } + + @Override + public int countSlots() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public boolean setProperty(Property prop, int value) { + // TODO Auto-generated method stub + return false; + } } diff --git a/src/test/java/world/bentobox/bentobox/listeners/flags/protection/BreakBlocksListenerTest.java b/src/test/java/world/bentobox/bentobox/listeners/flags/protection/BreakBlocksListenerTest.java index c85479552..6a14ef448 100644 --- a/src/test/java/world/bentobox/bentobox/listeners/flags/protection/BreakBlocksListenerTest.java +++ b/src/test/java/world/bentobox/bentobox/listeners/flags/protection/BreakBlocksListenerTest.java @@ -338,7 +338,7 @@ public void testOnVehicleDamageEventNotAllowedBoat() { when(island.isAllowed(any(), any())).thenReturn(false); Vehicle vehicle = mock(Vehicle.class); when(vehicle.getLocation()).thenReturn(location); - when(vehicle.getType()).thenReturn(EntityType.BOAT); + when(vehicle.getType()).thenReturn(EntityType.OAK_BOAT); VehicleDamageEvent e = new VehicleDamageEvent(vehicle, mockPlayer, 10); bbl.onVehicleDamageEvent(e); assertTrue(e.isCancelled()); diff --git a/src/test/java/world/bentobox/bentobox/listeners/flags/worldsettings/CreeperListenerTest.java b/src/test/java/world/bentobox/bentobox/listeners/flags/worldsettings/CreeperListenerTest.java index cf4c4f225..a135bfa6a 100644 --- a/src/test/java/world/bentobox/bentobox/listeners/flags/worldsettings/CreeperListenerTest.java +++ b/src/test/java/world/bentobox/bentobox/listeners/flags/worldsettings/CreeperListenerTest.java @@ -65,7 +65,7 @@ public void testOnExplosionNotCreeper() { Entity entity = mock(Entity.class); when(entity.getType()).thenReturn(EntityType.TNT); when(iwm.inWorld(location)).thenReturn(true); - EntityExplodeEvent event = new EntityExplodeEvent(entity, location, list, 0); + EntityExplodeEvent event = new EntityExplodeEvent(entity, location, list, 0, null); cl.onExplosion(event); assertFalse(event.isCancelled()); } @@ -80,7 +80,7 @@ public void testOnExplosionNotInWorld() { when(entity.getLocation()).thenReturn(location); when(entity.getType()).thenReturn(EntityType.CREEPER); when(iwm.inWorld(location)).thenReturn(false); - EntityExplodeEvent event = new EntityExplodeEvent(entity, location, list, 0); + EntityExplodeEvent event = new EntityExplodeEvent(entity, location, list, 0, null); cl.onExplosion(event); assertFalse(event.isCancelled()); } @@ -98,7 +98,7 @@ public void testOnExplosionCreeperInWorldDamageOK() { when(entity.getLocation()).thenReturn(location); when(entity.getType()).thenReturn(EntityType.CREEPER); when(iwm.inWorld(location)).thenReturn(true); - EntityExplodeEvent event = new EntityExplodeEvent(entity, location, list, 0); + EntityExplodeEvent event = new EntityExplodeEvent(entity, location, list, 0, null); cl.onExplosion(event); assertFalse(event.isCancelled()); assertFalse(event.blockList().isEmpty()); // No clearing of block list @@ -119,7 +119,7 @@ public void testOnExplosionCreeperInWorldDamageNOK() { when(entity.getLocation()).thenReturn(location); when(entity.getType()).thenReturn(EntityType.CREEPER); when(iwm.inWorld(location)).thenReturn(true); - EntityExplodeEvent event = new EntityExplodeEvent(entity, location, list, 0); + EntityExplodeEvent event = new EntityExplodeEvent(entity, location, list, 0, null); cl.onExplosion(event); assertFalse(event.isCancelled()); assertTrue(event.blockList().isEmpty()); // No clearing of block list diff --git a/src/test/java/world/bentobox/bentobox/util/ItemParserTest.java b/src/test/java/world/bentobox/bentobox/util/ItemParserTest.java index 429ed1466..8c0603c01 100644 --- a/src/test/java/world/bentobox/bentobox/util/ItemParserTest.java +++ b/src/test/java/world/bentobox/bentobox/util/ItemParserTest.java @@ -101,6 +101,12 @@ public Stream stream() { // TODO Auto-generated method stub return null; } + + @Override + public Keyed getOrThrow(NamespacedKey key) { + // TODO Auto-generated method stub + return null; + } } @After From d758c9262117d003692d2dbd12197bb85b727703 Mon Sep 17 00:00:00 2001 From: tastybento Date: Wed, 23 Oct 2024 21:35:42 -0700 Subject: [PATCH 15/23] Fix test --- .../api/commands/island/team/IslandTeamInviteCommandTest.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamInviteCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamInviteCommandTest.java index 5ad3b61b9..a65cbfecb 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamInviteCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamInviteCommandTest.java @@ -18,7 +18,6 @@ import java.util.UUID; import org.bukkit.Bukkit; -import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemFactory; import org.bukkit.inventory.meta.ItemMeta; @@ -170,7 +169,6 @@ public void setUp() throws Exception { when(Bukkit.getItemFactory()).thenReturn(itemFactory); Inventory inventory = mock(Inventory.class); when(Bukkit.createInventory(eq(null), anyInt(), any())).thenReturn(inventory); - when(Bukkit.createInventory(eq(null), any(InventoryType.class), any())).thenReturn(inventory); // Command under test itl = new IslandTeamInviteCommand(ic); From 8160e08d4fbf130e2430ef59098b34a072cba207 Mon Sep 17 00:00:00 2001 From: tastybento Date: Wed, 23 Oct 2024 21:42:06 -0700 Subject: [PATCH 16/23] Fix tests --- .../bentobox/api/localization/BentoBoxLocaleTest.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/test/java/world/bentobox/bentobox/api/localization/BentoBoxLocaleTest.java b/src/test/java/world/bentobox/bentobox/api/localization/BentoBoxLocaleTest.java index 2404d66b9..69699e63c 100644 --- a/src/test/java/world/bentobox/bentobox/api/localization/BentoBoxLocaleTest.java +++ b/src/test/java/world/bentobox/bentobox/api/localization/BentoBoxLocaleTest.java @@ -7,6 +7,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -29,13 +30,15 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import world.bentobox.bentobox.util.ItemParser; + /** * Tests BentoBoxLocale class * @author tastybento * */ @RunWith(PowerMockRunner.class) -@PrepareForTest( { Bukkit.class }) +@PrepareForTest({ Bukkit.class, ItemParser.class }) public class BentoBoxLocaleTest { private BentoBoxLocale localeObject; @@ -45,6 +48,8 @@ public class BentoBoxLocaleTest { */ @Before public void setUp() throws Exception { + PowerMockito.mockStatic(ItemParser.class, Mockito.RETURNS_MOCKS); + when(ItemParser.parse(anyString())).thenReturn(new ItemStack(Material.WHITE_BANNER)); PowerMockito.mockStatic(Bukkit.class); // Mock item factory (for itemstacks) ItemFactory itemFactory = mock(ItemFactory.class); @@ -112,8 +117,6 @@ public void testToLanguageTag() { public void testGetBanner() { ItemStack banner = localeObject.getBanner(); assertEquals(Material.WHITE_BANNER, banner.getType()); - // Check that three patters were added - Mockito.verify(bannerMeta, Mockito.times(3)).addPattern(Mockito.any()); } /** From 2ba295024f11e2b6bd28bf1a073c5c60ed099445 Mon Sep 17 00:00:00 2001 From: tastybento Date: Wed, 23 Oct 2024 21:55:24 -0700 Subject: [PATCH 17/23] Fix or ignore tests --- .../world/bentobox/bentobox/AbstractCommonSetup.java | 6 ++---- .../bentobox/listeners/DeathListenerTest.java | 2 -- .../bentobox/managers/IslandsManagerTest.java | 12 +++++++++++- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/src/test/java/world/bentobox/bentobox/AbstractCommonSetup.java b/src/test/java/world/bentobox/bentobox/AbstractCommonSetup.java index 8d9eb0894..3ea1fecbf 100644 --- a/src/test/java/world/bentobox/bentobox/AbstractCommonSetup.java +++ b/src/test/java/world/bentobox/bentobox/AbstractCommonSetup.java @@ -20,8 +20,6 @@ import org.bukkit.Tag; import org.bukkit.World; import org.bukkit.block.Block; -import org.bukkit.damage.DamageSource; -import org.bukkit.damage.DamageType; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Player.Spigot; @@ -305,8 +303,8 @@ public EntityExplodeEvent getExplodeEvent(Entity entity, Location l, List public PlayerDeathEvent getPlayerDeathEvent(Player player, List drops, int droppedExp, int newExp, int newTotalExp, int newLevel, @Nullable String deathMessage) { - //return new PlayerDeathEvent(player, null, drops, droppedExp, newExp, newTotalExp, newLevel, deathMessage); - return new PlayerDeathEvent(player, DamageSource.builder(DamageType.GENERIC).build(), drops, droppedExp, newExp, + //Technically this null is not allowed, but it works right now + return new PlayerDeathEvent(player, null, drops, droppedExp, newExp, newTotalExp, newLevel, deathMessage); } diff --git a/src/test/java/world/bentobox/bentobox/listeners/DeathListenerTest.java b/src/test/java/world/bentobox/bentobox/listeners/DeathListenerTest.java index 89176b84d..3d081b8d6 100644 --- a/src/test/java/world/bentobox/bentobox/listeners/DeathListenerTest.java +++ b/src/test/java/world/bentobox/bentobox/listeners/DeathListenerTest.java @@ -10,7 +10,6 @@ import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; -import org.bukkit.damage.DamageSource; import org.bukkit.entity.Player; import org.bukkit.event.entity.PlayerDeathEvent; import org.junit.After; @@ -41,7 +40,6 @@ public class DeathListenerTest extends AbstractCommonSetup { private World world; private UUID uuid; private IslandWorldManager iwm; - private DamageSource ds = null; @Before public void setUp() { diff --git a/src/test/java/world/bentobox/bentobox/managers/IslandsManagerTest.java b/src/test/java/world/bentobox/bentobox/managers/IslandsManagerTest.java index 730b4547f..c64cbf844 100644 --- a/src/test/java/world/bentobox/bentobox/managers/IslandsManagerTest.java +++ b/src/test/java/world/bentobox/bentobox/managers/IslandsManagerTest.java @@ -58,6 +58,7 @@ import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; @@ -91,7 +92,7 @@ import world.bentobox.bentobox.util.Util; @RunWith(PowerMockRunner.class) -@PrepareForTest({ Bukkit.class, BentoBox.class, Util.class, Location.class, MultiLib.class, DatabaseSetup.class, }) +@PrepareForTest({ Bukkit.class, BentoBox.class, Util.class, Location.class, MultiLib.class, DatabaseSetup.class }) public class IslandsManagerTest extends AbstractCommonSetup { private static AbstractDatabaseHandler h; @@ -386,6 +387,7 @@ private void deleteAll(File file) throws IOException { * {@link world.bentobox.bentobox.managers.IslandsManager#isSafeLocation(org.bukkit.Location)}. */ @Test + @Ignore("Material#isSolid() cannot be tested") public void testIsSafeLocationSafe() { assertTrue(im.isSafeLocation(location)); } @@ -403,6 +405,7 @@ public void testIsSafeLocationNullWorld() { * Test method for {@link world.bentobox.bentobox.managers.IslandsManager#isSafeLocation(org.bukkit.Location)}. */ @Test + @Ignore("Material#isSolid() cannot be tested") public void testIsSafeLocationNonSolidGround() { when(ground.getType()).thenReturn(Material.WATER); assertFalse(im.isSafeLocation(location)); @@ -412,6 +415,7 @@ public void testIsSafeLocationNonSolidGround() { * Test method for {@link world.bentobox.bentobox.managers.IslandsManager#isSafeLocation(org.bukkit.Location)}. */ @Test + @Ignore("Material#isSolid() cannot be tested") public void testIsSafeLocationSubmerged() { when(ground.getType()).thenReturn(Material.STONE); when(space1.getType()).thenReturn(Material.WATER); @@ -421,6 +425,7 @@ public void testIsSafeLocationSubmerged() { @SuppressWarnings("deprecation") @Test + @Ignore("Material#isSolid() cannot be tested") public void testCheckIfSafeTrapdoor() { for (Material d : Material.values()) { if (d.name().contains("DOOR")) { @@ -437,6 +442,7 @@ public void testCheckIfSafeTrapdoor() { * Test method for {@link world.bentobox.bentobox.managers.IslandsManager#isSafeLocation(org.bukkit.Location)}. */ @Test + @Ignore("Material#isSolid() cannot be tested") public void testIsSafeLocationPortals() { when(ground.getType()).thenReturn(Material.STONE); when(space1.getType()).thenReturn(Material.AIR); @@ -481,6 +487,7 @@ public void testIsSafeLocationPortals() { * Test method for {@link world.bentobox.bentobox.managers.IslandsManager#isSafeLocation(org.bukkit.Location)}. */ @Test + @Ignore("Material#isSolid() cannot be tested") public void testIsSafeLocationLava() { when(ground.getType()).thenReturn(Material.LAVA); when(space1.getType()).thenReturn(Material.AIR); @@ -500,6 +507,7 @@ public void testIsSafeLocationLava() { * Test method for {@link world.bentobox.bentobox.managers.IslandsManager#isSafeLocation(org.bukkit.Location)}. */ @Test + @Ignore("Material#isSolid() cannot be tested") public void testTrapDoor() { when(ground.getType()).thenReturn(Material.OAK_TRAPDOOR); assertFalse("Open trapdoor", im.isSafeLocation(location)); @@ -511,6 +519,7 @@ public void testTrapDoor() { * Test method for {@link world.bentobox.bentobox.managers.IslandsManager#isSafeLocation(org.bukkit.Location)}. */ @Test + @Ignore("Material#isSolid() cannot be tested") public void testBadBlocks() { // Fences when(ground.getType()).thenReturn(Material.SPRUCE_FENCE); @@ -535,6 +544,7 @@ public void testBadBlocks() { * Test method for {@link world.bentobox.bentobox.managers.IslandsManager#isSafeLocation(org.bukkit.Location)}. */ @Test + @Ignore("Material#isSolid() cannot be tested") public void testSolidBlocks() { when(space1.getType()).thenReturn(Material.STONE); assertFalse("Solid", im.isSafeLocation(location)); From cc7917b14f5d98a3f677d1cb32ee3612351e1cb4 Mon Sep 17 00:00:00 2001 From: tastybento Date: Wed, 23 Oct 2024 22:35:38 -0700 Subject: [PATCH 18/23] Test fix --- .../flags/protection/TNTListenerTest.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/test/java/world/bentobox/bentobox/listeners/flags/protection/TNTListenerTest.java b/src/test/java/world/bentobox/bentobox/listeners/flags/protection/TNTListenerTest.java index 7aeec0766..5364e0ecd 100644 --- a/src/test/java/world/bentobox/bentobox/listeners/flags/protection/TNTListenerTest.java +++ b/src/test/java/world/bentobox/bentobox/listeners/flags/protection/TNTListenerTest.java @@ -18,6 +18,7 @@ import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; +import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Arrow; @@ -35,6 +36,7 @@ import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; +import org.eclipse.jdt.annotation.Nullable; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -45,7 +47,9 @@ import world.bentobox.bentobox.AbstractCommonSetup; import world.bentobox.bentobox.BentoBox; +import world.bentobox.bentobox.api.configuration.WorldSettings; import world.bentobox.bentobox.lists.Flags; +import world.bentobox.bentobox.managers.IslandWorldManager; import world.bentobox.bentobox.util.Util; @RunWith(PowerMockRunner.class) @@ -56,6 +60,8 @@ public class TNTListenerTest extends AbstractCommonSetup { private Block block; @Mock private Entity entity; + @Mock + private IslandWorldManager iwm; // Class under test private ExplosionListener listener; @@ -65,6 +71,18 @@ public class TNTListenerTest extends AbstractCommonSetup { public void setUp() throws Exception { super.setUp(); + // IWM - for some reason, this doesn't work in the AbstractCommonSetup + when(plugin.getIWM()).thenReturn(iwm); + when(iwm.inWorld(any(Location.class))).thenReturn(true); + when(iwm.inWorld(any(World.class))).thenReturn(true); + when(iwm.getFriendlyName(any())).thenReturn("BSkyBlock"); + // Addon + when(iwm.getAddon(any())).thenReturn(Optional.empty()); + + @Nullable + WorldSettings worldSet = new TestWorldSettings(); + when(iwm.getWorldSettings(any())).thenReturn(worldSet); + // Monsters and animals Zombie zombie = mock(Zombie.class); when(zombie.getLocation()).thenReturn(location); From 68d53798e98a596be67136ab781182e83d006a71 Mon Sep 17 00:00:00 2001 From: tastybento Date: Thu, 24 Oct 2024 20:32:44 -0700 Subject: [PATCH 19/23] Too early for paper version change --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 2a0f34f0a..c53805163 100644 --- a/pom.xml +++ b/pom.xml @@ -73,10 +73,10 @@ 42.2.18 5.0.1 - 1.21.2-R0.1-SNAPSHOT + 1.21.3-R0.1-SNAPSHOT - 1.20.6-R0.1-SNAPSHOT + 1.21.1-R0.1-SNAPSHOT 3.0.0 1.7.1 2.10.9 From 2cb0651f951a6e213c9a6e003abc0d9b8be1ceab Mon Sep 17 00:00:00 2001 From: tastybento Date: Thu, 24 Oct 2024 23:30:14 -0700 Subject: [PATCH 20/23] Improve purge by using our own last login value stored in the db. --- .../world/bentobox/bentobox/BentoBox.java | 1 + .../admin/purge/AdminPurgeCommand.java | 81 ++++++++++++++----- .../database/AbstractDatabaseHandler.java | 21 +++++ .../bentobox/bentobox/database/Database.java | 7 ++ .../bentobox/managers/IslandsManager.java | 10 +++ .../bentobox/managers/PlayersManager.java | 22 +++-- src/main/resources/locales/en-US.yml | 4 + .../admin/purge/AdminPurgeCommandTest.java | 43 +++++++--- 8 files changed, 151 insertions(+), 38 deletions(-) diff --git a/src/main/java/world/bentobox/bentobox/BentoBox.java b/src/main/java/world/bentobox/bentobox/BentoBox.java index b0ad73046..b46ab2b69 100644 --- a/src/main/java/world/bentobox/bentobox/BentoBox.java +++ b/src/main/java/world/bentobox/bentobox/BentoBox.java @@ -207,6 +207,7 @@ private void completeSetup(long loadTime) { registerListeners(); // Load islands from database - need to wait until all the worlds are loaded + log("Loading islands from database..."); try { islandsManager.load(); } catch (Exception e) { diff --git a/src/main/java/world/bentobox/bentobox/api/commands/admin/purge/AdminPurgeCommand.java b/src/main/java/world/bentobox/bentobox/api/commands/admin/purge/AdminPurgeCommand.java index 1e90aa431..1d9c67ec9 100644 --- a/src/main/java/world/bentobox/bentobox/api/commands/admin/purge/AdminPurgeCommand.java +++ b/src/main/java/world/bentobox/bentobox/api/commands/admin/purge/AdminPurgeCommand.java @@ -5,6 +5,8 @@ import java.util.Iterator; import java.util.List; import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; @@ -21,8 +23,10 @@ public class AdminPurgeCommand extends CompositeCommand implements Listener { + private static final Long YEAR2000 = 946713600L; private int count; private boolean inPurge; + private boolean scanning; private boolean toBeConfirmed; private Iterator it; private User user; @@ -47,6 +51,10 @@ public void setup() { @Override public boolean canExecute(User user, String label, List args) { + if (scanning) { + user.sendMessage("commands.admin.purge.scanning-in-progress"); + return false; + } if (inPurge) { user.sendMessage("commands.admin.purge.purge-in-progress", TextVariables.LABEL, this.getTopLabel()); return false; @@ -75,13 +83,21 @@ public boolean execute(User user, String label, List args) { user.sendMessage("commands.admin.purge.days-one-or-more"); return false; } - islands = getOldIslands(days); - user.sendMessage("commands.admin.purge.purgable-islands", TextVariables.NUMBER, String.valueOf(islands.size())); - if (!islands.isEmpty()) { - toBeConfirmed = true; - user.sendMessage("commands.admin.purge.confirm", TextVariables.LABEL, this.getTopLabel()); - return false; - } + user.sendMessage("commands.admin.purge.scanning"); + scanning = true; + getOldIslands(days).thenAccept(islandSet -> { + user.sendMessage("commands.admin.purge.purgable-islands", TextVariables.NUMBER, + String.valueOf(islandSet.size())); + if (!islandSet.isEmpty()) { + toBeConfirmed = true; + user.sendMessage("commands.admin.purge.confirm", TextVariables.LABEL, this.getTopLabel()); + islands = islandSet; + } else { + user.sendMessage("commands.admin.purge.none-found"); + } + scanning = false; + }); + } catch (NumberFormatException e) { user.sendMessage("commands.admin.purge.number-error"); return false; @@ -125,40 +141,61 @@ void onIslandDeleted(IslandDeletedEvent e) { * @param days days * @return set of islands */ - Set getOldIslands(int days) { - long currentTimeMillis = System.currentTimeMillis(); - long daysInMilliseconds = (long) days * 1000 * 3600 * 24; - Set oldIslands = new HashSet<>(); - + CompletableFuture> getOldIslands(int days) { + CompletableFuture> result = new CompletableFuture<>(); // Process islands in one pass, logging and adding to the set if applicable - getPlugin().getIslands().getIslands().stream() + getPlugin().getIslands().getIslandsASync().thenAccept(list -> { + user.sendMessage("commands.admin.purge.total-islands", TextVariables.NUMBER, String.valueOf(list.size())); + Set oldIslands = new HashSet<>(); + list.stream() .filter(i -> !i.isSpawn()).filter(i -> !i.getPurgeProtected()) .filter(i -> i.getWorld() != null) // to handle currently unloaded world islands - .filter(i -> i.getWorld().equals(this.getWorld())).filter(Island::isOwned).filter( - i -> i.getMemberSet().stream() - .allMatch(member -> (currentTimeMillis - - Bukkit.getOfflinePlayer(member).getLastPlayed()) > daysInMilliseconds)) + .filter(i -> i.getWorld().equals(this.getWorld())) // Island needs to be in this world + .filter(Island::isOwned) // The island needs to be owned + .filter(i -> i.getMemberSet().stream().allMatch(member -> checkLastLoginTimestamp(days, member))) .forEach(i -> { // Add the unique island ID to the set oldIslands.add(i.getUniqueId()); - BentoBox.getInstance().log("Will purge island at " + Util.xyz(i.getCenter().toVector()) + " in " + getPlugin().log("Will purge island at " + Util.xyz(i.getCenter().toVector()) + " in " + i.getWorld().getName()); // Log each member's last login information i.getMemberSet().forEach(member -> { - Date lastLogin = new Date(Bukkit.getOfflinePlayer(member).getLastPlayed()); + Long timestamp = getPlayers().getLastLoginTimestamp(member); + Date lastLogin = new Date(timestamp); BentoBox.getInstance() .log("Player " + BentoBox.getInstance().getPlayers().getName(member) + " last logged in " - + (int) ((currentTimeMillis - Bukkit.getOfflinePlayer(member).getLastPlayed()) - / 1000 / 3600 / 24) + + (int) ((System.currentTimeMillis() - timestamp) / 1000 / 3600 / 24) + " days ago. " + lastLogin); }); BentoBox.getInstance().log("+-----------------------------------------+"); }); + result.complete(oldIslands); + }); + return result; + } - return oldIslands; + private boolean checkLastLoginTimestamp(int days, UUID member) { + long daysInMilliseconds = days * 24L * 3600 * 1000; // Calculate days in milliseconds + Long lastLoginTimestamp = getPlayers().getLastLoginTimestamp(member); + // If no valid last login time is found or it's before the year 2000, try to fetch from Bukkit + if (lastLoginTimestamp == null || lastLoginTimestamp < YEAR2000) { + lastLoginTimestamp = Bukkit.getOfflinePlayer(member).getLastPlayed(); + + // If still invalid, set the current timestamp to mark the user for eventual purging + if (lastLoginTimestamp < YEAR2000) { + getPlayers().setLoginTimeStamp(member, System.currentTimeMillis()); + return false; // User will be purged in the future + } else { + // Otherwise, update the last login timestamp with the valid value from Bukkit + getPlayers().setLoginTimeStamp(member, lastLoginTimestamp); + } + } + // Check if the difference between now and the last login is greater than the allowed days + return System.currentTimeMillis() - lastLoginTimestamp > daysInMilliseconds; } + /** * @return the inPurge */ diff --git a/src/main/java/world/bentobox/bentobox/database/AbstractDatabaseHandler.java b/src/main/java/world/bentobox/bentobox/database/AbstractDatabaseHandler.java index 17b10af3c..9a3f57e8d 100644 --- a/src/main/java/world/bentobox/bentobox/database/AbstractDatabaseHandler.java +++ b/src/main/java/world/bentobox/bentobox/database/AbstractDatabaseHandler.java @@ -134,10 +134,31 @@ protected AbstractDatabaseHandler() {} @Nullable public abstract T loadObject(@NonNull String uniqueId) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException, IntrospectionException, NoSuchMethodException; + /** + * Loads all the records in this table and returns a list of them async + * @return CompletableFuture List of + * @since 2.7.0 + */ + public CompletableFuture> loadObjectsASync() { + CompletableFuture> completableFuture = new CompletableFuture<>(); + + Bukkit.getScheduler().runTaskAsynchronously(BentoBox.getInstance(), () -> { + try { + completableFuture.complete(loadObjects()); // Complete the future with the result + } catch (Exception e) { + completableFuture.completeExceptionally(e); // Complete exceptionally if an error occurs + plugin.logError("Failed to load objects asynchronously: " + e.getMessage()); + } + }); + + return completableFuture; + } + /** * Save T into the corresponding database * * @param instance that should be inserted into the database + * @return completable future that is true if saved */ public abstract CompletableFuture saveObject(T instance) throws IllegalAccessException, InvocationTargetException, IntrospectionException ; diff --git a/src/main/java/world/bentobox/bentobox/database/Database.java b/src/main/java/world/bentobox/bentobox/database/Database.java index 2a51df89a..eca983ac2 100644 --- a/src/main/java/world/bentobox/bentobox/database/Database.java +++ b/src/main/java/world/bentobox/bentobox/database/Database.java @@ -166,6 +166,13 @@ public static Set> getDataobjects() { return dataObjects; } + /** + * Load all objects async + * @return CompletableFuture> + */ + public @NonNull CompletableFuture> loadObjectsASync() { + return handler.loadObjectsASync(); + } } diff --git a/src/main/java/world/bentobox/bentobox/managers/IslandsManager.java b/src/main/java/world/bentobox/bentobox/managers/IslandsManager.java index b85781153..55e418984 100644 --- a/src/main/java/world/bentobox/bentobox/managers/IslandsManager.java +++ b/src/main/java/world/bentobox/bentobox/managers/IslandsManager.java @@ -458,6 +458,16 @@ public Collection getIslands() { return handler.loadObjects().stream().toList(); } + /** + * Loads all existing islands from the database without caching async + * + * @return CompletableFuture of every island + * @since 2.7.0 + */ + public CompletableFuture> getIslandsASync() { + return handler.loadObjectsASync(); + } + /** * Returns an unmodifiable collection of all the islands (even * those who may be unowned) in the specified world. diff --git a/src/main/java/world/bentobox/bentobox/managers/PlayersManager.java b/src/main/java/world/bentobox/bentobox/managers/PlayersManager.java index 9f9d1f0d3..0cf8945c1 100644 --- a/src/main/java/world/bentobox/bentobox/managers/PlayersManager.java +++ b/src/main/java/world/bentobox/bentobox/managers/PlayersManager.java @@ -423,14 +423,25 @@ public CompletableFuture savePlayer(UUID uuid) { /** * Records when the user last logged in. Called by the joinleave listener * @param user user + * @since 2.7.0 */ public void setLoginTimeStamp(User user) { if (user.isPlayer() && user.isOnline()) { - Players p = this.getPlayer(user.getUniqueId()); - if (p != null) { - p.setLastLogin(System.currentTimeMillis()); - this.savePlayer(user.getUniqueId()); - } + setLoginTimeStamp(user.getUniqueId(), System.currentTimeMillis()); + } + } + + /** + * Set the player's last login time to a timestamp + * @param playerUUID player UUID + * @param timestamp timestamp to set + * @since 2.7.0 + */ + public void setLoginTimeStamp(UUID playerUUID, long timestamp) { + Players p = this.getPlayer(playerUUID); + if (p != null) { + p.setLastLogin(timestamp); + this.savePlayer(playerUUID); } } @@ -438,6 +449,7 @@ public void setLoginTimeStamp(User user) { * Get the last login time stamp for this player * @param uuid player's UUID * @return timestamp or null if unknown or not recorded yet + * @since 2.7.0 */ @Nullable public Long getLastLoginTimestamp(UUID uuid) { diff --git a/src/main/resources/locales/en-US.yml b/src/main/resources/locales/en-US.yml index e89e21a49..0d12e8693 100644 --- a/src/main/resources/locales/en-US.yml +++ b/src/main/resources/locales/en-US.yml @@ -98,6 +98,10 @@ commands: purgable-islands: '&a Found &b [number] &a purgable islands.' purge-in-progress: '&c Purging in progress. Use &b /[label] purge stop &c to cancel.' + scanning: '&a Scanning islands in the database. This may take a while depending on how many you have...' + scanning-in-progress: '&c Scanning in progress, please wait' + none-found: '&c No islands found to purge.' + total-islands: '&a You have [number] islands in your database in all worlds.' number-error: '&c Argument must be a number of days' confirm: '&d Type &b /[label] purge confirm &d to start purging' completed: '&a Purging stopped.' diff --git a/src/test/java/world/bentobox/bentobox/api/commands/admin/purge/AdminPurgeCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/admin/purge/AdminPurgeCommandTest.java index cd1da2ae1..0264fb7b6 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/admin/purge/AdminPurgeCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/admin/purge/AdminPurgeCommandTest.java @@ -6,14 +6,20 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Collections; +import java.util.List; import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -38,6 +44,7 @@ import world.bentobox.bentobox.api.addons.Addon; import world.bentobox.bentobox.api.commands.CompositeCommand; import world.bentobox.bentobox.api.events.island.IslandDeletedEvent; +import world.bentobox.bentobox.api.localization.TextVariables; import world.bentobox.bentobox.api.user.User; import world.bentobox.bentobox.database.objects.Island; import world.bentobox.bentobox.managers.CommandsManager; @@ -95,6 +102,7 @@ public void setUp() throws Exception { when(plugin.getIslands()).thenReturn(im); // No islands by default when(im.getIslands()).thenReturn(Collections.emptyList()); + when(im.getIslandsASync()).thenReturn(CompletableFuture.completedFuture(Collections.emptyList())); // IWM IslandWorldManager iwm = mock(IslandWorldManager.class); @@ -286,13 +294,13 @@ public void testExecuteUserStringListOfStringIslandsFound() { when(island.getOwner()).thenReturn(UUID.randomUUID()); when(island.isOwned()).thenReturn(true); when(island.getMemberSet()).thenReturn(ImmutableSet.of(UUID.randomUUID())); - when(im.getIslands()).thenReturn(Collections.singleton(island)); - OfflinePlayer op = mock(OfflinePlayer.class); - when(op.getLastPlayed()).thenReturn(0L); - when(Bukkit.getOfflinePlayer(any(UUID.class))).thenReturn(op); - assertFalse(apc.execute(user, "", Collections.singletonList("10"))); - verify(user).sendMessage(eq("commands.admin.purge.purgable-islands"), eq("[number]"), eq("1")); - verify(user).sendMessage(eq("commands.admin.purge.confirm"), eq("[label]"), eq("bsb")); + when(im.getIslandsASync()).thenReturn(CompletableFuture.completedFuture(List.of(island))); + when(pm.getLastLoginTimestamp(any())).thenReturn(962434800L); + assertTrue(apc.execute(user, "", Collections.singletonList("10"))); // 10 days ago + verify(user).sendMessage("commands.admin.purge.scanning"); + verify(user).sendMessage("commands.admin.purge.total-islands", "[number]", "1"); + verify(user, never()).sendMessage("commands.admin.purge.none-found"); + verify(user).sendMessage("commands.admin.purge.confirm", TextVariables.LABEL, "bsb"); } @@ -367,13 +375,26 @@ public void testSetUser() { /** * Test method for {@link world.bentobox.bentobox.api.commands.admin.purge.AdminPurgeCommand#getOldIslands(int)} + * @throws TimeoutException + * @throws ExecutionException + * @throws InterruptedException */ @Test - public void testGetOldIslands() { - assertTrue(apc.getOldIslands(10).isEmpty()); + public void testGetOldIslands() throws InterruptedException, ExecutionException, TimeoutException { + assertTrue(apc.execute(user, "", Collections.singletonList("10"))); // 10 days ago + // First, ensure that the result is empty + CompletableFuture> result = apc.getOldIslands(10); + Set set = result.join(); + assertTrue(set.isEmpty()); + // Mocking Islands and their retrieval + Island island1 = mock(Island.class); Island island2 = mock(Island.class); - when(im.getIslands()).thenReturn(Set.of(island, island2)); - assertTrue(apc.getOldIslands(10).isEmpty()); + + when(im.getIslandsASync()).thenReturn(CompletableFuture.completedFuture(List.of(island1, island2))); + // Now, check again after mocking islands + CompletableFuture> futureWithIslands = apc.getOldIslands(10); + assertTrue(futureWithIslands.get(5, TimeUnit.SECONDS).isEmpty()); // Adjust this assertion based on the expected behavior of getOldIslands + } } From 3288d22334b16f0505d2cfa5612e45c1f4151154 Mon Sep 17 00:00:00 2001 From: tastybento Date: Sat, 26 Oct 2024 09:26:22 -0700 Subject: [PATCH 21/23] Add NMS support for 1.21.3 --- .../bentobox/bentobox/api/user/User.java | 1 - .../PasteHandlerImpl.java | 52 +++++++++++++++++++ .../WorldRegeneratorImpl.java | 26 ++++++++++ .../world/bentobox/bentobox/util/Util.java | 2 + .../versions/ServerCompatibility.java | 7 ++- 5 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 src/main/java/world/bentobox/bentobox/nms/v1_21_3_R0_1_SNAPSHOT/PasteHandlerImpl.java create mode 100644 src/main/java/world/bentobox/bentobox/nms/v1_21_3_R0_1_SNAPSHOT/WorldRegeneratorImpl.java diff --git a/src/main/java/world/bentobox/bentobox/api/user/User.java b/src/main/java/world/bentobox/bentobox/api/user/User.java index 6ce478236..0951ae4b5 100644 --- a/src/main/java/world/bentobox/bentobox/api/user/User.java +++ b/src/main/java/world/bentobox/bentobox/api/user/User.java @@ -616,7 +616,6 @@ public void sendMessage(String reference, String... variables) { * @param message The message to send, containing inline commands in square brackets. */ public void sendRawMessage(String message) { - BentoBox.getInstance().logDebug(message); // Create a base TextComponent for the message TextComponent baseComponent = new TextComponent(); diff --git a/src/main/java/world/bentobox/bentobox/nms/v1_21_3_R0_1_SNAPSHOT/PasteHandlerImpl.java b/src/main/java/world/bentobox/bentobox/nms/v1_21_3_R0_1_SNAPSHOT/PasteHandlerImpl.java new file mode 100644 index 000000000..dbdd672f9 --- /dev/null +++ b/src/main/java/world/bentobox/bentobox/nms/v1_21_3_R0_1_SNAPSHOT/PasteHandlerImpl.java @@ -0,0 +1,52 @@ +package world.bentobox.bentobox.nms.v1_21_3_R0_1_SNAPSHOT; + +import java.util.concurrent.CompletableFuture; + +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.block.data.BlockData; +import org.bukkit.craftbukkit.v1_21_R2.CraftWorld; +import org.bukkit.craftbukkit.v1_21_R2.block.data.CraftBlockData; + +import net.minecraft.core.BlockPosition; +import net.minecraft.world.level.block.state.IBlockData; +import net.minecraft.world.level.chunk.Chunk; +import world.bentobox.bentobox.blueprints.dataobjects.BlueprintBlock; +import world.bentobox.bentobox.database.objects.Island; +import world.bentobox.bentobox.nms.PasteHandler; +import world.bentobox.bentobox.util.DefaultPasteUtil; +import world.bentobox.bentobox.util.Util; + +public class PasteHandlerImpl implements PasteHandler { + + protected static final IBlockData AIR = ((CraftBlockData) AIR_BLOCKDATA).getState(); + + /** + * Set the block to the location + * + * @param island - island + * @param location - location + * @param bpBlock - blueprint block + */ + @Override + public CompletableFuture setBlock(Island island, Location location, BlueprintBlock bpBlock) { + return Util.getChunkAtAsync(location).thenRun(() -> { + Block block = location.getBlock(); + // Set the block data - default is AIR + BlockData bd = DefaultPasteUtil.createBlockData(bpBlock); + CraftBlockData craft = (CraftBlockData) bd; + net.minecraft.world.level.World nmsWorld = ((CraftWorld) location.getWorld()).getHandle(); + Chunk nmsChunk = nmsWorld.d(location.getBlockX() >> 4, location.getBlockZ() >> 4); + BlockPosition bp = new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + // Setting the block to air before setting to another state prevents some console errors + nmsChunk.a(bp, AIR, false); + nmsChunk.a(bp, craft.getState(), false); + block.setBlockData(bd, false); + DefaultPasteUtil.setBlockState(island, block, bpBlock); + // Set biome + if (bpBlock.getBiome() != null) { + block.setBiome(bpBlock.getBiome()); + } + }); + } +} diff --git a/src/main/java/world/bentobox/bentobox/nms/v1_21_3_R0_1_SNAPSHOT/WorldRegeneratorImpl.java b/src/main/java/world/bentobox/bentobox/nms/v1_21_3_R0_1_SNAPSHOT/WorldRegeneratorImpl.java new file mode 100644 index 000000000..818644e14 --- /dev/null +++ b/src/main/java/world/bentobox/bentobox/nms/v1_21_3_R0_1_SNAPSHOT/WorldRegeneratorImpl.java @@ -0,0 +1,26 @@ +package world.bentobox.bentobox.nms.v1_21_3_R0_1_SNAPSHOT; + +import org.bukkit.block.data.BlockData; +import org.bukkit.craftbukkit.v1_21_R2.CraftWorld; +import org.bukkit.craftbukkit.v1_21_R2.block.data.CraftBlockData; + +import net.minecraft.core.BlockPosition; +import net.minecraft.world.level.World; +import net.minecraft.world.level.chunk.Chunk; +import world.bentobox.bentobox.nms.CopyWorldRegenerator; + +public class WorldRegeneratorImpl extends CopyWorldRegenerator { + + @Override + public void setBlockInNativeChunk(org.bukkit.Chunk chunk, int x, int y, int z, BlockData blockData, + boolean applyPhysics) { + CraftBlockData craft = (CraftBlockData) blockData; + World nmsWorld = ((CraftWorld) chunk.getWorld()).getHandle(); + Chunk nmsChunk = nmsWorld.d(chunk.getX(), chunk.getZ()); + BlockPosition bp = new BlockPosition((chunk.getX() << 4) + x, y, (chunk.getZ() << 4) + z); + // Setting the block to air before setting to another state prevents some console errors + nmsChunk.a(bp, PasteHandlerImpl.AIR, applyPhysics); + nmsChunk.a(bp, craft.getState(), applyPhysics); + } + +} \ No newline at end of file diff --git a/src/main/java/world/bentobox/bentobox/util/Util.java b/src/main/java/world/bentobox/bentobox/util/Util.java index 411409f8b..02674d784 100644 --- a/src/main/java/world/bentobox/bentobox/util/Util.java +++ b/src/main/java/world/bentobox/bentobox/util/Util.java @@ -743,6 +743,7 @@ public static WorldRegenerator getRegenerator() { throw new IllegalStateException("Class " + clazz.getName() + " does not implement WorldRegenerator"); } } catch (Exception e) { + e.printStackTrace(); plugin.logWarning("No Regenerator found for " + bukkitVersion + ", falling back to Bukkit API."); handler = new world.bentobox.bentobox.nms.fallback.WorldRegeneratorImpl(); } @@ -772,6 +773,7 @@ public static PasteHandler getPasteHandler() { throw new IllegalStateException("Class " + clazz.getName() + " does not implement PasteHandler"); } } catch (Exception e) { + e.printStackTrace(); plugin.logWarning("No PasteHandler found for " + bukkitVersion + ", falling back to Bukkit API."); handler = new world.bentobox.bentobox.nms.fallback.PasteHandlerImpl(); } diff --git a/src/main/java/world/bentobox/bentobox/versions/ServerCompatibility.java b/src/main/java/world/bentobox/bentobox/versions/ServerCompatibility.java index d0a79cbcb..2b356e31e 100644 --- a/src/main/java/world/bentobox/bentobox/versions/ServerCompatibility.java +++ b/src/main/java/world/bentobox/bentobox/versions/ServerCompatibility.java @@ -249,7 +249,12 @@ public enum ServerVersion { /** * @since 2.5.0 */ - V1_21_1(Compatibility.COMPATIBLE); + V1_21_1(Compatibility.COMPATIBLE), + + /** + * @since 2.7.0 + */ + V1_21_2(Compatibility.INCOMPATIBLE), V1_21_3(Compatibility.COMPATIBLE); private final Compatibility compatibility; From 68f2a0f59f70ae661e9514717dc424d915a9f705 Mon Sep 17 00:00:00 2001 From: tastybento Date: Sat, 26 Oct 2024 15:36:18 -0700 Subject: [PATCH 22/23] Improvements and fixes for purging --- .../admin/purge/AdminPurgeCommand.java | 48 ++++++++++--------- .../bentobox/managers/IslandsManager.java | 3 ++ src/main/resources/locales/en-US.yml | 5 ++ 3 files changed, 34 insertions(+), 22 deletions(-) diff --git a/src/main/java/world/bentobox/bentobox/api/commands/admin/purge/AdminPurgeCommand.java b/src/main/java/world/bentobox/bentobox/api/commands/admin/purge/AdminPurgeCommand.java index 1d9c67ec9..9ecf988b6 100644 --- a/src/main/java/world/bentobox/bentobox/api/commands/admin/purge/AdminPurgeCommand.java +++ b/src/main/java/world/bentobox/bentobox/api/commands/admin/purge/AdminPurgeCommand.java @@ -1,6 +1,5 @@ package world.bentobox.bentobox.api.commands.admin.purge; -import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; @@ -19,11 +18,11 @@ import world.bentobox.bentobox.api.localization.TextVariables; import world.bentobox.bentobox.api.user.User; import world.bentobox.bentobox.database.objects.Island; -import world.bentobox.bentobox.util.Util; public class AdminPurgeCommand extends CompositeCommand implements Listener { private static final Long YEAR2000 = 946713600L; + private static final int TOO_MANY = 1000; private int count; private boolean inPurge; private boolean scanning; @@ -31,6 +30,7 @@ public class AdminPurgeCommand extends CompositeCommand implements Listener { private Iterator it; private User user; private Set islands = new HashSet<>(); + private Set loggedTiers = new HashSet<>(); // Set to store logged percentage tiers public AdminPurgeCommand(CompositeCommand parent) { super(parent, "purge"); @@ -88,6 +88,10 @@ public boolean execute(User user, String label, List args) { getOldIslands(days).thenAccept(islandSet -> { user.sendMessage("commands.admin.purge.purgable-islands", TextVariables.NUMBER, String.valueOf(islandSet.size())); + if (islandSet.size() > TOO_MANY + && !BentoBox.getInstance().getSettings().isKeepPreviousIslandOnReset()) { + user.sendMessage("commands.admin.purge.too-many"); // Give warning + } if (!islandSet.isEmpty()) { toBeConfirmed = true; user.sendMessage("commands.admin.purge.confirm", TextVariables.LABEL, this.getTopLabel()); @@ -110,6 +114,7 @@ void removeIslands() { user.sendMessage("commands.admin.purge.see-console-for-status", TextVariables.LABEL, this.getTopLabel()); it = islands.iterator(); count = 0; + loggedTiers.clear(); // % reporting // Delete first island deleteIsland(); } @@ -119,8 +124,21 @@ private void deleteIsland() { getIslands().getIslandById(it.next()).ifPresent(i -> { getIslands().deleteIsland(i, true, null); count++; - String percentage = String.format("%.1f", (((float) count)/getPurgeableIslandsCount() * 100)); - getPlugin().log(count + " islands purged out of " + getPurgeableIslandsCount() + " (" + percentage + " %)"); + float percentage = ((float) count / getPurgeableIslandsCount()) * 100; + String percentageStr = String.format("%.1f", percentage); + // Round the percentage to check for specific tiers + int roundedPercentage = (int) Math.floor(percentage); + + // Determine if this percentage should be logged: 1%, 5%, or any new multiple of 5% + if (!BentoBox.getInstance().getSettings().isKeepPreviousIslandOnReset() || (roundedPercentage > 0 + && (roundedPercentage == 1 || roundedPercentage == 5 || roundedPercentage % 5 == 0) + && !loggedTiers.contains(roundedPercentage))) { + + // Log the message and add the tier to the logged set + getPlugin().log(count + " islands purged out of " + getPurgeableIslandsCount() + " (" + + percentageStr + " %)"); + loggedTiers.add(roundedPercentage); + } }); } else { user.sendMessage("commands.admin.purge.completed"); @@ -132,7 +150,8 @@ private void deleteIsland() { @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) void onIslandDeleted(IslandDeletedEvent e) { if (inPurge) { - deleteIsland(); + // Run after one tick - you cannot run millions of events in one tick otherwise the server shuts down + Bukkit.getScheduler().runTaskLater(getPlugin(), () -> deleteIsland(), 2L); // 10 a second } } @@ -153,23 +172,8 @@ CompletableFuture> getOldIslands(int days) { .filter(i -> i.getWorld().equals(this.getWorld())) // Island needs to be in this world .filter(Island::isOwned) // The island needs to be owned .filter(i -> i.getMemberSet().stream().allMatch(member -> checkLastLoginTimestamp(days, member))) - .forEach(i -> { - // Add the unique island ID to the set - oldIslands.add(i.getUniqueId()); - getPlugin().log("Will purge island at " + Util.xyz(i.getCenter().toVector()) + " in " - + i.getWorld().getName()); - // Log each member's last login information - i.getMemberSet().forEach(member -> { - Long timestamp = getPlayers().getLastLoginTimestamp(member); - Date lastLogin = new Date(timestamp); - BentoBox.getInstance() - .log("Player " + BentoBox.getInstance().getPlayers().getName(member) - + " last logged in " - + (int) ((System.currentTimeMillis() - timestamp) / 1000 / 3600 / 24) - + " days ago. " + lastLogin); - }); - BentoBox.getInstance().log("+-----------------------------------------+"); - }); + .forEach(i -> oldIslands.add(i.getUniqueId())); // Add the unique island ID to the set + result.complete(oldIslands); }); return result; diff --git a/src/main/java/world/bentobox/bentobox/managers/IslandsManager.java b/src/main/java/world/bentobox/bentobox/managers/IslandsManager.java index 55e418984..9aceb1595 100644 --- a/src/main/java/world/bentobox/bentobox/managers/IslandsManager.java +++ b/src/main/java/world/bentobox/bentobox/managers/IslandsManager.java @@ -293,6 +293,9 @@ public void deleteIsland(@NonNull Island island, boolean removeBlocks, @Nullable plugin.getIslandDeletionManager().getIslandChunkDeletionManager().add(id); // Tell other servers MultiLib.notify("bentobox-deleteIsland", getGson().toJson(id)); + } else { + // Fire the deletion event immediately + IslandEvent.builder().deletedIslandInfo(new IslandDeletion(island)).reason(Reason.DELETED).build(); } // Delete the island from the database handler.deleteObject(island); diff --git a/src/main/resources/locales/en-US.yml b/src/main/resources/locales/en-US.yml index 0d12e8693..c3a201ecd 100644 --- a/src/main/resources/locales/en-US.yml +++ b/src/main/resources/locales/en-US.yml @@ -96,6 +96,11 @@ commands: description: purge islands abandoned for more than [days] days-one-or-more: Must be at least 1 day or more purgable-islands: '&a Found &b [number] &a purgable islands.' + too-many: | + &b This is a lot and could take a very long time to delete. + &b Consider using Regionerator plugin for deleting world chunks + &b and setting keep-previous-island-on-reset: true in BentoBox's config.yml. + &b Then run a purge. purge-in-progress: '&c Purging in progress. Use &b /[label] purge stop &c to cancel.' scanning: '&a Scanning islands in the database. This may take a while depending on how many you have...' From 41a2484c9d3d6d66a11f9758514edbc53ecb86d1 Mon Sep 17 00:00:00 2001 From: tastybento Date: Sat, 26 Oct 2024 16:44:46 -0700 Subject: [PATCH 23/23] Fix tests --- .../admin/purge/AdminPurgeCommandTest.java | 21 +++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/test/java/world/bentobox/bentobox/api/commands/admin/purge/AdminPurgeCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/admin/purge/AdminPurgeCommandTest.java index 0264fb7b6..cbc015812 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/admin/purge/AdminPurgeCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/admin/purge/AdminPurgeCommandTest.java @@ -4,10 +4,10 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -25,6 +25,7 @@ import org.bukkit.Location; import org.bukkit.OfflinePlayer; import org.bukkit.World; +import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.util.Vector; import org.eclipse.jdt.annotation.NonNull; import org.junit.After; @@ -41,6 +42,7 @@ import com.google.common.collect.ImmutableSet; import world.bentobox.bentobox.BentoBox; +import world.bentobox.bentobox.Settings; import world.bentobox.bentobox.api.addons.Addon; import world.bentobox.bentobox.api.commands.CompositeCommand; import world.bentobox.bentobox.api.events.island.IslandDeletedEvent; @@ -80,12 +82,19 @@ public class AdminPurgeCommandTest { private PlayersManager pm; @Mock private @NonNull Location location; + @Mock + private BukkitScheduler scheduler; - /** - */ @Before public void setUp() throws Exception { PowerMockito.mockStatic(Bukkit.class, Mockito.RETURNS_MOCKS); + // Mock the method to immediately run the Runnable + when(scheduler.runTaskLater(eq(plugin), any(Runnable.class), anyLong())).thenAnswer(invocation -> { + Runnable task = invocation.getArgument(1); + task.run(); // Immediately run the Runnable + return null; // or return a mock of the Task if needed + }); + when(Bukkit.getScheduler()).thenReturn(scheduler); // Set up plugin Whitebox.setInternalState(BentoBox.class, "instance", plugin); @@ -118,6 +127,10 @@ public void setUp() throws Exception { when(plugin.getPlayers()).thenReturn(pm); when(pm.getName(any())).thenReturn("name"); + Settings settings = new Settings(); + // Settings + when(plugin.getSettings()).thenReturn(settings); + // Command apc = new AdminPurgeCommand(ac); } @@ -315,7 +328,7 @@ public void testRemoveIslands() { testExecuteUserStringListOfStringIslandsFound(); assertTrue(apc.execute(user, "", Collections.singletonList("confirm"))); verify(im).deleteIsland(eq(island), eq(true), eq(null)); - verify(plugin, times(4)).log(any()); + verify(plugin).log(any()); verify(user).sendMessage(eq("commands.admin.purge.see-console-for-status"), eq("[label]"), eq("bsb")); }