warpGroups = source.stream().map(l -> (WarpGroup) l).toList();
- int slot = 0;
for (WarpGroup warpGroup : warpGroups) {
+ setClickEventForSlot(warpGroup);
+ }
+ }
- final int _slot = isPlusItem(warpGroup) ? getPlusSlot(slot) : getWarpGroupSlot(warpGroup, slot);
+ protected void setClickEventForSlot(@NotNull WarpGroup warpGroup) {
+ final int _slot = isPlusItem(warpGroup) ? plusSlot : getWarpGroupSlot(warpGroup);
- getMenu().getSlot(_slot).setClickHandler((clickPlayer, clickInformation) -> {
- clickPlayer.closeInventory();
+ getMenu().getSlot(_slot).setClickHandler((clickPlayer, clickInformation) -> {
+ clickPlayer.closeInventory();
- // Create a click action for the "Create Warp" item if the player has permission
- if(isPlusItem(warpGroup)){
- NavigationModule.getInstance().getWarpsComponent().createWarpGroup(clickPlayer);
- return;
- }
+ // Create a click action for the "Create Warp" item if the player has permission
+ if(isPlusItem(warpGroup)){
+ NavigationModule.getInstance().getWarpsComponent().createWarpGroup(clickPlayer);
+ return;
+ }
- if(clickInformation.getClickType().isRightClick() && clickPlayer.hasPermission(Permissions.WARP_GROUP_EDIT))
- new WarpGroupEditMenu(clickPlayer, warpGroup, true, true);
- else
- new WarpMenu(clickPlayer, warpGroup, true, true);
+ if(clickInformation.getClickType().isRightClick() && clickPlayer.hasPermission(Permissions.WARP_GROUP_EDIT))
+ new WarpGroupEditMenu(clickPlayer, warpGroup, true, true);
+ else
+ leftClickAction(clickPlayer, warpGroup);
+ });
+ }
- });
- slot++;
- }
+ protected void leftClickAction(Player clickPlayer, @NotNull WarpGroup warpGroup) {
+ new WarpMenu(clickPlayer, warpGroup, true, true);
}
- protected boolean isPlusItem(WarpGroup warpGroup){
+ protected boolean isPlusItem(@NotNull WarpGroup warpGroup){
return warpGroup.getName().equals("%create-warp-group%") && getMenuPlayer().hasPermission(Permissions.WARP_GROUP_CREATE);
}
- protected int getWarpGroupSlot(WarpGroup warpGroup, int currentIndex){
- int warpGroupSlot = currentIndex;
+ protected int getWarpGroupSlot(@NotNull WarpGroup g) {
+ int s = g.getSlot();
+ if (s >= 0 && s <= 26) return s;
+ int a = g.getInternalSlot();
+ return a >= 0 && a <= 26 ? a : -1;
+ }
- if(warpGroup.getSlot() != -1 && warpGroup.getSlot() > 0 && warpGroup.getSlot() < 27)
- warpGroupSlot = warpGroup.getSlot();
+ protected void setPlusSlot(int internalSlot, int freeSlot){
+ if(internalSlot >= 0) {
+ plusSlot = internalSlot;
+ return;
+ }
- return warpGroupSlot;
+ if(freeSlot < 0) return;
+ plusSlot = freeSlot;
}
- protected int getPlusSlot(int currentIndex){
- int warpGroupSlot = currentIndex;
+ /**
+ * Recalculates automatic slot assignments for the given warp groups.
+ *
+ * Preserves valid explicit slots (0..26). For groups with an invalid slot,
+ * assigns the first available slot in ascending order; if none remain, sets -1.
+ * Any group with a valid explicit slot has its internal auto slot cleared (-1).
+ *
+ * @param warpGroups groups to update
+ * @return The next free slot or -1 if it's outside the range
+ */
+ private static int recalculateAutoSlots(@NotNull List warpGroups) {
+ final int MAX = 27;
+
+ // 1) Calculate all free slots
+ ArrayDeque free = getFreeSlots(warpGroups, MAX);
+
+ // 2) Assign auto slots only where needed
+ for (WarpGroup g : warpGroups) {
+ int s = g.getSlot();
+ if (s >= 0 && s < MAX) {
+ g.setInternalSlot(-1); // explicit slot → clear auto
+ } else {
+ Integer next = free.pollFirst(); // next free, or null if none
+ g.setInternalSlot(next != null ? next : -1);
+ }
+ }
+
+ // 3) Return next free slot - mainly used for plus slot
+ Integer next = free.pollFirst(); // next free, or null if none
- for(WarpGroup warpGroup : buildTeam.getWarpGroups())
- if(warpGroup.getSlot() != -1 && warpGroup.getSlot() > 0 && warpGroup.getSlot() < 27)
- warpGroupSlot = ALTERNATE_PLUS_SLOT;
+ if (BuildTeamTools.getInstance().isDebug() && BuildTeamTools.getInstance().getComponentLogger().isInfoEnabled()) {
+ BuildTeamTools.getInstance().getComponentLogger().info("Free slot: {}.", free);
+ BuildTeamTools.getInstance().getComponentLogger().info("Auto slots: {}.",
+ new Gson().toJson(warpGroups.stream().map(warpGroup -> new WarpGropSlotDebug(
+ warpGroup.getName(),
+ warpGroup.getSlot(),
+ warpGroup.getInternalSlot())).toList()));
+ }
- return warpGroupSlot;
+ return next != null ? next : -1;
}
+
+ private static @NotNull ArrayDeque getFreeSlots(@NotNull List warpGroups, int max) {
+ // 1) Mark occupied (explicit) slots
+ boolean[] taken = new boolean[max];
+ for (WarpGroup g : warpGroups) {
+ int s = g.getSlot();
+ if (s >= 0 && s < max) taken[s] = true;
+ }
+
+ // 2) Build the free-slot queue (ascending)
+ ArrayDeque free = new ArrayDeque<>();
+ for (int i = 0; i < max; i++) {
+ if (!taken[i]) free.add(i);
+ }
+
+ return free;
+ }
+
+ private record WarpGropSlotDebug(String name, int slot, int internalSlot) {}
}
diff --git a/src/main/java/net/buildtheearth/modules/navigation/components/warps/menu/WarpGroupSelectionMenu.java b/src/main/java/net/buildtheearth/modules/navigation/components/warps/menu/WarpGroupSelectionMenu.java
index accb5a0b..70df51eb 100644
--- a/src/main/java/net/buildtheearth/modules/navigation/components/warps/menu/WarpGroupSelectionMenu.java
+++ b/src/main/java/net/buildtheearth/modules/navigation/components/warps/menu/WarpGroupSelectionMenu.java
@@ -5,9 +5,7 @@
import net.buildtheearth.modules.navigation.components.warps.model.WarpGroup;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
-
-import java.util.List;
-import java.util.stream.Collectors;
+import org.jetbrains.annotations.NotNull;
public class WarpGroupSelectionMenu extends WarpGroupMenu {
@@ -38,20 +36,8 @@ protected void setItemClickEventsAsync() {
}
@Override
- protected void setPaginatedItemClickEventsAsync(List> source) {
- List warpGroups = source.stream().map(l -> (WarpGroup) l).collect(Collectors.toList());
-
- int slot = 0;
- for (WarpGroup warpGroup : warpGroups) {
- final int _slot = slot;
- getMenu().getSlot(getWarpGroupSlot(warpGroup, _slot)).setClickHandler((clickPlayer, clickInformation) -> {
- clickPlayer.closeInventory();
- clickPlayer.playSound(clickPlayer.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1.0F, 1.0F);
-
- warp.setWarpGroup(warpGroup);
- new WarpEditMenu(clickPlayer, warp, alreadyExists, true);
- });
- slot++;
- }
- }
+ protected void leftClickAction(@NotNull Player clickPlayer, @NotNull WarpGroup warpGroup) {
+ clickPlayer.playSound(clickPlayer.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1.0F, 1.0F);
+ warp.setWarpGroup(warpGroup);
+ new WarpEditMenu(clickPlayer, warp, alreadyExists, true); }
}
diff --git a/src/main/java/net/buildtheearth/modules/navigation/components/warps/menu/WarpMenu.java b/src/main/java/net/buildtheearth/modules/navigation/components/warps/menu/WarpMenu.java
index c333f716..d80c4438 100644
--- a/src/main/java/net/buildtheearth/modules/navigation/components/warps/menu/WarpMenu.java
+++ b/src/main/java/net/buildtheearth/modules/navigation/components/warps/menu/WarpMenu.java
@@ -1,23 +1,26 @@
package net.buildtheearth.modules.navigation.components.warps.menu;
import net.buildtheearth.modules.navigation.NavigationModule;
-import net.buildtheearth.modules.network.model.Permissions;
-import net.buildtheearth.utils.*;
-import net.buildtheearth.utils.menus.AbstractPaginatedMenu;
import net.buildtheearth.modules.navigation.components.warps.model.Warp;
import net.buildtheearth.modules.navigation.components.warps.model.WarpGroup;
+import net.buildtheearth.modules.network.NetworkModule;
+import net.buildtheearth.modules.network.model.Permissions;
+import net.buildtheearth.utils.CustomHeads;
+import net.buildtheearth.utils.Item;
+import net.buildtheearth.utils.ListUtil;
+import net.buildtheearth.utils.MenuItems;
+import net.buildtheearth.utils.menus.AbstractPaginatedMenu;
import org.bukkit.entity.Player;
import org.ipvp.canvas.mask.BinaryMask;
import org.ipvp.canvas.mask.Mask;
+import org.jetbrains.annotations.NotNull;
-import java.util.ArrayList;
-import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class WarpMenu extends AbstractPaginatedMenu {
- public final int BACK_ITEM_SLOT = 27;
+ public static final int BACK_ITEM_SLOT = 27;
private final boolean hasBackItem;
private final WarpGroup warpGroup;
@@ -42,8 +45,7 @@ protected void setMenuItemsAsync() {
}
@Override
- protected void setItemClickEventsAsync() {
- }
+ protected void setItemClickEventsAsync() { /* Not needed */ }
@Override
protected Mask getMask() {
@@ -62,15 +64,16 @@ protected List> getSource() {
List warps = warpGroup.getWarps().stream().sorted((warp1, warp2) -> warp1.getName().compareToIgnoreCase(warp2.getName())).collect(Collectors.toList());
// Add a "create warp" item if the player has permission
- if (getMenuPlayer().hasPermission(Permissions.WARP_CREATE))
+ if (getMenuPlayer().hasPermission(Permissions.WARP_CREATE)
+ && NetworkModule.getInstance().getBuildTeam().equals(warpGroup.getBuildTeam()))
warps.add(new Warp(null, "%create-warp%", null, null, null, null, null, null, 0, 0, 0, 0, 0, false));
return warps;
}
@Override
- protected void setPaginatedPreviewItems(List> source) {
- List warps = source.stream().map(l -> (Warp) l).collect(Collectors.toList());
+ protected void setPaginatedPreviewItems(@NotNull List> source) {
+ List warps = source.stream().map(l -> (Warp) l).toList();
// Create the country items
int slot = 0;
@@ -84,10 +87,6 @@ protected void setPaginatedPreviewItems(List> source) {
continue;
}
- ArrayList loreLines = ListUtil.createList("", "§eAddress:");
- loreLines.addAll(Arrays.asList(Utils.splitStringByLineLength(warp.getAddress(), 30, ", ")));
- loreLines.addAll(ListUtil.createList("", "§8Left-Click to warp to this location.", "§8Right-Click to edit this warp."));
-
getMenu().getSlot(slot).setItem(warp.getMaterialItem());
slot++;
}
@@ -96,13 +95,11 @@ protected void setPaginatedPreviewItems(List> source) {
}
@Override
- protected void setPaginatedMenuItemsAsync(List> source) {
-
- }
+ protected void setPaginatedMenuItemsAsync(List> source) {/* Not needed */}
@Override
- protected void setPaginatedItemClickEventsAsync(List> source) {
- List warps = source.stream().map(l -> (Warp) l).collect(Collectors.toList());
+ protected void setPaginatedItemClickEventsAsync(@NotNull List> source) {
+ List warps = source.stream().map(l -> (Warp) l).toList();
int slot = 0;
for (Warp warp : warps) {
@@ -112,11 +109,12 @@ protected void setPaginatedItemClickEventsAsync(List> source) {
// Create a click action for the "Create Warp" item if the player has permission
if(warp.getName().equals("%create-warp%") && getMenuPlayer().hasPermission(Permissions.WARP_CREATE) && _slot == warps.size() - 1){
- NavigationModule.getInstance().getWarpsComponent().createWarp(clickPlayer);
+ NavigationModule.getInstance().getWarpsComponent().createWarp(clickPlayer, warpGroup);
return;
}
- if(clickInformation.getClickType().isRightClick() && clickPlayer.hasPermission(Permissions.WARP_EDIT))
+ if (clickInformation.getClickType().isRightClick() && clickPlayer.hasPermission(Permissions.WARP_EDIT)
+ && warp.getWarpGroup().getBuildTeam().equals(NetworkModule.getInstance().getBuildTeam()))
new WarpEditMenu(clickPlayer, warp, true, true);
else
NavigationModule.getInstance().getWarpsComponent().warpPlayer(clickPlayer, warp);
diff --git a/src/main/java/net/buildtheearth/modules/navigation/components/warps/model/WarpGroup.java b/src/main/java/net/buildtheearth/modules/navigation/components/warps/model/WarpGroup.java
index 533160c0..e51282e8 100644
--- a/src/main/java/net/buildtheearth/modules/navigation/components/warps/model/WarpGroup.java
+++ b/src/main/java/net/buildtheearth/modules/navigation/components/warps/model/WarpGroup.java
@@ -3,7 +3,9 @@
import lombok.Getter;
import lombok.Setter;
import net.buildtheearth.modules.network.model.BuildTeam;
-import net.buildtheearth.utils.*;
+import net.buildtheearth.utils.CustomHeads;
+import net.buildtheearth.utils.Item;
+import net.buildtheearth.utils.ListUtil;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.json.JSONObject;
@@ -18,7 +20,7 @@ public class WarpGroup {
private UUID id = UUID.randomUUID();
@Getter
- private BuildTeam buildTeam;
+ private final BuildTeam buildTeam;
@Getter @Setter
private String name;
@@ -35,6 +37,9 @@ public class WarpGroup {
@Getter
private final List warps;
+ // Slot which is used internally by the navigation module when auto slot is enabled
+ @Getter @Setter
+ private int internalSlot = -1;
public WarpGroup(BuildTeam buildTeam, String name, String description, int slot, String material) {
this.buildTeam = buildTeam;
@@ -81,9 +86,9 @@ public ItemStack getMaterialItem() {
else if(material.startsWith("http://textures.minecraft.net/texture/"))
return Item.createCustomHeadTextureURL(material, itemName, lore);
- Material material = Material.matchMaterial(this.material.split(":")[0]);
+ Material matchedMaterial = Material.matchMaterial(this.material.split(":")[0]);
- if(material == null)
+ if(matchedMaterial == null)
return CustomHeads.getLetterHead(
name.substring(0, 1),
CustomHeads.LetterType.STONE,
@@ -91,9 +96,9 @@ else if(material.startsWith("http://textures.minecraft.net/texture/"))
lore
);
else if(!this.material.contains(":"))
- return Item.create(material, itemName, lore);
+ return Item.create(matchedMaterial, itemName, lore);
else
- return Item.create(material, itemName, Short.parseShort(this.material.split(":")[1]), lore);
+ return Item.create(matchedMaterial, itemName, Short.parseShort(this.material.split(":")[1]), lore);
}
diff --git a/src/main/java/net/buildtheearth/modules/navigation/menu/CountrySelectorMenu.java b/src/main/java/net/buildtheearth/modules/navigation/menu/CountrySelectorMenu.java
index 3678e3d2..aafb89d1 100644
--- a/src/main/java/net/buildtheearth/modules/navigation/menu/CountrySelectorMenu.java
+++ b/src/main/java/net/buildtheearth/modules/navigation/menu/CountrySelectorMenu.java
@@ -1,32 +1,36 @@
package net.buildtheearth.modules.navigation.menu;
import lombok.NonNull;
+import net.buildtheearth.modules.navigation.NavUtils;
+import net.buildtheearth.modules.navigation.components.warps.WarpsComponent;
import net.buildtheearth.modules.network.NetworkModule;
import net.buildtheearth.modules.network.model.BuildTeam;
import net.buildtheearth.modules.network.model.Continent;
+import net.buildtheearth.modules.network.model.Permissions;
import net.buildtheearth.modules.network.model.Region;
-import net.buildtheearth.utils.*;
+import net.buildtheearth.utils.ChatHelper;
+import net.buildtheearth.utils.Item;
+import net.buildtheearth.utils.ListUtil;
+import net.buildtheearth.utils.MenuItems;
import net.buildtheearth.utils.menus.AbstractPaginatedMenu;
import org.bukkit.entity.Player;
import org.ipvp.canvas.mask.BinaryMask;
import org.ipvp.canvas.mask.Mask;
+import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
-import java.util.stream.Collectors;
public class CountrySelectorMenu extends AbstractPaginatedMenu {
- private final Continent continent;
private final List regions;
- public final int BACK_ITEM_SLOT = 27;
- public static int SWITCH_PAGE_ITEM_SLOT = 34;
+ public static final int BACK_ITEM_SLOT = 27;
+ public static final int SWITCH_PAGE_ITEM_SLOT = 34;
public CountrySelectorMenu(Player menuPlayer, @NonNull Continent continent, boolean autoLoad) {
super(4, 3, continent.getLabel() + " - countries", menuPlayer, autoLoad);
- this.continent = continent;
this.regions = new ArrayList<>(continent.getCountries());
// Add USA region to North America because it is being built by multiple teams
@@ -34,13 +38,13 @@ public CountrySelectorMenu(Player menuPlayer, @NonNull Continent continent, bool
regions.add(
new Region("USA",
Continent.NORTH_AMERICA,
- new BuildTeam(null, null, null, "4 Teams", null, Continent.NORTH_AMERICA, false, false),
+ new BuildTeam(null, null, null, "4 Teams", null, false, false, false, ""),
"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNGNhYzk3NzRkYTEyMTcyNDg1MzJjZTE0N2Y3ODMxZjY3YTEyZmRjY2ExY2YwY2I0YjM4NDhkZTZiYzk0YjQifX19"
, 9372610, "US", "USA"
)
);
- if(regions.size() > 0) {
+ if (!regions.isEmpty()) {
// Sort countries by area
regions.sort(Comparator.comparing(Region::getArea).reversed());
@@ -48,13 +52,12 @@ public CountrySelectorMenu(Player menuPlayer, @NonNull Continent continent, bool
regions.removeAll(regions.stream().filter(region ->
region.getBuildTeam() == null
|| region.getHeadBase64() == null
- || region.getBuildTeam() == null
|| region.getBuildTeam().getID() == null
|| (
NetworkModule.getInstance().getBuildTeam() != null
&& region.getBuildTeam().getID().equals(NetworkModule.getInstance().getBuildTeam().getID())
)
- ).collect(Collectors.toList()));
+ ).toList());
}
ChatHelper.logDebug("Continent in constructor: %s", continent);
@@ -75,14 +78,17 @@ protected void setPreviewItems() {
}
@Override
- protected void setPaginatedPreviewItems(List> source) {
- List countries = source.stream().map(l -> (Region) l).collect(Collectors.toList());
+ protected void setPaginatedPreviewItems(@NotNull List> source) {
+ List countries = source.stream().map(l -> (Region) l).toList();
// Create the country items
int slot = 0;
for (Region region : countries) {
ArrayList countryLore = ListUtil.createList("", "§eBuild Team:", region.getBuildTeam().getBlankName(), "", "§eArea:", formatArea(region.getArea()) + " km²", "", "§8Click to join this country's server!");
+ if (!region.getBuildTeam().getWarpGroups().isEmpty()) {
+ countryLore.add("Right click to open the warp group menu!");
+ }
getMenu().getSlot(slot).setItem(
Item.createCustomHeadBase64(region.getHeadBase64() == null ? "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYmFkYzA0OGE3Y2U3OGY3ZGFkNzJhMDdkYTI3ZDg1YzA5MTY4ODFlNTUyMmVlZWQxZTNkYWYyMTdhMzhjMWEifX19" : region.getHeadBase64(),
"§6§l" + region.getName(),
@@ -93,7 +99,8 @@ protected void setPaginatedPreviewItems(List> source) {
}
@Override
- protected void setMenuItemsAsync() {}
+ protected void setMenuItemsAsync(/* No async Items set */) {
+ }
@Override
protected void setItemClickEventsAsync() {
@@ -102,8 +109,8 @@ protected void setItemClickEventsAsync() {
}
@Override
- protected void setPaginatedItemClickEventsAsync(List> source) {
- List countries = source.stream().map(l -> (Region) l).collect(Collectors.toList());
+ protected void setPaginatedItemClickEventsAsync(@NotNull List> source) {
+ List countries = source.stream().map(l -> (Region) l).toList();
int slot = 0;
for (Region clickedRegion : countries) {
@@ -111,20 +118,20 @@ protected void setPaginatedItemClickEventsAsync(List> source) {
getMenu().getSlot(_slot).setClickHandler((clickPlayer, clickInformation) -> {
clickPlayer.closeInventory();
- ChatHelper.logDebug("%s", clickedRegion.getName());
+ ChatHelper.logDebug("Clicked Region: %s", clickedRegion.getName() + " (" + clickedRegion.getCountryCodeCca3() + ")");
- if(clickedRegion.getCountryCodeCca3().equalsIgnoreCase("USA"))
- new StateSelectorMenu(clickedRegion, clickPlayer, true);
- else if (clickedRegion.getBuildTeam().isConnected())
- Utils.sendPlayerToServer(clickPlayer, clickedRegion.getBuildTeam().getServerName());
- else
- NetworkModule.sendNotConnectedMessage(clickPlayer, clickedRegion.getBuildTeam().getIP());
+ if (clickInformation.getClickType().isRightClick() &&
+ clickPlayer.hasPermission(Permissions.WARP_USE) &&
+ !clickedRegion.getBuildTeam().getWarpGroups().isEmpty()) {
+ WarpsComponent.openWarpMenu(clickPlayer, clickedRegion.getBuildTeam(), this);
+ } else {
+ NavUtils.switchToTeam(clickedRegion.getBuildTeam(), clickPlayer);
+ }
});
slot++;
}
}
-
@Override
protected Mask getMask() {
return BinaryMask.builder(getMenu())
@@ -146,10 +153,8 @@ protected void setPaginatedMenuItemsAsync(List> source) {
}
- /** Converts an area in square meters to a string with dot notation starting from the right every 3 digits.
- *
- * @param area
- * @return
+ /**
+ * Converts an area in square meters to a string with dot notation starting from the right every 3 digits.
*/
public static String formatArea(double area) {
String areaStr = String.valueOf((int) area);
diff --git a/src/main/java/net/buildtheearth/modules/navigation/menu/ExploreMenu.java b/src/main/java/net/buildtheearth/modules/navigation/menu/ExploreMenu.java
index 231e8442..ba3a6a97 100644
--- a/src/main/java/net/buildtheearth/modules/navigation/menu/ExploreMenu.java
+++ b/src/main/java/net/buildtheearth/modules/navigation/menu/ExploreMenu.java
@@ -7,7 +7,6 @@
import net.buildtheearth.utils.Item;
import net.buildtheearth.utils.MenuItems;
import net.buildtheearth.utils.menus.AbstractMenu;
-import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.entity.Player;
import org.ipvp.canvas.mask.BinaryMask;
import org.ipvp.canvas.mask.Mask;
@@ -34,8 +33,8 @@ public ExploreMenu(Player menuPlayer, boolean autoLoad) {
protected void setPreviewItems() {
// Create the continent items
for (Continent continent : Continent.values()) {
- ArrayList continentLore = new ArrayList<>(Collections.singletonList(ChatHelper.getStandardString("Visit countries in %s", continent.getLabel())));
- getMenu().getSlot(continent.getSlot()).setItem(Item.create(XMaterial.COMPASS.parseMaterial(),"§e§l" + continent.getLabel(), 1, continentLore));
+ ArrayList continentLore = new ArrayList<>(Collections.singletonList(ChatHelper.getStandardString(false, "Visit countries in %s", continent.getLabel())));
+ getMenu().getSlot(continent.getSlot()).setItem(Item.create(XMaterial.COMPASS.get(), "§e§l" + continent.getLabel(), 1, continentLore));
}
super.setPreviewItems();
@@ -48,13 +47,9 @@ protected void setItemClickEventsAsync() {
getMenu().getSlot(continent.getSlot()).setClickHandler((clickPlayer, clickInformation) -> {
clickPlayer.closeInventory();
- System.out.println("Continent before creating CountrySelectorMenu: " + continent); // Add this line
+ ChatHelper.logDebug("Clicked Continent before creating CountrySelectorMenu: %s", continent.getLabel());
- if(continent.equals(Continent.AFRICA)) {
- // TODO implement that the player gets information about the BTE Africa server when clicking on Africa
- } else {
- new CountrySelectorMenu(clickPlayer, continent, true);
- }
+ new CountrySelectorMenu(clickPlayer, continent, true);
});
}
}
diff --git a/src/main/java/net/buildtheearth/modules/navigation/menu/MainMenu.java b/src/main/java/net/buildtheearth/modules/navigation/menu/MainMenu.java
index d826cc68..1d9b7dbc 100644
--- a/src/main/java/net/buildtheearth/modules/navigation/menu/MainMenu.java
+++ b/src/main/java/net/buildtheearth/modules/navigation/menu/MainMenu.java
@@ -2,21 +2,29 @@
import com.cryptomorin.xseries.XMaterial;
import net.buildtheearth.BuildTeamTools;
+import net.buildtheearth.modules.navigation.NavUtils;
+import net.buildtheearth.modules.navigation.components.warps.WarpsComponent;
import net.buildtheearth.modules.network.NetworkModule;
import net.buildtheearth.utils.ChatHelper;
import net.buildtheearth.utils.Item;
import net.buildtheearth.utils.MenuItems;
-import net.buildtheearth.utils.Utils;
import net.buildtheearth.utils.io.ConfigPaths;
+import net.buildtheearth.utils.io.ConfigUtil;
import net.buildtheearth.utils.menus.AbstractMenu;
import net.kyori.adventure.text.format.NamedTextColor;
+import org.apache.commons.lang3.BooleanUtils;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.ipvp.canvas.mask.BinaryMask;
import org.ipvp.canvas.mask.Mask;
+import org.jetbrains.annotations.NotNull;
+import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
+import java.util.Deque;
+import java.util.List;
+import java.util.Objects;
/**
* The main menu for the BTE universal navigator.
@@ -31,86 +39,102 @@
*/
public class MainMenu extends AbstractMenu {
- private static final String inventoryName = "BuildTheEarth Navigator";
+ private static final String INVENTORY_NAME = "BuildTheEarth Navigator";
private static FileConfiguration config;
public MainMenu(Player menuPlayer) {
- super(3, inventoryName, menuPlayer);
+ super(3, INVENTORY_NAME, menuPlayer);
}
@Override
protected void setPreviewItems() {
- config = BuildTeamTools.getInstance().getConfig();
- int[] slots = getSlots();
+ config = BuildTeamTools.getInstance().getConfig(ConfigUtil.NAVIGATION);
+ @NotNull Deque<@NotNull Integer> slots = getSlots();
// Fill the blank slots with glass panes
- getMenu().getSlot(11).setItem(MenuItems.ITEM_BACKGROUND);
- getMenu().getSlot(13).setItem(MenuItems.ITEM_BACKGROUND);
- getMenu().getSlot(15).setItem(MenuItems.ITEM_BACKGROUND);
-
- // Set Explore Item
- ArrayList exploreLore = new ArrayList<>(Collections.singletonList(ChatHelper.getColorizedString(NamedTextColor.GRAY, "Click to explore the project!", false)));
- getMenu().getSlot(slots[0]).setItem(Item.create(XMaterial.SPRUCE_BOAT.parseMaterial(), ChatHelper.getColorizedString(NamedTextColor.YELLOW, "Explore", true), 1, exploreLore));
-
+ for (int i = 10; i <= 16; i++) {
+ getMenu().getSlot(i).setItem(MenuItems.ITEM_BACKGROUND);
+ }
// Set Build Item
- if(config.getBoolean(ConfigPaths.Navigation.BUILD_ITEM_ENABLED)) {
+ if (config.getBoolean(ConfigPaths.Navigation.BUILD_ITEM_ENABLED)) {
ArrayList buildLore = new ArrayList<>(Collections.singletonList(ChatHelper.getColorizedString(NamedTextColor.GRAY, "Click to build for the project!", false)));
- getMenu().getSlot(slots[1]).setItem(Item.create(XMaterial.DIAMOND_PICKAXE.parseMaterial(), ChatHelper.getColorizedString(NamedTextColor.GREEN, "Build", true), 1, buildLore));
+ getMenu().getSlot(Objects.requireNonNull(slots.pollFirst())).setItem(Item.edit(Objects.requireNonNull(XMaterial.DIAMOND_PICKAXE.parseItem()), 1, ChatHelper.getColorizedString(NamedTextColor.GREEN, "Terra Server", true), buildLore));
+ }
+
+ // Set Plotsystem Item Click Event
+ if (config.getBoolean(ConfigPaths.Navigation.PLOTSYSTEM_ITEM_ENABLED)) {
+ ArrayList tutorialsLore = new ArrayList<>(Collections.singletonList(ChatHelper.getColorizedString(NamedTextColor.GRAY, "Click to start your journey!", false)));
+ getMenu().getSlot(Objects.requireNonNull(slots.pollFirst())).setItem(Item.edit(Objects.requireNonNull(XMaterial.KNOWLEDGE_BOOK.parseItem()), 1, ChatHelper.getColorizedString(NamedTextColor.AQUA, "Plot System", true), tutorialsLore));
+ }
+
+ if (config.getBoolean(ConfigPaths.Navigation.EXPLORE_ITEM_ENABLED)) {
+ // Set Explore Item
+ List exploreLore = List.of(ChatHelper.getColorizedString(NamedTextColor.GRAY, "Click to explore the warps!", false), ChatHelper.getColorizedString(NamedTextColor.LIGHT_PURPLE, "Right click to explore other build teams.", false));
+ getMenu().getSlot(Objects.requireNonNull(slots.pollFirst())).setItem(Item.edit(Objects.requireNonNull(XMaterial.SPRUCE_BOAT.parseItem()), 1, ChatHelper.getColorizedString(NamedTextColor.YELLOW, "Explore", true), exploreLore));
}
// Set Tutorials Item
- if(config.getBoolean(ConfigPaths.Navigation.TUTORIALS_ITEM_ENABLED)) {
+ if (config.getBoolean(ConfigPaths.Navigation.TUTORIALS_ITEM_ENABLED)) {
ArrayList tutorialsLore = new ArrayList<>(Collections.singletonList(ChatHelper.getColorizedString(NamedTextColor.GRAY, "Click to do some tutorials!", false)));
- getMenu().getSlot(slots[2]).setItem(Item.create(XMaterial.KNOWLEDGE_BOOK.parseMaterial(), ChatHelper.getColorizedString(NamedTextColor.AQUA, "Tutorials", true), 1, tutorialsLore));
+ getMenu().getSlot(Objects.requireNonNull(slots.pollFirst())).setItem(Item.edit(Objects.requireNonNull(XMaterial.KNOWLEDGE_BOOK.parseItem()), 1, ChatHelper.getColorizedString(NamedTextColor.AQUA, "Tutorials", true), tutorialsLore));
}
super.setPreviewItems();
}
@Override
- protected void setMenuItemsAsync() {}
+ protected void setMenuItemsAsync() { /* No async Items set */}
@Override
protected void setItemClickEventsAsync() {
- int[] slots = getSlots();
-
- // Set Explore Item Click Event
- getMenu().getSlot(slots[0]).setClickHandler((clickPlayer, clickInformation) -> {
- clickPlayer.closeInventory();
- new ExploreMenu(clickPlayer, true);
- });
+ Deque slots = getSlots();
// Set Build Item Click Event
- if(config.getBoolean(ConfigPaths.Navigation.BUILD_ITEM_ENABLED)) {
- getMenu().getSlot(slots[1]).setClickHandler((clickPlayer, clickInformation) -> {
- clickPlayer.closeInventory();
- String action = config.getString(ConfigPaths.Navigation.BUILD_ITEM_ACTION);
+ if (config.getBoolean(ConfigPaths.Navigation.BUILD_ITEM_ENABLED)) {
+ getMenu().getSlot(Objects.requireNonNull(slots.pollFirst()))
+ .setClickHandler((clickPlayer, clickInformation) -> {
+ clickPlayer.closeInventory();
+ String action = config.getString(ConfigPaths.Navigation.BUILD_ITEM_ACTION);
+ performClickAction(clickPlayer, Objects.requireNonNull(action).replace("&", "§"), "build");
+ });
+ }
- // If no command or message is set, teleport player to the plot system server
- if(action == null || action.equals("/command") || action.equals("message")) {
- clickPlayer.sendMessage(ChatHelper.getStandardString("Teleporting you to the plot system server..."));
- Utils.sendPlayerToServer(clickPlayer, NetworkModule.GLOBAL_PLOT_SYSTEM_SERVER);
- return;
- }
+ // Set Plotsystem Item Click Event
+ if (config.getBoolean(ConfigPaths.Navigation.PLOTSYSTEM_ITEM_ENABLED)) {
+ getMenu().getSlot(Objects.requireNonNull(slots.pollFirst()))
+ .setClickHandler((clickPlayer, clickInformation) -> {
+ clickPlayer.closeInventory();
+ String action = config.getString(ConfigPaths.Navigation.PLOTSYSTEM_ITEM_ACTION);
+ performClickAction(clickPlayer, Objects.requireNonNull(action).replace("&", "§"), "plotsystem");
+ });
+ }
- performClickAction(clickPlayer, action.replace("&", "§"));
+ if (config.getBoolean(ConfigPaths.Navigation.EXPLORE_ITEM_ENABLED)) {
+ // Set Explore Item Click Event
+ getMenu().getSlot(Objects.requireNonNull(slots.pollFirst())).setClickHandler((clickPlayer, clickInformation) -> {
+ clickPlayer.closeInventory();
+ if (clickInformation.getClickType().isRightClick()) {
+ new ExploreMenu(clickPlayer, true);
+ } else {
+ WarpsComponent.openWarpMenu(clickPlayer, NetworkModule.getInstance().getBuildTeam(), this);
+ }
});
}
// Set Tutorials Item Click Event
- if(config.getBoolean(ConfigPaths.Navigation.TUTORIALS_ITEM_ENABLED)) {
- getMenu().getSlot(slots[2]).setClickHandler((clickPlayer, clickInformation) -> {
+ if (config.getBoolean(ConfigPaths.Navigation.TUTORIALS_ITEM_ENABLED)) {
+ getMenu().getSlot(Objects.requireNonNull(slots.pollFirst())).setClickHandler((clickPlayer, clickInformation) -> {
clickPlayer.closeInventory();
String action = config.getString(ConfigPaths.Navigation.TUTORIALS_ITEM_ACTION);
// If no command or message is set, open the tutorial menu
- if(action == null || action.equals("/command") || action.equals("message")) {
+ if (action == null || action.equals("/command") || action.equals("message")) {
new TutorialsMenu(clickPlayer);
return;
}
- performClickAction(clickPlayer, action.replace("&", "§"));
+ performClickAction(clickPlayer, action.replace("&", "§"), "tutorial");
});
}
}
@@ -120,47 +144,63 @@ protected Mask getMask() {
return BinaryMask.builder(getMenu())
.item(MenuItems.ITEM_BACKGROUND)
.pattern("111111111")
- .pattern("110101011")
+ .pattern("100000001")
.pattern("111111111")
.build();
}
- /** Returns the slots for the Build, Explore and Tutorials items depending on which items are enabled in the config
+ /**
+ * Returns the slots for the Build, Explore and Tutorials items depending on which items are enabled in the config
*
- * @return int[] - Slots of the Explore [0], Build [1] and Tutorials [2] items
+ * @return int[] - Slots of the enabled items
*/
- private int[] getSlots() {
- int[] slots = new int[3];
-
+ private @NotNull Deque<@NotNull Integer> getSlots() {
+ Deque slots = new ArrayDeque<>();
boolean buildEnabled = config.getBoolean(ConfigPaths.Navigation.BUILD_ITEM_ENABLED);
boolean tutorialsEnabled = config.getBoolean(ConfigPaths.Navigation.TUTORIALS_ITEM_ENABLED);
+ boolean plotsystemEnabled = config.getBoolean(ConfigPaths.Navigation.PLOTSYSTEM_ITEM_ENABLED);
+ boolean exploreEnabled = config.getBoolean(ConfigPaths.Navigation.EXPLORE_ITEM_ENABLED);
- int exploreSlot = 11;
- int buildSlot = 13;
- int tutorialsSlot = 15;
-
- int enabledItemCount = (buildEnabled ? 1 : 0) + 1 + (tutorialsEnabled ? 1 : 0);
+ int enabledItemCount = BooleanUtils.toInteger(buildEnabled) + BooleanUtils.toInteger(tutorialsEnabled) +
+ BooleanUtils.toInteger(plotsystemEnabled) + BooleanUtils.toInteger(exploreEnabled);
// Depending on how many items are enabled, set the slots to the correct positions
- if (enabledItemCount == 2) {
- if (buildEnabled)
- buildSlot = 15;
- else
- buildSlot = 11;
+ switch (enabledItemCount) {
+ case 1:
+ slots.add(13);
+ break;
+ case 2:
+ slots.add(11);
+ slots.add(15);
+ break;
+ case 3:
+ slots.add(11);
+ slots.add(13);
+ slots.add(15);
+ break;
+ case 4:
+ slots.add(10);
+ slots.add(12);
+ slots.add(14);
+ slots.add(16);
+ break;
+ default:
+ throw new IllegalStateException("Unexpected enabled items value: " + enabledItemCount);
}
- slots[0] = exploreSlot;
- slots[1] = buildSlot;
- slots[2] = tutorialsSlot;
-
return slots;
}
- private void performClickAction(Player p, String action) {
+ private void performClickAction(Player p, @NotNull String action, @NotNull String type) {
// Check if an action is set in the config
- if(!action.equals("/command") &&! action.equals("message"))
+ if (action.startsWith("transfer:")) {
+ NavUtils.transferPlayer(p, action.substring(9));
+ } else if (action.startsWith("switch:")) {
+ NavUtils.sendPlayerToConnectedServer(p, action.substring(7));
+ } else if (!action.equals("/command") && !action.equals("message")) {
p.chat(action);
- else
- p.sendMessage(ChatHelper.getErrorString("No action is set for the %s in the config yet! Please contact an %s.", "build item", "admin"));
+ } else {
+ p.sendMessage(ChatHelper.getErrorString("No action is set for the %s in the config yet! Please contact an %s.", type + " item", "admin"));
+ }
}
}
\ No newline at end of file
diff --git a/src/main/java/net/buildtheearth/modules/navigation/menu/StateSelectorMenu.java b/src/main/java/net/buildtheearth/modules/navigation/menu/StateSelectorMenu.java
index 4a348f2c..a239bc8f 100644
--- a/src/main/java/net/buildtheearth/modules/navigation/menu/StateSelectorMenu.java
+++ b/src/main/java/net/buildtheearth/modules/navigation/menu/StateSelectorMenu.java
@@ -1,14 +1,19 @@
package net.buildtheearth.modules.navigation.menu;
import lombok.NonNull;
+import net.buildtheearth.modules.navigation.NavUtils;
import net.buildtheearth.modules.network.NetworkModule;
import net.buildtheearth.modules.network.model.Region;
import net.buildtheearth.modules.network.model.RegionType;
-import net.buildtheearth.utils.*;
+import net.buildtheearth.utils.ChatHelper;
+import net.buildtheearth.utils.Item;
+import net.buildtheearth.utils.ListUtil;
+import net.buildtheearth.utils.MenuItems;
import net.buildtheearth.utils.menus.AbstractPaginatedMenu;
import org.bukkit.entity.Player;
import org.ipvp.canvas.mask.BinaryMask;
import org.ipvp.canvas.mask.Mask;
+import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Comparator;
@@ -20,9 +25,10 @@ public class StateSelectorMenu extends AbstractPaginatedMenu {
private final Region country;
private final List states;
- public final int BACK_ITEM_SLOT = 27;
- public static int SWITCH_PAGE_ITEM_SLOT = 34;
+ public static final int BACK_ITEM_SLOT = 27;
+ public static final int SWITCH_PAGE_ITEM_SLOT = 34;
+ // TODO Eloborate if this is still needed anywheere, otherwise remove it - maybe ts needed for new jersey
public StateSelectorMenu(@NonNull Region country, Player menuPlayer, boolean autoLoad) {
super(4, 3, country.getName() + " - states", menuPlayer, autoLoad);
this.country = country;
@@ -33,14 +39,14 @@ public StateSelectorMenu(@NonNull Region country, Player menuPlayer, boolean aut
if(country.getCountryCodeCca3().equalsIgnoreCase("USA"))
states.add(NetworkModule.getInstance().getRegions().stream().filter(region -> region.getBuildTeam() != null && region.getBuildTeam().getID().equals("Qy2duN4l")).findFirst().orElse(null));
- if(this.states.size() > 0) {
+ if (!this.states.isEmpty()) {
// Remove all regions that don't have a build team
this.states.removeAll(this.states.stream().filter(region ->
region == null
|| region.getBuildTeam() == null
|| region.getBuildTeam().getID() == null
|| region.getBuildTeam().getID().equals(NetworkModule.getInstance().getBuildTeam().getID())
- ).collect(Collectors.toList()));
+ ).toList());
// Sort countries by area
this.states.sort(Comparator.comparing(Region::getName));
@@ -63,12 +69,12 @@ protected void setPreviewItems() {
@Override
protected void setPaginatedPreviewItems(List> source) {
- List states = source.stream().map(l -> (Region) l).collect(Collectors.toList());
+ List collectedStates = source.stream().map(l -> (Region) l).toList();
// Create the country items
int slot = 0;
- for (Region region : states) {
+ for (Region region : collectedStates) {
ArrayList stateLore = ListUtil.createList("", "§eBuild Team:", region.getBuildTeam().getBlankName(), "", "§8Click to join this state's server!");
getMenu().getSlot(slot).setItem(
Item.createCustomHeadBase64(region.getHeadBase64() == null ? "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYmFkYzA0OGE3Y2U3OGY3ZGFkNzJhMDdkYTI3ZDg1YzA5MTY4ODFlNTUyMmVlZWQxZTNkYWYyMTdhMzhjMWEifX19" : region.getHeadBase64(),
@@ -89,8 +95,8 @@ protected void setItemClickEventsAsync() {
}
@Override
- protected void setPaginatedItemClickEventsAsync(List> source) {
- List countries = source.stream().map(l -> (Region) l).collect(Collectors.toList());
+ protected void setPaginatedItemClickEventsAsync(@NotNull List> source) {
+ List countries = source.stream().map(l -> (Region) l).toList();
int slot = 0;
for (Region clickedRegion : countries) {
@@ -98,12 +104,12 @@ protected void setPaginatedItemClickEventsAsync(List> source) {
getMenu().getSlot(_slot).setClickHandler((clickPlayer, clickInformation) -> {
clickPlayer.closeInventory();
- ChatHelper.logDebug("%s", clickedRegion.getName());
+ ChatHelper.logDebug("Clicked the state: %s", clickedRegion.getName() + " (" + clickedRegion.getCountryCodeCca3() + ")");
if (clickedRegion.getBuildTeam().isConnected())
- Utils.sendPlayerToServer(clickPlayer, clickedRegion.getBuildTeam().getServerName());
+ NavUtils.sendPlayerToConnectedServer(clickPlayer, clickedRegion.getBuildTeam().getServerName());
else
- NetworkModule.sendNotConnectedMessage(clickPlayer, clickedRegion.getBuildTeam().getIP());
+ NavUtils.sendNotConnectedMessage(clickPlayer, clickedRegion.getBuildTeam().getIP(), clickedRegion.getBuildTeam().getName());
});
slot++;
}
diff --git a/src/main/java/net/buildtheearth/modules/navigation/menu/TutorialsMenu.java b/src/main/java/net/buildtheearth/modules/navigation/menu/TutorialsMenu.java
index 3303398f..4c4a3c15 100644
--- a/src/main/java/net/buildtheearth/modules/navigation/menu/TutorialsMenu.java
+++ b/src/main/java/net/buildtheearth/modules/navigation/menu/TutorialsMenu.java
@@ -1,8 +1,6 @@
package net.buildtheearth.modules.navigation.menu;
-import net.buildtheearth.BuildTeamTools;
import net.buildtheearth.utils.menus.AbstractMenu;
-import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.ipvp.canvas.mask.Mask;
@@ -16,11 +14,10 @@ public class TutorialsMenu extends AbstractMenu {
private static final int BACK_BUTTON_SLOT = 13;
- private static final String inventoryName = "Tutorials Menu";
- private static final FileConfiguration config = BuildTeamTools.getInstance().getConfig();
+ private static final String INVENTORY_NAME = "Tutorials Menu";
public TutorialsMenu(Player player) {
- super(3, inventoryName, player);
+ super(3, INVENTORY_NAME, player);
}
@Override
diff --git a/src/main/java/net/buildtheearth/modules/network/NetworkModule.java b/src/main/java/net/buildtheearth/modules/network/NetworkModule.java
index 2ffae403..355dc8a0 100644
--- a/src/main/java/net/buildtheearth/modules/network/NetworkModule.java
+++ b/src/main/java/net/buildtheearth/modules/network/NetworkModule.java
@@ -15,12 +15,9 @@
import net.buildtheearth.utils.io.ConfigPaths;
import net.buildtheearth.utils.io.Constants;
import net.buildtheearth.utils.io.Errors;
-import net.md_5.bungee.api.chat.ClickEvent;
-import net.md_5.bungee.api.chat.ComponentBuilder;
-import net.md_5.bungee.api.chat.HoverEvent;
-import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
+import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
@@ -31,9 +28,7 @@
public class NetworkModule extends Module {
- public static String GLOBAL_PLOT_SYSTEM_SERVER = "NYC-1";
-
- public static int CACHE_UPLOAD_SPEED = 20 * 60 * 10 + 20;
+ public static final int CACHE_UPLOAD_SPEED = 20 * 60 * 10 + 20;
/** Information about the build team of this server */
@Getter @Setter
@@ -65,8 +60,8 @@ public static NetworkModule getInstance() {
@Override
public void enable() {
- String API_KEY = BuildTeamTools.getInstance().getConfig().getString(ConfigPaths.API_KEY);
- if(API_KEY == null || API_KEY.isEmpty() || API_KEY.equals(Constants.DEFAULT_API_KEY)){
+ String apiKey = BuildTeamTools.getInstance().getConfig().getString(ConfigPaths.API_KEY);
+ if (apiKey == null || apiKey.isEmpty() || apiKey.equals(Constants.DEFAULT_API_KEY)) {
shutdown(Errors.API_KEY_NOT_CONFIGURED);
return;
}
@@ -106,15 +101,13 @@ public CompletableFuture updateCache() {
try {
- NetworkAPI.getBuildTeamInformation().thenRun(() -> {
- NetworkAPI.setupCurrentServerData()
+ NetworkAPI.getBuildTeamInformation().thenRun(() -> NetworkAPI.setupCurrentServerData()
.thenRun(() ->
- future.complete(null))
+ future.complete(null))
.exceptionally(e -> {
future.completeExceptionally(e);
return null;
- });
- }).exceptionally(e -> {
+ })).exceptionally(e -> {
future.completeExceptionally(e);
return null;
});
@@ -146,7 +139,7 @@ public void ping(Player p) {
* {@link #ping(Player)}
*/
public void pingAllOnlinePlayers() {
- Bukkit.getOnlinePlayers().forEach(player -> ping(player));
+ Bukkit.getOnlinePlayers().forEach(this::ping);
}
/**
@@ -162,36 +155,12 @@ public void switchServer(Player player, String targetServer) {
player.sendPluginMessage(BuildTeamTools.getInstance(), "BungeeCord", out.toByteArray());
}
- /** Sends a message to the player that the server is not connected to the network yet.
- * Instead of the server name the server IP will be displayed so the player can join the other server ip manually.
- *
- * @param player The player to send the message to
- * @param serverIP The IP of the server the player should join
- */
- public static void sendNotConnectedMessage(Player player, String serverIP) {
- TextComponent comp = new TextComponent("§e" + serverIP + " §7(Click to copy)");
- comp.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, serverIP));
- comp.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("§eClick to copy").create()));
-
- String notConnected = "§cThis server is not connected to the network yet and has a different Server IP:";
-
- if(!NetworkModule.getInstance().getBuildTeam().isConnected())
- notConnected = "§cThis server has a different Server IP:";
-
- player.closeInventory();
- player.sendMessage(notConnected);
- player.sendMessage("");
- player.spigot().sendMessage(comp);
- player.sendMessage("");
- player.sendMessage("§cClick on the IP to copy it. Then enter it in your Minecraft Server List. (Paste with CTRL + V)");
- }
-
/** Returns all regions of the given region type.
*
* @param regionType The region type to get the regions of
* @return A list of all regions of the given region type
*/
- public static ArrayList getRegionsByRegionType(RegionType regionType){
+ public static @NotNull List getRegionsByRegionType(RegionType regionType) {
ArrayList regions = new ArrayList<>();
for(Region region : NetworkModule.getInstance().getRegions())
if(region.getType().equals(regionType))
@@ -218,9 +187,9 @@ public boolean ownsRegion(String regionName, String countryCodeCca2) {
* @return The BuildTeam with the given ID
*/
public BuildTeam getBuildTeamByID(String teamID) {
- for(BuildTeam buildTeam : buildTeams)
- if (buildTeam.getID() != null && buildTeam.getID().equals(teamID))
- return buildTeam;
+ for (BuildTeam team : buildTeams)
+ if (team.getID() != null && team.getID().equals(teamID))
+ return team;
return null;
}
diff --git a/src/main/java/net/buildtheearth/modules/network/api/NetworkAPI.java b/src/main/java/net/buildtheearth/modules/network/api/NetworkAPI.java
index ff137e52..69a8346b 100644
--- a/src/main/java/net/buildtheearth/modules/network/api/NetworkAPI.java
+++ b/src/main/java/net/buildtheearth/modules/network/api/NetworkAPI.java
@@ -1,6 +1,10 @@
package net.buildtheearth.modules.network.api;
+import lombok.experimental.UtilityClass;
import net.buildtheearth.BuildTeamTools;
+import net.buildtheearth.modules.navigation.NavUtils;
+import net.buildtheearth.modules.navigation.components.warps.model.Warp;
+import net.buildtheearth.modules.navigation.components.warps.model.WarpGroup;
import net.buildtheearth.modules.network.NetworkModule;
import net.buildtheearth.modules.network.model.BuildTeam;
import net.buildtheearth.modules.network.model.Continent;
@@ -8,12 +12,11 @@
import net.buildtheearth.modules.network.model.RegionType;
import net.buildtheearth.utils.ChatHelper;
import net.buildtheearth.utils.io.ConfigPaths;
-import net.buildtheearth.modules.navigation.components.warps.model.Warp;
-import net.buildtheearth.modules.navigation.components.warps.model.WarpGroup;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
+import org.jetbrains.annotations.NotNull;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
@@ -21,6 +24,7 @@
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
+@UtilityClass
public class NetworkAPI {
/**
@@ -50,10 +54,10 @@ public void onFailure(IOException e) {
}
// Add all currently connected regions to their respective continents
- public static CompletableFuture getBuildTeamInformation() {
+ public static @NotNull CompletableFuture getBuildTeamInformation() {
CompletableFuture future = new CompletableFuture<>();
- API.getAsync("https://nwapi.buildtheearth.net/api/teams", new API.ApiResponseCallback() {
+ getAsync("https://nwapi.buildtheearth.net/api/teams", new API.ApiResponseCallback() {
@Override
public void onResponse(String response) {
try {
@@ -78,23 +82,12 @@ public void onResponse(String response) {
for (Object object : responseArray.toArray()) {
// Check if the object is a JSON object
- if (!(object instanceof JSONObject)) continue;
- JSONObject teamObject = (JSONObject) object;
-
- // Extract a JSON array containing the regions belonging to the team
- Object regions = teamObject.get("Regions");
- if (!(regions instanceof JSONArray)) continue;
- JSONArray regionArray = (JSONArray) regions;
-
- // Extract a JSON array containing the warps belonging to the team
- Object warps = teamObject.get("Warps");
- if (!(warps instanceof JSONArray)) continue;
- JSONArray warpArray = (JSONArray) warps;
-
- // Extract a JSON array containing the warp groups belonging to the team
- Object warpGroups = teamObject.get("WarpGroups");
- if (!(warpGroups instanceof JSONArray)) continue;
- JSONArray warpGroupArray = (JSONArray) warpGroups;
+ if (!(object instanceof JSONObject teamObject) ||
+ !(teamObject.get("Regions") instanceof JSONArray regions) ||
+ !(teamObject.get("Warps") instanceof JSONArray warps) ||
+ !(teamObject.get("WarpGroups") instanceof JSONArray warpGroups)) {
+ continue;
+ }
// Get some values to add to the build team
Continent continent = Continent.getByLabel((String) teamObject.get("Continent"));
@@ -105,18 +98,18 @@ public void onResponse(String response) {
String serverName = getMainServerName(teamObject);
String name = (String) teamObject.get("Name");
String blankName = (String) teamObject.get("BlankName");
+ boolean allowsTransfers = (long) teamObject.get("AllowsTransfers") == 1;
+ String tag = (String) teamObject.get("Tag");
- BuildTeam buildTeam = new BuildTeam(teamID, mainServerIP, name, blankName, serverName, continent, isConnected, hasBuildTeamToolsInstalled);
+ BuildTeam buildTeam = new BuildTeam(teamID, mainServerIP, name, blankName, serverName,
+ isConnected, hasBuildTeamToolsInstalled, allowsTransfers, tag);
NetworkModule.getInstance().getBuildTeams().add(buildTeam);
- // Create an "other" Warp Group for warps that don't belong to a warp group
- WarpGroup otherWarpGroup = new WarpGroup(buildTeam, "Other", "Other warps", -1, null);
- buildTeam.getWarpGroups().add(otherWarpGroup);
+ WarpGroup otherWarpGroup = NavUtils.createOtherWarpGroup();
// Add all the warp groups of the team to their respective build teams
- for (Object warpGroupJSON : warpGroupArray.toArray()) {
- if (!(warpGroupJSON instanceof JSONObject)) continue;
- JSONObject warpGroupObject = (JSONObject) warpGroupJSON;
+ for (Object warpGroupJSON : warpGroups.toArray()) {
+ if (!(warpGroupJSON instanceof JSONObject warpGroupObject)) continue;
UUID warpGroupID = UUID.fromString((String) warpGroupObject.get("ID"));
String warpGroupName = (String) warpGroupObject.get("Name");
@@ -129,10 +122,11 @@ public void onResponse(String response) {
buildTeam.getWarpGroups().add(warpGroup);
}
+ if (!otherWarpGroup.getWarps().isEmpty()) buildTeam.getWarpGroups().add(otherWarpGroup);
+
// Add all the warps of the team to their respective warp groups
- for (Object warpJSON : warpArray.toArray()) {
- if (!(warpJSON instanceof JSONObject)) continue;
- JSONObject warpObject = (JSONObject) warpJSON;
+ for (Object warpJSON : warps.toArray()) {
+ if (!(warpJSON instanceof JSONObject warpObject)) continue;
String warpIDString = (String) warpObject.get("ID");
UUID warpID = warpIDString != null ? UUID.fromString(warpIDString) : null;
@@ -151,7 +145,7 @@ public void onResponse(String response) {
float warpPitch = Float.parseFloat(warpObject.get("Pitch") + "");
boolean isHighlight = warpObject.get("isHighlight") != null && (long) warpObject.get("isHighlight") == 1;
- if (material != null && material.equals(""))
+ if (material != null && material.isEmpty())
material = null;
WarpGroup warpGroup = null;
@@ -186,9 +180,8 @@ public void onResponse(String response) {
}
// Add all the regions of the team to their respective continents
- for (Object regionJSON : regionArray.toArray()) {
- if (!(regionJSON instanceof JSONObject)) continue;
- JSONObject regionObject = (JSONObject) regionJSON;
+ for (Object regionJSON : regions.toArray()) {
+ if (!(regionJSON instanceof JSONObject regionObject)) continue;
String regionName = (String) regionObject.get("RegionName");
String headBase64 = (String) regionObject.get("Head");
@@ -226,12 +219,10 @@ private String getMainServerName(JSONObject teamObject) {
String mainServerIP = (String) teamObject.get("MainServerIP");
Object serversObject = teamObject.get("Servers");
- if(!(serversObject instanceof JSONArray)) return null;
- JSONArray serversArray = (JSONArray) serversObject;
+ if (!(serversObject instanceof JSONArray serversArray)) return null;
for(Object object : serversArray.toArray()) {
- if(!(object instanceof JSONObject)) return null;
- JSONObject serverObject = (JSONObject) object;
+ if (!(object instanceof JSONObject serverObject)) return null;
String serverIP = (String) serverObject.get("IP");
if(serverIP.equals(mainServerIP)) return (String) serverObject.get("Name");
@@ -243,8 +234,8 @@ private int getArea(JSONObject regionObject) {
if(regionObject == null) return 0;
if(regionObject.get("area") == null) return 0;
- if (regionObject.get("area") instanceof Long)
- return ((Long) regionObject.get("area")).intValue();
+ if (regionObject.get("area") instanceof Long area)
+ return Math.toIntExact(area);
return ((Double) regionObject.get("area")).intValue();
}
@@ -261,10 +252,10 @@ public void onFailure(IOException e) {
return future;
}
- public static CompletableFuture setupCurrentServerData() {
+ public static @NotNull CompletableFuture setupCurrentServerData() {
CompletableFuture future = new CompletableFuture<>();
- API.getAsync("https://nwapi.buildtheearth.net/api/teams/" + BuildTeamTools.getInstance().getConfig().getString(ConfigPaths.API_KEY), new API.ApiResponseCallback() {
+ getOneAsync("https://nwapi.buildtheearth.net/api/teams/" + BuildTeamTools.getInstance().getConfig().getString(ConfigPaths.API_KEY), new API.ApiResponseCallback() {
@Override
public void onResponse(String response) {
try {
@@ -370,8 +361,37 @@ public void onFailure(IOException e) {
});
}
- public static Warp getWarpByKey(String key) {
- //TODO IMPLEMENT
- return null;
+ private static void getOneAsync(String url, API.ApiResponseCallback callback) {
+ var path = BuildTeamTools.getInstance().getDataPath().resolve("buildteam.json");
+ if (BuildTeamTools.getInstance().isDebug() && path.toFile().exists()) {
+ // If the file exists, read from it instead of making an API call
+ try {
+ String content = new String(java.nio.file.Files.readAllBytes(path));
+ callback.onResponse(content);
+ BuildTeamTools.getInstance().getComponentLogger().warn("[DEBUG] Read connected buildteam from local file buildteam.json. Remove the file if you want up to date data.");
+ return;
+ } catch (IOException e) {
+ ChatHelper.logError("Failed to read from local buildteam.json: %s", e.getMessage());
+ }
+ }
+
+ API.getAsync(url, callback);
+ }
+
+ private static void getAsync(String url, API.ApiResponseCallback callback) {
+ var path = BuildTeamTools.getInstance().getDataPath().resolve("buildteams.json");
+ if (BuildTeamTools.getInstance().isDebug() && path.toFile().exists()) {
+ // If the file exists, read from it instead of making an API call
+ try {
+ String content = new String(java.nio.file.Files.readAllBytes(path));
+ callback.onResponse(content);
+ BuildTeamTools.getInstance().getComponentLogger().warn("[DEBUG] Read buildteams from local file buildteams.json. Remove the file if you want up to date data.");
+ return;
+ } catch (IOException e) {
+ ChatHelper.logError("Failed to read from local buildteams.json: %s", e.getMessage());
+ }
+ }
+
+ API.getAsync(url, callback);
}
}
diff --git a/src/main/java/net/buildtheearth/modules/network/api/OpenStreetMapAPI.java b/src/main/java/net/buildtheearth/modules/network/api/OpenStreetMapAPI.java
index a43fdf9e..41cd903e 100644
--- a/src/main/java/net/buildtheearth/modules/network/api/OpenStreetMapAPI.java
+++ b/src/main/java/net/buildtheearth/modules/network/api/OpenStreetMapAPI.java
@@ -1,5 +1,7 @@
package net.buildtheearth.modules.network.api;
+import net.buildtheearth.utils.ChatHelper;
+import org.jetbrains.annotations.NotNull;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
@@ -12,23 +14,25 @@ public class OpenStreetMapAPI extends API {
* @param coordinates The latitude & longitude coordinates to get the country, region & city/town from
* @return The country name and country code belonging to this location
*/
- public static CompletableFuture getCountryFromLocationAsync(double[] coordinates) {
+ public static @NotNull CompletableFuture getCountryFromLocationAsync(double @NotNull [] coordinates) {
CompletableFuture future = new CompletableFuture<>();
- String url = "https://nominatim.openstreetmap.org/reverse?lat=" + coordinates[0] + "&lon=" + coordinates[1] + "&zoom=10&format=geocodejson&accept-language=en";
+ String url = "https://photon.komoot.io/reverse?lat=" + coordinates[0] + "&lon=" + coordinates[1] + "&lang=en";
+
+ ChatHelper.logDebug("Requesting country from location: %s", url);
API.getAsync(url, new API.ApiResponseCallback() {
@Override
public void onResponse(String response) {
JSONObject jsonObject = API.createJSONObject(response);
- JSONArray featuresArray = (JSONArray) jsonObject.get("features");
- JSONObject featuresObject = (JSONObject) featuresArray.get(0);
+ ChatHelper.logDebug("Response from OpenStreetMap: %s", jsonObject);
+
+ JSONObject featuresObject = (JSONObject) ((JSONArray) jsonObject.get("features")).getFirst();
JSONObject propertiesObject = (JSONObject) featuresObject.get("properties");
- JSONObject geoCodingObject = (JSONObject) propertiesObject.get("geocoding");
- String countryCodeCca2 = (String) geoCodingObject.get("country_code");
- String countryName = (String) geoCodingObject.get("country");
+ String countryCodeCca2 = (String) propertiesObject.get("countrycode");
+ String countryName = (String) propertiesObject.get("country");
future.complete(new String[]{countryName, countryCodeCca2});
}
diff --git a/src/main/java/net/buildtheearth/modules/network/model/BuildTeam.java b/src/main/java/net/buildtheearth/modules/network/model/BuildTeam.java
index d45ea275..3472a30c 100644
--- a/src/main/java/net/buildtheearth/modules/network/model/BuildTeam.java
+++ b/src/main/java/net/buildtheearth/modules/network/model/BuildTeam.java
@@ -1,12 +1,12 @@
package net.buildtheearth.modules.network.model;
import lombok.Getter;
+import net.buildtheearth.modules.navigation.components.warps.model.Warp;
+import net.buildtheearth.modules.navigation.components.warps.model.WarpGroup;
import net.buildtheearth.modules.network.NetworkModule;
import net.buildtheearth.modules.network.api.API;
import net.buildtheearth.modules.network.api.NetworkAPI;
import net.buildtheearth.utils.ChatHelper;
-import net.buildtheearth.modules.navigation.components.warps.model.Warp;
-import net.buildtheearth.modules.navigation.components.warps.model.WarpGroup;
import org.bukkit.entity.Player;
import java.io.IOException;
@@ -30,24 +30,28 @@ public class BuildTeam {
@Getter
private final boolean hasBTToolsInstalled;
@Getter
- private final Continent continent;
- @Getter
private final List regions;
@Getter
private final List warpGroups;
+ @Getter
+ private final boolean allowsTransfers;
+ @Getter
+ private final String tag;
- public BuildTeam(String ID, String serverIP, String name, String blankName, String serverName, Continent continent, boolean isConnected, boolean hasBTToolsInstalled) {
+ public BuildTeam(String ID, String serverIP, String name, String blankName, String serverName,
+ boolean isConnected, boolean hasBTToolsInstalled, boolean allowsTransfers, String tag) {
this.ID = ID;
this.name = name;
this.blankName = blankName;
this.serverName = serverName;
- this.continent = continent;
this.isConnected = isConnected;
this.hasBTToolsInstalled = hasBTToolsInstalled;
this.regions = new ArrayList<>();
this.warpGroups = new ArrayList<>();
+ this.allowsTransfers = allowsTransfers;
+ this.tag = tag;
if(!isConnected)
this.IP = serverIP;
diff --git a/src/main/java/net/buildtheearth/utils/ChatHelper.java b/src/main/java/net/buildtheearth/utils/ChatHelper.java
index 09b4df18..db250e57 100644
--- a/src/main/java/net/buildtheearth/utils/ChatHelper.java
+++ b/src/main/java/net/buildtheearth/utils/ChatHelper.java
@@ -34,6 +34,10 @@ public static void logError(String errorMessage, Object... objects) {
Bukkit.getLogger().log(Level.INFO, ChatHelper.getErrorString(errorMessage, objects));
}
+ public static void logError(String errorMessage, Exception e, Object... objects) {
+ BuildTeamTools.getInstance().getComponentLogger().error(ChatHelper.getErrorComponent(errorMessage, objects), e);
+ }
+
public static void log(String string, Object... objects) {
Bukkit.getConsoleSender().sendMessage( getConsoleString(string, objects));
}
diff --git a/src/main/java/net/buildtheearth/utils/Item.java b/src/main/java/net/buildtheearth/utils/Item.java
index 82cce476..69401a13 100644
--- a/src/main/java/net/buildtheearth/utils/Item.java
+++ b/src/main/java/net/buildtheearth/utils/Item.java
@@ -15,20 +15,28 @@
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.inventory.meta.SkullMeta;
+import org.jetbrains.annotations.Contract;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
public class Item {
- public static HashMap nonPlayerSkulls = new HashMap<>();
+ public static final Map nonPlayerSkulls = new HashMap<>();
private ItemStack item;
private Material material;
private String displayName;
private int amount = -1;
- private ArrayList lore;
+ private List lore;
private boolean hideAttributes;
private boolean hideEnchantments;
private final List canDestroyItems = new ArrayList<>();
@@ -61,7 +69,7 @@ public Item setAmount(int amount) {
return this;
}
- public Item setLore(ArrayList lore) {
+ public Item setLore(List lore) {
this.lore = lore;
return this;
}
@@ -105,9 +113,9 @@ public ItemStack build() {
else
item.setAmount(1);
- if(item.getEnchantments().keySet().size() == 0)
- for (Enchantment en : this.enchantments.keySet())
- item.addUnsafeEnchantment(en, this.enchantments.get(en));
+ if (item.getEnchantments().isEmpty())
+ for (Map.Entry en : this.enchantments.entrySet())
+ item.addUnsafeEnchantment(en.getKey(), en.getValue());
@@ -124,7 +132,7 @@ public ItemStack build() {
if (this.hideEnchantments)
itemmeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
- if(!canDestroyItems.isEmpty()){
+ /*if(!canDestroyItems.isEmpty()){
// TODO Marked for removal in 1.20.6, not fixed yet.
//Set nameSpacedKeySet = new HashSet<>();
//for(String itemName : canDestroyItems)
@@ -138,7 +146,7 @@ public ItemStack build() {
//for(String itemName : canPlaceItems)
// nameSpacedKeySet.add(NamespacedKey.minecraft(itemName));
//itemmeta.setPlaceableKeys(nameSpacedKeySet);
- }
+ }*/
item.setItemMeta(itemmeta);
return item;
@@ -154,11 +162,7 @@ public static ItemStack create(Material material, int amount) {
public static ItemStack create(Material material, String name) {
ItemStack item = new ItemStack(material, 1);
- ItemMeta itemmeta = item.getItemMeta();
- itemmeta.setDisplayName(name);
- itemmeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
- item.setItemMeta(itemmeta);
- return item;
+ return edit(item, name);
}
public static ItemStack create(Material material, String name, int amount) {
@@ -170,7 +174,7 @@ public static ItemStack create(Material material, String name, int amount) {
return item;
}
- public static ItemStack create(Material material, String name, ArrayList lore) {
+ public static @NotNull ItemStack create(Material material, String name, List lore) {
ItemStack item = new ItemStack(material, 1, (short)0);
ItemMeta itemmeta = item.getItemMeta();
itemmeta.setDisplayName(name);
@@ -180,7 +184,7 @@ public static ItemStack create(Material material, String name, ArrayList
return item;
}
- public static ItemStack create(Material material, String name, short durability, ArrayList lore) {
+ public static @NotNull ItemStack create(Material material, String name, short durability, List lore) {
ItemStack item = new ItemStack(material, 1, durability);
ItemMeta itemmeta = item.getItemMeta();
itemmeta.setDisplayName(name);
@@ -190,7 +194,7 @@ public static ItemStack create(Material material, String name, short durability,
return item;
}
- public static ItemStack create(Material material, String name, int amount, ArrayList lore) {
+ public static @NotNull ItemStack create(Material material, String name, int amount, List lore) {
ItemStack item = new ItemStack(material, amount);
ItemMeta itemmeta = item.getItemMeta();
itemmeta.setDisplayName(name);
@@ -200,7 +204,7 @@ public static ItemStack create(Material material, String name, int amount, Array
return item;
}
- public static ItemStack createLeatherArmor(Material material, String name, Color color, ArrayList lore) {
+ public static @NotNull ItemStack createLeatherArmor(Material material, String name, Color color, List lore) {
ItemStack item = new ItemStack(material);
LeatherArmorMeta itemmeta = (LeatherArmorMeta)item.getItemMeta();
itemmeta.setDisplayName(name);
@@ -211,7 +215,7 @@ public static ItemStack createLeatherArmor(Material material, String name, Color
return item;
}
- public static ItemStack create(Material material, String name, ArrayList lore, Enchantment enchnt1, Integer level1) {
+ public static @NotNull ItemStack create(Material material, String name, List lore, Enchantment enchnt1, Integer level1) {
ItemStack item = new ItemStack(material);
item.addUnsafeEnchantment(enchnt1, level1);
ItemMeta itemmeta = item.getItemMeta();
@@ -222,7 +226,7 @@ public static ItemStack create(Material material, String name, ArrayList
return item;
}
- public static ItemStack create(Material material, String name, ArrayList lore, Enchantment enchnt1, Integer level1, Enchantment enchnt2, Integer level2) {
+ public static @NotNull ItemStack create(Material material, String name, List lore, Enchantment enchnt1, Integer level1, Enchantment enchnt2, Integer level2) {
ItemStack item = new ItemStack(material);
item.addUnsafeEnchantment(enchnt1, level1);
item.addUnsafeEnchantment(enchnt2, level2);
@@ -234,7 +238,7 @@ public static ItemStack create(Material material, String name, ArrayList
return item;
}
- public static ItemStack create(Material material, String name, ArrayList lore, Enchantment enchnt1, Integer level1, Enchantment enchnt2, Integer level2, Enchantment enchnt3, Integer level3) {
+ public static @NotNull ItemStack create(Material material, String name, List lore, Enchantment enchnt1, Integer level1, Enchantment enchnt2, Integer level2, Enchantment enchnt3, Integer level3) {
ItemStack item = new ItemStack(material);
item.addUnsafeEnchantment(enchnt1, level1);
item.addUnsafeEnchantment(enchnt2, level2);
@@ -247,7 +251,7 @@ public static ItemStack create(Material material, String name, ArrayList
return item;
}
- public static ItemStack createLeatherArmor(Material material, Color color) {
+ public static @NotNull ItemStack createLeatherArmor(Material material, Color color) {
ItemStack item = new ItemStack(material);
LeatherArmorMeta itemmeta = (LeatherArmorMeta)item.getItemMeta();
itemmeta.setColor(color);
@@ -256,7 +260,7 @@ public static ItemStack createLeatherArmor(Material material, Color color) {
return item;
}
- public static ItemStack createLeatherArmor(Material material, String name, Color color, ArrayList lore, Enchantment enchnt1, Integer level1) {
+ public static @NotNull ItemStack createLeatherArmor(Material material, String name, Color color, List lore, Enchantment enchnt1, Integer level1) {
ItemStack item = new ItemStack(material);
item.addUnsafeEnchantment(enchnt1, level1);
LeatherArmorMeta itemmeta = (LeatherArmorMeta)item.getItemMeta();
@@ -268,7 +272,7 @@ public static ItemStack createLeatherArmor(Material material, String name, Color
return item;
}
- public static ItemStack createLeatherArmor(Material material, String name, Color color, ArrayList lore, Enchantment enchnt1, Integer level1, Enchantment enchnt2, Integer level2) {
+ public static @NotNull ItemStack createLeatherArmor(Material material, String name, Color color, List lore, Enchantment enchnt1, Integer level1, Enchantment enchnt2, Integer level2) {
ItemStack item = new ItemStack(material);
item.addUnsafeEnchantment(enchnt1, level1);
item.addUnsafeEnchantment(enchnt2, level2);
@@ -281,7 +285,7 @@ public static ItemStack createLeatherArmor(Material material, String name, Color
return item;
}
- public static ItemStack createLeatherArmor(Material material, String name, Color color, ArrayList lore, Enchantment enchnt1, Integer level1, Enchantment enchnt2, Integer level2, Enchantment enchnt3, Integer level3) {
+ public static @NotNull ItemStack createLeatherArmor(Material material, String name, Color color, List lore, Enchantment enchnt1, Integer level1, Enchantment enchnt2, Integer level2, Enchantment enchnt3, Integer level3) {
ItemStack item = new ItemStack(material);
item.addUnsafeEnchantment(enchnt1, level1);
item.addUnsafeEnchantment(enchnt2, level2);
@@ -295,21 +299,7 @@ public static ItemStack createLeatherArmor(Material material, String name, Color
return item;
}
- public static ItemStack createPlayerHead(String name, String owner) {
- ItemStack item = XMaterial.PLAYER_HEAD.parseItem();
-
- if(item == null)
- return null;
-
- SkullMeta itemmeta = (SkullMeta)item.getItemMeta();
- itemmeta.setDisplayName(name);
- itemmeta.setOwner(owner);
- itemmeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
- item.setItemMeta(itemmeta);
- return item;
- }
-
- public static ItemStack createPlayerHead(String name, String owner, ArrayList lore) {
+ public static @Nullable ItemStack createPlayerHead(String name, String owner) {
ItemStack item = XMaterial.PLAYER_HEAD.parseItem();
if(item == null)
@@ -318,13 +308,12 @@ public static ItemStack createPlayerHead(String name, String owner, ArrayList lore) {
+ public static @Nullable ItemStack createPlayerHead(String name, String owner, List lore) {
ItemStack item = XMaterial.PLAYER_HEAD.parseItem();
if(item == null)
@@ -339,17 +328,20 @@ public static ItemStack createPlayerHead(String name, String owner, int amount,
return item;
}
- public static ItemStack edit(ItemStack item, Material material) {
+ @Contract("_, _ -> param1")
+ public static @NotNull ItemStack edit(@NotNull ItemStack item, Material material) {
item.setType(material);
return item;
}
- public static ItemStack edit(ItemStack item, int amount) {
+ @Contract("_, _ -> param1")
+ public static @NotNull ItemStack edit(@NotNull ItemStack item, int amount) {
item.setAmount(amount);
return item;
}
- public static ItemStack edit(ItemStack item, String name) {
+ @Contract("_, _ -> param1")
+ public static @NotNull ItemStack edit(@NotNull ItemStack item, String name) {
ItemMeta itemmeta = item.getItemMeta();
itemmeta.setDisplayName(name);
itemmeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
@@ -357,7 +349,8 @@ public static ItemStack edit(ItemStack item, String name) {
return item;
}
- public static ItemStack edit(ItemStack item, int amount, String name) {
+ @Contract("_, _, _ -> param1")
+ public static @NotNull ItemStack edit(@NotNull ItemStack item, int amount, String name) {
item.setAmount(amount);
ItemMeta itemmeta = item.getItemMeta();
itemmeta.setDisplayName(name);
@@ -366,7 +359,8 @@ public static ItemStack edit(ItemStack item, int amount, String name) {
return item;
}
- public static ItemStack edit(ItemStack item, ArrayList lore) {
+ @Contract("_, _ -> param1")
+ public static @NotNull ItemStack edit(@NotNull ItemStack item, List lore) {
ItemMeta itemmeta = item.getItemMeta();
itemmeta.setLore(lore);
itemmeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
@@ -374,7 +368,8 @@ public static ItemStack edit(ItemStack item, ArrayList lore) {
return item;
}
- public static ItemStack edit(ItemStack item, int amount, String name, ArrayList lore) {
+ @Contract("_, _, _, _ -> param1")
+ public static @NotNull ItemStack edit(@NotNull ItemStack item, int amount, String name, List lore) {
item.setAmount(amount);
ItemMeta itemmeta = item.getItemMeta();
itemmeta.setDisplayName(name);
@@ -384,7 +379,7 @@ public static ItemStack edit(ItemStack item, int amount, String name, ArrayList<
return item;
}
- public static ItemStack fromUniqueMaterialString(String materialString) {
+ public static @Nullable ItemStack fromUniqueMaterialString(String materialString) {
Material material = Material.matchMaterial(materialString);
if(material != null)
return XMaterial.matchXMaterial(material).parseItem();
@@ -396,7 +391,7 @@ public static ItemStack fromUniqueMaterialString(String materialString) {
return null;
}
- public static String getUniqueMaterialString(ItemStack item) {
+ public static @NotNull String getUniqueMaterialString(ItemStack item) {
if(CommonModule.getInstance().getVersionComponent().is_1_12())
return XMaterial.matchXMaterial(item).getId() + ":" + XMaterial.matchXMaterial(item).getData();
else
@@ -404,7 +399,7 @@ public static String getUniqueMaterialString(ItemStack item) {
}
- public static String getUniqueMaterialString(XMaterial material) {
+ public static @NotNull String getUniqueMaterialString(@NotNull XMaterial material) {
return getUniqueMaterialString(material.parseItem());
}
@@ -420,7 +415,7 @@ public static String getUniqueMaterialString(XMaterial[] materials) {
return s.toString();
}
- public static XMaterial convertStringToXMaterial(String materialString) {
+ public static @Nullable XMaterial convertStringToXMaterial(String materialString) {
XMaterial material;
if(XMaterial.matchXMaterial(materialString).isPresent())
@@ -448,8 +443,9 @@ public static BlockType convertXMaterialToBlockType(XMaterial material) {
return bt;
}
- public static String createStringFromItemList(ArrayList items) throws IllegalArgumentException {
- StringBuilder s = new StringBuilder(items.get(0));
+
+ public static @NotNull String createStringFromItemList(@NotNull List items) throws IllegalArgumentException {
+ StringBuilder s = new StringBuilder(items.getFirst());
for (int i = 1; i < items.size(); i++)
if(XMaterial.matchXMaterial(items.get(i)).isPresent()) {
@@ -461,14 +457,14 @@ public static String createStringFromItemList(ArrayList items) throws Il
return s.toString();
}
- public static ItemStack createCustomHeadTextureURL(String url, String name, ArrayList lore) {
+ public static ItemStack createCustomHeadTextureURL(String url, String name, List lore) {
byte[] encodedByteData = Base64.getEncoder().encode(String.format("{textures:{SKIN:{url:\"%s\"}}}", url).getBytes());
String encodedData = new String(encodedByteData);
return createCustomHeadBase64(encodedData, name, lore);
}
- public static ItemStack createCustomHeadBase64(String base64, String name, ArrayList lore) {
+ public static @Nullable ItemStack createCustomHeadBase64(String base64, String name, List lore) {
if (nonPlayerSkulls.containsKey(base64 + name + lore))
return nonPlayerSkulls.get(base64 + name + lore);
@@ -519,8 +515,7 @@ private static void mutateItemMeta(SkullMeta meta, String b64) {
}
-
- private static GameProfile makeProfile(String b64) {
+ private static @NotNull GameProfile makeProfile(@NotNull String b64) {
UUID id = new UUID(
b64.substring(b64.length() - 20).hashCode(),
b64.substring(b64.length() - 10).hashCode()
diff --git a/src/main/java/net/buildtheearth/utils/Utils.java b/src/main/java/net/buildtheearth/utils/Utils.java
index 150dbfa9..d1446a9d 100644
--- a/src/main/java/net/buildtheearth/utils/Utils.java
+++ b/src/main/java/net/buildtheearth/utils/Utils.java
@@ -1,16 +1,5 @@
package net.buildtheearth.utils;
-import com.google.common.io.ByteArrayDataOutput;
-import com.google.common.io.ByteStreams;
-import net.buildtheearth.BuildTeamTools;
-import net.buildtheearth.modules.network.NetworkModule;
-import org.bukkit.Bukkit;
-import org.bukkit.ChatColor;
-import org.bukkit.Material;
-import org.bukkit.World;
-import org.bukkit.entity.Player;
-import org.bukkit.inventory.ItemStack;
-
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@@ -44,17 +33,6 @@ public static String[] splitStringByLineLength(String input, int maxLineLength,
return lines.toArray(new String[0]);
}
- public static void sendPlayerToServer(Player player, String server) {
- if(NetworkModule.getInstance().getBuildTeam() == null
- || !NetworkModule.getInstance().getBuildTeam().isConnected())
- return;
-
- ByteArrayDataOutput out = ByteStreams.newDataOutput();
- out.writeUTF("Connect");
- out.writeUTF(server);
- player.sendPluginMessage(BuildTeamTools.getInstance(), "BungeeCord", out.toByteArray());
- }
-
public static Object pickRandom(Object[] array) {
if (array.length == 0)
return null;
@@ -66,11 +44,9 @@ public static Object pickRandom(Object[] array) {
/**
* Converts the given Time to a time string
*
- * @param p player for translation
* @param time time in Milliseconds
- * @return
*/
- public static String toDate(Player p, long time) {
+ public static String toDate(long time) {
String s = "";
int days = 0;
int hours = 0;
@@ -79,22 +55,21 @@ public static String toDate(Player p, long time) {
if (time > 86400000) { //Tage
days = (int) (time / 86400000);
- time = time - (86400000 * days);
+ time = time - (86400000L * days);
}
if (time > 3600000) { //Stunden
hours = (int) (time / 3600000);
- time = time - (3600000 * hours);
+ time = time - (3600000L * hours);
}
if (time > 60000) { //Minuten
minutes = (int) (time / 60000);
- time = time - (60000 * minutes);
+ time = time - (60000L * minutes);
}
if (time > 1000) { //Sekunden
seconds = (int) (time / 1000);
- time = time - (1000 * seconds);
}
if (days > 0) {
@@ -103,13 +78,13 @@ public static String toDate(Player p, long time) {
else
s = s + days + " Days, ";
}
- if (hours > 0 | days > 0) {
+ if (hours > 0 || days > 0) {
if (hours == 1)
s = s + hours + " Hour";
else
s = s + hours + " Hours";
}
- if ((minutes > 0 | hours > 0) & days == 0) {
+ if ((minutes > 0 || hours > 0) && days == 0) {
if (hours > 0)
s = s + ", ";
@@ -118,7 +93,7 @@ public static String toDate(Player p, long time) {
else
s = s + minutes + " Minutes";
}
- if ((seconds > 0 | minutes > 0) & hours == 0 & days == 0) {
+ if ((seconds > 0 || minutes > 0) && hours == 0 && days == 0) {
if (minutes > 0)
s = s + ", ";
diff --git a/src/main/java/net/buildtheearth/utils/io/ConfigPaths.java b/src/main/java/net/buildtheearth/utils/io/ConfigPaths.java
index c8b7a153..f6421547 100644
--- a/src/main/java/net/buildtheearth/utils/io/ConfigPaths.java
+++ b/src/main/java/net/buildtheearth/utils/io/ConfigPaths.java
@@ -25,13 +25,23 @@ public static class Navigation {
// Navigator.MainMenuItems
private static final String NAVIGATOR_MAIN_MENU = "main-menu-items.";
private static final String BUILD_ITEM = NAVIGATOR_MAIN_MENU + "build-item.";
- public static final String BUILD_ITEM_ENABLED = BUILD_ITEM + "build-enabled";
- public static final String BUILD_ITEM_ACTION = BUILD_ITEM + "build-action";
+ public static final String BUILD_ITEM_ENABLED = BUILD_ITEM + "enabled";
+ public static final String BUILD_ITEM_ACTION = BUILD_ITEM + "action";
private static final String TUTORIALS_ITEM = NAVIGATOR_MAIN_MENU + "tutorial-item.";
- public static final String TUTORIALS_ITEM_ENABLED = TUTORIALS_ITEM + "tutorial-enabled";
- public static final String TUTORIALS_ITEM_ACTION = TUTORIALS_ITEM + "tutorial-action";
+ public static final String TUTORIALS_ITEM_ENABLED = TUTORIALS_ITEM + "enabled";
+ public static final String TUTORIALS_ITEM_ACTION = TUTORIALS_ITEM + "action";
+ private static final String PLOTSYSTEM_ITEM = NAVIGATOR_MAIN_MENU + "plotsystem-item.";
+ public static final String PLOTSYSTEM_ITEM_ENABLED = PLOTSYSTEM_ITEM + "enabled";
+ public static final String PLOTSYSTEM_ITEM_ACTION = PLOTSYSTEM_ITEM + "action";
+
+ private static final String EXPLORE_ITEM = NAVIGATOR_MAIN_MENU + "explore-item.";
+ public static final String EXPLORE_ITEM_ENABLED = EXPLORE_ITEM + "enabled";
+
+ // Navigator.Warps
+ private static final String NAVIGATOR_WARPS = "warps.";
+ public static final String WARPS_GROUP_SORTING_MODE = NAVIGATOR_WARPS + "sorting-mode";
}
public static class PlotSystem {
diff --git a/src/main/resources/modules/navigation/config.yml b/src/main/resources/modules/navigation/config.yml
index 9ee3f9ee..0eed449b 100644
--- a/src/main/resources/modules/navigation/config.yml
+++ b/src/main/resources/modules/navigation/config.yml
@@ -8,7 +8,6 @@
# | [Contacts - Discord] BuildTheEarth Staff Discord, @minefact
# ----------------------------------------------------------------------------------------------
-
# Configures the navigator item in the players hotbar
navigator-hotbar-item:
# Enables or disables the navigator hotbar item [true|false]
@@ -16,22 +15,37 @@ navigator-hotbar-item:
# The hotbar slot into which the navigator item should be placed
nav-slot: 0
+# ACTION - Below you can define actions for some items. There is a comment when a default action exists, else it will error out.
+# Command & Message - just specify it like you would do it in the chat. E.g.: /tp 100 50 100
+# Transfer - Transfer the player to the specified team. E.g.: transfer:
+# Switch - Switch the player to the specified server (on the same proxy). E.g.: switch:>
+
# Specifies which menu items should be enabled
main-menu-items:
# Configures the build item inside the navigator
build-item:
# Enables or disables the build item inside the navigator [true|false]
- build-enabled: true
- # (Optional) Execute a custom command or send a message when the build item is clicked [/command|message]
- build-action: /command
+ enabled: false
+ action: /command
+ plotsystem-item:
+ # Enables or disables the Plot System item inside the navigator [true|false]
+ enabled: true
+ action: /command
+ explore-item:
+ # Enables or disables the explore item inside the navigator [true|false]
+ # Left click opens BTT Warp System, right click Buildteam Explore Menu
+ enabled: true
# Configures the tutorial item inside the navigator
tutorial-item:
# Enables or disables the tutorial item inside the navigator [true|false]
- tutorial-enabled: false
- # (Optional) Execute a custom command or send a message when the tutorial item is clicked [/command|message]
- tutorial-action: /command
-
+ enabled: false
+ # (Optional) If nothing is set/changed here, it will open up the btt tutorial menu
+ action: /command
+warps:
+ # The order in which the warps should be displayed in the navigator
+ # Possible values: default (same as the creation order), name
+ sorting-mode: default
# NOTE: Do not change
config-version: 1.4
\ No newline at end of file
diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml
index d4e47846..dece42e8 100644
--- a/src/main/resources/plugin.yml
+++ b/src/main/resources/plugin.yml
@@ -2,13 +2,14 @@ name: BuildTeamTools
main: net.buildtheearth.BuildTeamTools
api-version: 1.13
version: 0.1.3-alpha
-author: MineFact, frikandelworst, George112n, ELgamer, SirJodelstein
-softdepend: [WorldEdit, HeadDatabase]
+author: MineFact, frikandelworst, George112n, ELgamer, SirJodelstein, Zoriot
+softdepend: [WorldEdit, HeadDatabase, PlotSystem-Terra]
+
commands:
- buildteam:
- description: Main command of the Build Team plugin.
- usage: /buildteam
- aliases: [btt, buildteamtools]
+ buildteamtools:
+ description: Main command of the Build Team Tools plugin.
+ usage: /buildteamtools
+ aliases: [btt]
generate:
description: Allows usage of the Generator Tool.
usage: /generate
@@ -21,9 +22,10 @@ commands:
description: Command for managing warps.
usage: /warp
aliases: [warps]
- temporary:
- description: Temporary test command.
- usage: /temporary
+ warpsbt:
+ description: Opens the warp menu for the specified BuildTeam
+ usage: /warpsbt
+ aliases: [ wbt ]
kml:
description: kml pasting and parsing
usage: /kml
@@ -44,6 +46,10 @@ commands:
usage: /blockpalette [filter|menu|filter ...]
aliases: [bp, blocks]
permission: blockpalette.use
+ buildteam:
+ description: Sends the player to the specified BuildTeam
+ usage: /buildteam
+ aliases: [bt]
permissions:
blockpalette.use:
description: Allows players to use /blockpalette