result.put(flag, section.getLong(key)));
}
diff --git a/src/main/java/world/bentobox/bentobox/database/objects/adapters/package-info.java b/src/main/java/world/bentobox/bentobox/database/objects/adapters/package-info.java
new file mode 100644
index 000000000..e5a955634
--- /dev/null
+++ b/src/main/java/world/bentobox/bentobox/database/objects/adapters/package-info.java
@@ -0,0 +1,6 @@
+/**
+ * These adapters are used by the YAML database, which is now only used
+ * for configuration storage and management. For the GSON adapters used
+ * by the "real" databases, see {@link world.bentobox.bentobox.database.json.adapters}
+ */
+package world.bentobox.bentobox.database.objects.adapters;
\ No newline at end of file
diff --git a/src/main/java/world/bentobox/bentobox/database/objects/package-info.java b/src/main/java/world/bentobox/bentobox/database/objects/package-info.java
new file mode 100644
index 000000000..dee4be6e1
--- /dev/null
+++ b/src/main/java/world/bentobox/bentobox/database/objects/package-info.java
@@ -0,0 +1,11 @@
+/**
+ * These are the data objects and adapters that BentoBox uses to store its data.
+ *
+ *
+ * Key objects are Island and Players. BentoBox loads all Island objects on startup into RAM. Players are loaded
+ * as and when required.
+ *
+ * @author tastybento
+ *
+ */
+package world.bentobox.bentobox.database.objects;
\ No newline at end of file
diff --git a/src/main/java/world/bentobox/bentobox/database/package-info.java b/src/main/java/world/bentobox/bentobox/database/package-info.java
new file mode 100644
index 000000000..d8873e206
--- /dev/null
+++ b/src/main/java/world/bentobox/bentobox/database/package-info.java
@@ -0,0 +1,21 @@
+/**
+ * Provides an abstract database for storing Java POJOs
+ * and also YAML config files.
+ *
+ *
+ * The database supports concrete implementations for JSON flat file, MongoDB, MySQL, PostgreSQL, SQLite
+ * and the ability to transition between them.
+ *
+ *
+ * Storage of POJOs is done via GSON, i.e, the object is serialized and then stored. Each data object must
+ * implement the DataObject interface, which requires a uniqueId field. This is what is used for indexing
+ * and finding.
+ *
+ *
+ * Performance with JSON is generally very good, and the other databases are really there for concurrent usage
+ * by other applications.
+ *
+ * @author tastybento
+ *
+ */
+package world.bentobox.bentobox.database;
\ No newline at end of file
diff --git a/src/main/java/world/bentobox/bentobox/database/sql/SQLConfiguration.java b/src/main/java/world/bentobox/bentobox/database/sql/SQLConfiguration.java
index baafdad8b..373d4f04b 100644
--- a/src/main/java/world/bentobox/bentobox/database/sql/SQLConfiguration.java
+++ b/src/main/java/world/bentobox/bentobox/database/sql/SQLConfiguration.java
@@ -18,7 +18,7 @@ public class SQLConfiguration {
private String loadObjectsSQL;
private String renameTableSQL;
private final String tableName;
- private boolean renameRequired;
+ private final boolean renameRequired;
private final String oldTableName;
public SQLConfiguration(BentoBox plugin, Class type) {
diff --git a/src/main/java/world/bentobox/bentobox/database/sql/SQLDatabaseConnector.java b/src/main/java/world/bentobox/bentobox/database/sql/SQLDatabaseConnector.java
index bc4383fac..3770062fc 100644
--- a/src/main/java/world/bentobox/bentobox/database/sql/SQLDatabaseConnector.java
+++ b/src/main/java/world/bentobox/bentobox/database/sql/SQLDatabaseConnector.java
@@ -15,7 +15,7 @@ import world.bentobox.bentobox.database.DatabaseConnector;
public abstract class SQLDatabaseConnector implements DatabaseConnector {
protected String connectionUrl;
- private DatabaseConnectionSettingsImpl dbSettings;
+ private final DatabaseConnectionSettingsImpl dbSettings;
protected static Connection connection = null;
protected static Set> types = new HashSet<>();
diff --git a/src/main/java/world/bentobox/bentobox/database/sql/sqlite/SQLiteDatabase.java b/src/main/java/world/bentobox/bentobox/database/sql/sqlite/SQLiteDatabase.java
index ff599734b..327bdb657 100644
--- a/src/main/java/world/bentobox/bentobox/database/sql/sqlite/SQLiteDatabase.java
+++ b/src/main/java/world/bentobox/bentobox/database/sql/sqlite/SQLiteDatabase.java
@@ -10,7 +10,7 @@ import world.bentobox.bentobox.database.DatabaseSetup;
*/
public class SQLiteDatabase implements DatabaseSetup {
- private SQLiteDatabaseConnector connector = new SQLiteDatabaseConnector(BentoBox.getInstance());
+ private final SQLiteDatabaseConnector connector = new SQLiteDatabaseConnector(BentoBox.getInstance());
@Override
public AbstractDatabaseHandler getHandler(Class dataObjectClass) {
diff --git a/src/main/java/world/bentobox/bentobox/database/transition/TransitionDatabaseHandler.java b/src/main/java/world/bentobox/bentobox/database/transition/TransitionDatabaseHandler.java
index 325837f99..a3bb314bd 100644
--- a/src/main/java/world/bentobox/bentobox/database/transition/TransitionDatabaseHandler.java
+++ b/src/main/java/world/bentobox/bentobox/database/transition/TransitionDatabaseHandler.java
@@ -19,8 +19,8 @@ import world.bentobox.bentobox.database.AbstractDatabaseHandler;
*/
public class TransitionDatabaseHandler extends AbstractDatabaseHandler {
- private AbstractDatabaseHandler fromHandler;
- private AbstractDatabaseHandler toHandler;
+ private final AbstractDatabaseHandler fromHandler;
+ private final AbstractDatabaseHandler toHandler;
/**
* Constructor
diff --git a/src/main/java/world/bentobox/bentobox/database/yaml/YamlDatabase.java b/src/main/java/world/bentobox/bentobox/database/yaml/YamlDatabase.java
index 597a24384..4df6fb9cf 100644
--- a/src/main/java/world/bentobox/bentobox/database/yaml/YamlDatabase.java
+++ b/src/main/java/world/bentobox/bentobox/database/yaml/YamlDatabase.java
@@ -6,7 +6,7 @@ import world.bentobox.bentobox.database.DatabaseSetup;
public class YamlDatabase implements DatabaseSetup {
- private YamlDatabaseConnector connector = new YamlDatabaseConnector(BentoBox.getInstance());
+ private final YamlDatabaseConnector connector = new YamlDatabaseConnector(BentoBox.getInstance());
/**
* Get the config
diff --git a/src/main/java/world/bentobox/bentobox/database/yaml/YamlDatabaseConnector.java b/src/main/java/world/bentobox/bentobox/database/yaml/YamlDatabaseConnector.java
index c7a132965..aacc05b97 100644
--- a/src/main/java/world/bentobox/bentobox/database/yaml/YamlDatabaseConnector.java
+++ b/src/main/java/world/bentobox/bentobox/database/yaml/YamlDatabaseConnector.java
@@ -151,12 +151,9 @@ public class YamlDatabaseConnector implements DatabaseConnector {
for (Entry e : commentMap.entrySet()) {
if (nextLine.contains(e.getKey())) {
// We want the comment to start at the same level as the entry
- StringBuilder commentLine = new StringBuilder();
- for (int i = 0; i < nextLine.indexOf(e.getKey()); i++){
- commentLine.append(' ');
- }
- commentLine.append(e.getValue());
- nextLine = commentLine.toString();
+ String commentLine = " ".repeat(Math.max(0, nextLine.indexOf(e.getKey()))) +
+ e.getValue();
+ nextLine = commentLine;
break;
}
}
@@ -191,11 +188,11 @@ public class YamlDatabaseConnector implements DatabaseConnector {
@NonNull
public String getUniqueId(String tableName) {
UUID uuid = UUID.randomUUID();
- File file = new File(dataFolder, tableName + File.separator + uuid.toString() + YML);
+ File file = new File(dataFolder, tableName + File.separator + uuid + YML);
int limit = 0;
while (file.exists() && limit++ < MAX_LOOPS) {
uuid = UUID.randomUUID();
- file = new File(dataFolder, tableName + File.separator + uuid.toString() + YML);
+ file = new File(dataFolder, tableName + File.separator + uuid + YML);
}
return uuid.toString();
}
diff --git a/src/main/java/world/bentobox/bentobox/database/yaml/YamlDatabaseHandler.java b/src/main/java/world/bentobox/bentobox/database/yaml/YamlDatabaseHandler.java
index 6cad6bd8d..6c9d56dd5 100644
--- a/src/main/java/world/bentobox/bentobox/database/yaml/YamlDatabaseHandler.java
+++ b/src/main/java/world/bentobox/bentobox/database/yaml/YamlDatabaseHandler.java
@@ -534,7 +534,7 @@ public class YamlDatabaseHandler extends AbstractDatabaseHandler {
}
private void setComment(@NonNull String comment, @NonNull YamlConfiguration config, @NonNull Map yamlComments, @NonNull String parent) {
- String random = "comment-" + UUID.randomUUID().toString();
+ String random = "comment-" + UUID.randomUUID();
// Store placeholder
config.set(parent + random, " ");
// Create comment
@@ -554,20 +554,20 @@ public class YamlDatabaseHandler extends AbstractDatabaseHandler {
}
// UUID has it's own serialization, that is not picked up automatically
if (object instanceof UUID) {
- return ((UUID)object).toString();
+ return object.toString();
}
// Only the world name is needed for worlds
- if (object instanceof World) {
- return ((World)object).getName();
+ if (object instanceof World w) {
+ return w.getName();
}
// Location
- if (object instanceof Location) {
- return Util.getStringLocation((Location)object);
+ if (object instanceof Location l) {
+ return Util.getStringLocation(l);
}
// Enums
- if (object instanceof Enum) {
+ if (object instanceof Enum> e) {
//Custom enums are a child of the Enum class. Just get the names of each one.
- return ((Enum>)object).name();
+ return e.name();
}
return object;
}
diff --git a/src/main/java/world/bentobox/bentobox/hooks/DynmapHook.java b/src/main/java/world/bentobox/bentobox/hooks/DynmapHook.java
index 3eb8c5347..a14cbaf93 100644
--- a/src/main/java/world/bentobox/bentobox/hooks/DynmapHook.java
+++ b/src/main/java/world/bentobox/bentobox/hooks/DynmapHook.java
@@ -24,7 +24,7 @@ public class DynmapHook extends Hook {
private MarkerAPI markerAPI;
@NonNull
- private Map<@NonNull GameModeAddon, @NonNull MarkerSet> markerSets;
+ private final Map<@NonNull GameModeAddon, @NonNull MarkerSet> markerSets;
public DynmapHook() {
super("dynmap", Material.FILLED_MAP);
diff --git a/src/main/java/world/bentobox/bentobox/hooks/LangUtilsHook.java b/src/main/java/world/bentobox/bentobox/hooks/LangUtilsHook.java
index 2d5aa10ae..d7e630f16 100644
--- a/src/main/java/world/bentobox/bentobox/hooks/LangUtilsHook.java
+++ b/src/main/java/world/bentobox/bentobox/hooks/LangUtilsHook.java
@@ -262,31 +262,29 @@ public class LangUtilsHook extends Hook {
if (hooked) {
return LanguageHelper.getPotionName(potionType, getUserLocale(user));
}
- switch (potionType) {
- case UNCRAFTABLE: return "Uncraftable Potion";
- case WATER: return "Water Bottle";
- case MUNDANE: return "Mundane Potion";
- case THICK: return "Thick Potion";
- case AWKWARD: return "Awkward Potion";
- case NIGHT_VISION: return "Potion of Night Vision";
- case INVISIBILITY: return "Potion of Invisibility";
- case JUMP: return "Potion of Leaping";
- case FIRE_RESISTANCE: return "Potion of Fire Resistance";
- case SPEED: return "Potion of Swiftness";
- case SLOWNESS: return "Potion of Slowness";
- case WATER_BREATHING: return "Potion of Water Breathing";
- case INSTANT_HEAL: return "Potion of Healing";
- case INSTANT_DAMAGE: return "Potion of Harming";
- case POISON: return "Potion of Poison";
- case REGEN: return "Potion of Regeneration";
- case STRENGTH: return "Potion of Strength";
- case WEAKNESS: return "Potion of Weakness";
- case LUCK: return "Potion of Luck";
- case TURTLE_MASTER: return "Potion of the Turtle Master";
- case SLOW_FALLING: return "Potion of Slow Falling";
- default:
- return Util.prettifyText(potionType.name());
- }
+ return switch (potionType) {
+ case UNCRAFTABLE -> "Uncraftable Potion";
+ case WATER -> "Water Bottle";
+ case MUNDANE -> "Mundane Potion";
+ case THICK -> "Thick Potion";
+ case AWKWARD -> "Awkward Potion";
+ case NIGHT_VISION -> "Potion of Night Vision";
+ case INVISIBILITY -> "Potion of Invisibility";
+ case JUMP -> "Potion of Leaping";
+ case FIRE_RESISTANCE -> "Potion of Fire Resistance";
+ case SPEED -> "Potion of Swiftness";
+ case SLOWNESS -> "Potion of Slowness";
+ case WATER_BREATHING -> "Potion of Water Breathing";
+ case INSTANT_HEAL -> "Potion of Healing";
+ case INSTANT_DAMAGE -> "Potion of Harming";
+ case POISON -> "Potion of Poison";
+ case REGEN -> "Potion of Regeneration";
+ case STRENGTH -> "Potion of Strength";
+ case WEAKNESS -> "Potion of Weakness";
+ case LUCK -> "Potion of Luck";
+ case TURTLE_MASTER -> "Potion of the Turtle Master";
+ case SLOW_FALLING -> "Potion of Slow Falling";
+ };
}
@@ -301,31 +299,29 @@ public class LangUtilsHook extends Hook {
if (hooked) {
return LanguageHelper.getSplashPotionName(potionType, getUserLocale(user));
}
- switch (potionType) {
- case UNCRAFTABLE: return "Splash Uncraftable Potion";
- case WATER: return "Splash Water Bottle";
- case MUNDANE: return "Mundane Splash Potion";
- case THICK: return "Thick Splash Potion";
- case AWKWARD: return "Awkward Splash Potion";
- case NIGHT_VISION: return "Splash Potion of Night Vision";
- case INVISIBILITY: return "Splash Potion of Invisibility";
- case JUMP: return "Splash Potion of Leaping";
- case FIRE_RESISTANCE: return "Splash Potion of Fire Resistance";
- case SPEED: return "Splash Potion of Swiftness";
- case SLOWNESS: return "Splash Potion of Slowness";
- case WATER_BREATHING: return "Splash Potion of Water Breathing";
- case INSTANT_HEAL: return "Splash Potion of Healing";
- case INSTANT_DAMAGE: return "Splash Potion of Harming";
- case POISON: return "Splash Potion of Poison";
- case REGEN: return "Splash Potion of Regeneration";
- case STRENGTH: return "Splash Potion of Strength";
- case WEAKNESS: return "Splash Potion of Weakness";
- case LUCK: return "Splash Potion of Luck";
- case TURTLE_MASTER: return "Splash Potion of the Turtle Master";
- case SLOW_FALLING: return "Splash Potion of Slow Falling";
- default:
- return Util.prettifyText(potionType.name());
- }
+ return switch (potionType) {
+ case UNCRAFTABLE -> "Splash Uncraftable Potion";
+ case WATER -> "Splash Water Bottle";
+ case MUNDANE -> "Mundane Splash Potion";
+ case THICK -> "Thick Splash Potion";
+ case AWKWARD -> "Awkward Splash Potion";
+ case NIGHT_VISION -> "Splash Potion of Night Vision";
+ case INVISIBILITY -> "Splash Potion of Invisibility";
+ case JUMP -> "Splash Potion of Leaping";
+ case FIRE_RESISTANCE -> "Splash Potion of Fire Resistance";
+ case SPEED -> "Splash Potion of Swiftness";
+ case SLOWNESS -> "Splash Potion of Slowness";
+ case WATER_BREATHING -> "Splash Potion of Water Breathing";
+ case INSTANT_HEAL -> "Splash Potion of Healing";
+ case INSTANT_DAMAGE -> "Splash Potion of Harming";
+ case POISON -> "Splash Potion of Poison";
+ case REGEN -> "Splash Potion of Regeneration";
+ case STRENGTH -> "Splash Potion of Strength";
+ case WEAKNESS -> "Splash Potion of Weakness";
+ case LUCK -> "Splash Potion of Luck";
+ case TURTLE_MASTER -> "Splash Potion of the Turtle Master";
+ case SLOW_FALLING -> "Splash Potion of Slow Falling";
+ };
}
/**
@@ -339,31 +335,29 @@ public class LangUtilsHook extends Hook {
if (hooked) {
return LanguageHelper.getLingeringPotionName(potionType, getUserLocale(user));
}
- switch (potionType) {
- case UNCRAFTABLE: return "Lingering Uncraftable Potion";
- case WATER: return "Lingering Water Bottle";
- case MUNDANE: return "Mundane Lingering Potion";
- case THICK: return "Thick Lingering Potion";
- case AWKWARD: return "Awkward Lingering Potion";
- case NIGHT_VISION: return "Lingering Potion of Night Vision";
- case INVISIBILITY: return "Lingering Potion of Invisibility";
- case JUMP: return "Lingering Potion of Leaping";
- case FIRE_RESISTANCE: return "Lingering Potion of Fire Resistance";
- case SPEED: return "Lingering Potion of Swiftness";
- case SLOWNESS: return "Lingering Potion of Slowness";
- case WATER_BREATHING: return "Lingering Potion of Water Breathing";
- case INSTANT_HEAL: return "Lingering Potion of Healing";
- case INSTANT_DAMAGE: return "Lingering Potion of Harming";
- case POISON: return "Lingering Potion of Poison";
- case REGEN: return "Lingering Potion of Regeneration";
- case STRENGTH: return "Lingering Potion of Strength";
- case WEAKNESS: return "Lingering Potion of Weakness";
- case LUCK: return "Lingering Potion of Luck";
- case TURTLE_MASTER: return "Lingering Potion of the Turtle Master";
- case SLOW_FALLING: return "Lingering Potion of Slow Falling";
- default:
- return Util.prettifyText(potionType.name());
- }
+ return switch (potionType) {
+ case UNCRAFTABLE -> "Lingering Uncraftable Potion";
+ case WATER -> "Lingering Water Bottle";
+ case MUNDANE -> "Mundane Lingering Potion";
+ case THICK -> "Thick Lingering Potion";
+ case AWKWARD -> "Awkward Lingering Potion";
+ case NIGHT_VISION -> "Lingering Potion of Night Vision";
+ case INVISIBILITY -> "Lingering Potion of Invisibility";
+ case JUMP -> "Lingering Potion of Leaping";
+ case FIRE_RESISTANCE -> "Lingering Potion of Fire Resistance";
+ case SPEED -> "Lingering Potion of Swiftness";
+ case SLOWNESS -> "Lingering Potion of Slowness";
+ case WATER_BREATHING -> "Lingering Potion of Water Breathing";
+ case INSTANT_HEAL -> "Lingering Potion of Healing";
+ case INSTANT_DAMAGE -> "Lingering Potion of Harming";
+ case POISON -> "Lingering Potion of Poison";
+ case REGEN -> "Lingering Potion of Regeneration";
+ case STRENGTH -> "Lingering Potion of Strength";
+ case WEAKNESS -> "Lingering Potion of Weakness";
+ case LUCK -> "Lingering Potion of Luck";
+ case TURTLE_MASTER -> "Lingering Potion of the Turtle Master";
+ case SLOW_FALLING -> "Lingering Potion of Slow Falling";
+ };
}
/**
@@ -377,31 +371,27 @@ public class LangUtilsHook extends Hook {
if (hooked) {
return LanguageHelper.getTippedArrowName(potionType, getUserLocale(user));
}
- switch (potionType) {
- case UNCRAFTABLE: return "Uncraftable Tipped Arrow";
- case WATER: return "Arrow of Splashing";
- case MUNDANE:
- case THICK:
- case AWKWARD: return "Tipped Arrow";
- case NIGHT_VISION: return "Arrow of Night Vision";
- case INVISIBILITY: return "Arrow of Invisibility";
- case JUMP: return "Arrow of Leaping";
- case FIRE_RESISTANCE: return "Arrow of Fire Resistance";
- case SPEED: return "Arrow of Swiftness";
- case SLOWNESS: return "Arrow of Slowness";
- case WATER_BREATHING: return "Arrow of Water Breathing";
- case INSTANT_HEAL: return "Arrow of Healing";
- case INSTANT_DAMAGE: return "Arrow of Harming";
- case POISON: return "Arrow of Poison";
- case REGEN: return "Arrow of Regeneration";
- case STRENGTH: return "Arrow of Strength";
- case WEAKNESS: return "Arrow of Weakness";
- case LUCK: return "Arrow of Luck";
- case TURTLE_MASTER: return "Arrow of the Turtle Master";
- case SLOW_FALLING: return "Arrow of Slow Falling";
- default:
- return Util.prettifyText(potionType.name());
- }
+ return switch (potionType) {
+ case UNCRAFTABLE -> "Uncraftable Tipped Arrow";
+ case WATER -> "Arrow of Splashing";
+ case MUNDANE, THICK, AWKWARD -> "Tipped Arrow";
+ case NIGHT_VISION -> "Arrow of Night Vision";
+ case INVISIBILITY -> "Arrow of Invisibility";
+ case JUMP -> "Arrow of Leaping";
+ case FIRE_RESISTANCE -> "Arrow of Fire Resistance";
+ case SPEED -> "Arrow of Swiftness";
+ case SLOWNESS -> "Arrow of Slowness";
+ case WATER_BREATHING -> "Arrow of Water Breathing";
+ case INSTANT_HEAL -> "Arrow of Healing";
+ case INSTANT_DAMAGE -> "Arrow of Harming";
+ case POISON -> "Arrow of Poison";
+ case REGEN -> "Arrow of Regeneration";
+ case STRENGTH -> "Arrow of Strength";
+ case WEAKNESS -> "Arrow of Weakness";
+ case LUCK -> "Arrow of Luck";
+ case TURTLE_MASTER -> "Arrow of the Turtle Master";
+ case SLOW_FALLING -> "Arrow of Slow Falling";
+ };
}
/**
@@ -620,22 +610,22 @@ public class LangUtilsHook extends Hook {
// The description of the music record is the same in any language,
// so directly output it here.
- switch (material) {
- case MUSIC_DISC_13 : return "C418 - 13";
- case MUSIC_DISC_CAT : return "C418 - cat";
- case MUSIC_DISC_BLOCKS : return "C418 - blocks";
- case MUSIC_DISC_CHIRP : return "C418 - chirp";
- case MUSIC_DISC_FAR : return "C418 - far";
- case MUSIC_DISC_MALL : return "C418 - mall";
- case MUSIC_DISC_MELLOHI : return "C418 - mellohi";
- case MUSIC_DISC_STAL : return "C418 - stal";
- case MUSIC_DISC_STRAD : return "C418 - strad";
- case MUSIC_DISC_WARD : return "C418 - ward";
- case MUSIC_DISC_11 : return "C418 - 11";
- case MUSIC_DISC_WAIT : return "C418 - wait";
- case MUSIC_DISC_PIGSTEP : return "Lena Raine - Pigstep";
- default : return null;
- }
+ return switch (material) {
+ case MUSIC_DISC_13 -> "C418 - 13";
+ case MUSIC_DISC_CAT -> "C418 - cat";
+ case MUSIC_DISC_BLOCKS -> "C418 - blocks";
+ case MUSIC_DISC_CHIRP -> "C418 - chirp";
+ case MUSIC_DISC_FAR -> "C418 - far";
+ case MUSIC_DISC_MALL -> "C418 - mall";
+ case MUSIC_DISC_MELLOHI -> "C418 - mellohi";
+ case MUSIC_DISC_STAL -> "C418 - stal";
+ case MUSIC_DISC_STRAD -> "C418 - strad";
+ case MUSIC_DISC_WARD -> "C418 - ward";
+ case MUSIC_DISC_11 -> "C418 - 11";
+ case MUSIC_DISC_WAIT -> "C418 - wait";
+ case MUSIC_DISC_PIGSTEP -> "Lena Raine - Pigstep";
+ default -> null;
+ };
}
}
diff --git a/src/main/java/world/bentobox/bentobox/hooks/package-info.java b/src/main/java/world/bentobox/bentobox/hooks/package-info.java
new file mode 100644
index 000000000..86ce95aae
--- /dev/null
+++ b/src/main/java/world/bentobox/bentobox/hooks/package-info.java
@@ -0,0 +1,7 @@
+/**
+ * This is where hooks into other plugins go.
+ *
+ * @author Poslovitch
+ *
+ */
+package world.bentobox.bentobox.hooks;
\ No newline at end of file
diff --git a/src/main/java/world/bentobox/bentobox/hooks/placeholders/PlaceholderAPIHook.java b/src/main/java/world/bentobox/bentobox/hooks/placeholders/PlaceholderAPIHook.java
index 91177291e..7b3b174fd 100644
--- a/src/main/java/world/bentobox/bentobox/hooks/placeholders/PlaceholderAPIHook.java
+++ b/src/main/java/world/bentobox/bentobox/hooks/placeholders/PlaceholderAPIHook.java
@@ -26,7 +26,7 @@ import world.bentobox.bentobox.api.placeholders.placeholderapi.BentoBoxPlacehold
public class PlaceholderAPIHook extends PlaceholderHook {
private BentoBoxPlaceholderExpansion bentoboxExpansion;
- private Map addonsExpansions;
+ private final Map addonsExpansions;
private final Set bentoBoxPlaceholders;
private final Map> addonPlaceholders;
diff --git a/src/main/java/world/bentobox/bentobox/listeners/BannedCommands.java b/src/main/java/world/bentobox/bentobox/listeners/BannedCommands.java
index e1828f93e..c9dc27be1 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/BannedCommands.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/BannedCommands.java
@@ -19,7 +19,7 @@ import world.bentobox.bentobox.lists.Flags;
*/
public class BannedCommands implements Listener {
- private BentoBox plugin;
+ private final BentoBox plugin;
/**
* @param plugin - plugin
diff --git a/src/main/java/world/bentobox/bentobox/listeners/BlockEndDragon.java b/src/main/java/world/bentobox/bentobox/listeners/BlockEndDragon.java
index 380264da7..8c219a353 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/BlockEndDragon.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/BlockEndDragon.java
@@ -18,7 +18,7 @@ import world.bentobox.bentobox.lists.Flags;
public class BlockEndDragon implements Listener {
- private BentoBox plugin;
+ private final BentoBox plugin;
public BlockEndDragon(@NonNull BentoBox plugin) {
this.plugin = plugin;
diff --git a/src/main/java/world/bentobox/bentobox/listeners/DeathListener.java b/src/main/java/world/bentobox/bentobox/listeners/DeathListener.java
index 22edcd57c..5cc4c73dc 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/DeathListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/DeathListener.java
@@ -15,7 +15,7 @@ import world.bentobox.bentobox.BentoBox;
*/
public class DeathListener implements Listener {
- private BentoBox plugin;
+ private final BentoBox plugin;
public DeathListener(@NonNull BentoBox plugin) {
super();
diff --git a/src/main/java/world/bentobox/bentobox/listeners/JoinLeaveListener.java b/src/main/java/world/bentobox/bentobox/listeners/JoinLeaveListener.java
index bac2aa6b1..e1f28b671 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/JoinLeaveListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/JoinLeaveListener.java
@@ -32,8 +32,8 @@ import world.bentobox.bentobox.util.Util;
public class JoinLeaveListener implements Listener {
- private BentoBox plugin;
- private PlayersManager players;
+ private final BentoBox plugin;
+ private final PlayersManager players;
/**
* @param plugin - plugin object
@@ -80,7 +80,7 @@ public class JoinLeaveListener implements Listener {
players.setPlayerName(user);
players.save(playerUUID);
} else {
- plugin.logWarning("Player that just logged in has no name! " + playerUUID.toString());
+ plugin.logWarning("Player that just logged in has no name! " + playerUUID);
}
// If mobs have to be removed when a player joins, then wipe all the mobs on his island.
@@ -126,9 +126,8 @@ public class JoinLeaveListener implements Listener {
// - abort on logout is false
// - abort on logout is true && user is online
if (!plugin.getIWM().isCreateIslandOnFirstLoginAbortOnLogout(w) || user.isOnline()){
- plugin.getIWM().getAddon(w).ifPresent(addon -> addon.getPlayerCommand()
- .map(command -> command.getSubCommand("create").orElse(null))
- .ifPresent(command -> command.execute(user, "create", Collections.singletonList(BlueprintsManager.DEFAULT_BUNDLE_NAME))));
+ plugin.getIWM().getAddon(w).flatMap(addon -> addon.getPlayerCommand().flatMap(command -> command.getSubCommand("create")))
+ .ifPresent(command -> command.execute(user, "create", Collections.singletonList(BlueprintsManager.DEFAULT_BUNDLE_NAME)));
}
};
diff --git a/src/main/java/world/bentobox/bentobox/listeners/PanelListenerManager.java b/src/main/java/world/bentobox/bentobox/listeners/PanelListenerManager.java
index 70d39b6d9..53d402c5e 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/PanelListenerManager.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/PanelListenerManager.java
@@ -1,9 +1,9 @@
package world.bentobox.bentobox.listeners;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
-import java.util.stream.Collectors;
import org.bukkit.ChatColor;
import org.bukkit.entity.HumanEntity;
@@ -24,7 +24,7 @@ import world.bentobox.bentobox.api.user.User;
public class PanelListenerManager implements Listener {
- private static HashMap openPanels = new HashMap<>();
+ private static final HashMap openPanels = new HashMap<>();
@EventHandler(priority = EventPriority.HIGHEST)
public void onInventoryClick(InventoryClickEvent event) {
@@ -97,8 +97,8 @@ public class PanelListenerManager implements Listener {
*/
public static void closeAllPanels() {
// Use stream clones to avoid concurrent modification exceptions
- openPanels.values().stream().collect(Collectors.toList()).forEach(p ->
- p.getInventory().getViewers().stream().collect(Collectors.toList()).forEach(HumanEntity::closeInventory));
+ new ArrayList<>(openPanels.values()).forEach(p ->
+ new ArrayList<>(p.getInventory().getViewers()).forEach(HumanEntity::closeInventory));
}
/**
diff --git a/src/main/java/world/bentobox/bentobox/listeners/PlayerEntityPortalEvent.java b/src/main/java/world/bentobox/bentobox/listeners/PlayerEntityPortalEvent.java
index ed0cff519..3a8c04cd4 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/PlayerEntityPortalEvent.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/PlayerEntityPortalEvent.java
@@ -47,7 +47,7 @@ public class PlayerEntityPortalEvent {
* @return whether there should create be a destination portal created
*/
public boolean getCanCreatePortal() {
- return epe == null ? ppe.getCanCreatePortal() : false;
+ return epe == null && ppe.getCanCreatePortal();
}
/**
diff --git a/src/main/java/world/bentobox/bentobox/listeners/PortalTeleportationListener.java b/src/main/java/world/bentobox/bentobox/listeners/PortalTeleportationListener.java
index 495d4e1ab..d0e55998d 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/PortalTeleportationListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/PortalTeleportationListener.java
@@ -20,8 +20,8 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityPortalEnterEvent;
import org.bukkit.event.entity.EntityPortalEvent;
+import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerPortalEvent;
-import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.util.Vector;
import org.eclipse.jdt.annotation.NonNull;
@@ -43,18 +43,13 @@ import world.bentobox.bentobox.util.teleport.SafeSpotTeleport;
public class PortalTeleportationListener implements Listener {
private final BentoBox plugin;
- private Set inPortal;
+ private final Set inPortal;
+ private final Set inTeleport;
public PortalTeleportationListener(@NonNull BentoBox plugin) {
this.plugin = plugin;
inPortal = new HashSet<>();
- }
-
-
- @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
- public void onPlayerTeleport(PlayerTeleportEvent e) {
- // Remove player from inPortal after a teleport
- inPortal.remove(e.getPlayer().getUniqueId());
+ inTeleport = new HashSet<>();
}
/**
@@ -72,19 +67,13 @@ public class PortalTeleportationListener implements Listener {
if (inPortal.contains(uuid) || !plugin.getIWM().inWorld(Util.getWorld(e.getLocation().getWorld()))) {
return;
}
+ inPortal.add(uuid);
if (!Bukkit.getAllowNether() && type.equals(Material.NETHER_PORTAL)) {
- inPortal.add(uuid);
// Schedule a time
Bukkit.getScheduler().runTaskLater(plugin, () -> {
// Check again if still in portal
- if (entity.getLocation().getBlock().getType().equals(Material.NETHER_PORTAL)) {
- PlayerPortalEvent en = new PlayerPortalEvent((Player)entity, e.getLocation(), null, TeleportCause.NETHER_PORTAL, 0, false, 0);
- if (!this.onIslandPortal(en)) {
- // Failed
- inPortal.remove(uuid);
- }
- } else {
- inPortal.remove(uuid);
+ if (inPortal.contains(uuid)) {
+ this.onIslandPortal(new PlayerPortalEvent((Player)entity, e.getLocation(), null, TeleportCause.NETHER_PORTAL, 0, false, 0));
}
}, 40);
return;
@@ -104,7 +93,6 @@ public class PortalTeleportationListener implements Listener {
/**
* Handles non-player portal use.
- * Currently disables portal use by entities to prevent dupe glitching.
*
* @param e - event
*/
@@ -117,7 +105,7 @@ public class PortalTeleportationListener implements Listener {
|| m.equals(Material.END_PORTAL)
|| m.equals(Material.END_GATEWAY))
.findFirst();
- if (!mat.isPresent()) {
+ if (mat.isEmpty()) {
e.setCancelled(true);
return false;
} else if (mat.get().equals(Material.NETHER_PORTAL)){
@@ -129,21 +117,32 @@ public class PortalTeleportationListener implements Listener {
return false;
}
+ /**
+ * Remove inPortal flag only when player exits the portal
+ * @param e player move event
+ */
+ @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
+ public void onExitPortal(PlayerMoveEvent e) {
+ if (!inPortal.contains(e.getPlayer().getUniqueId())) {
+ return;
+ }
+ if (e.getTo() != null && !e.getTo().getBlock().getType().equals(Material.NETHER_PORTAL)) {
+ inPortal.remove(e.getPlayer().getUniqueId());
+ inTeleport.remove(e.getPlayer().getUniqueId());
+ }
+ }
+
/**
* Handles nether or end portals
* @param e - event
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public boolean onIslandPortal(PlayerPortalEvent e) {
- switch (e.getCause()) {
- case END_GATEWAY:
- case END_PORTAL:
- return processPortal(new PlayerEntityPortalEvent(e), Environment.THE_END);
- case NETHER_PORTAL:
- return processPortal(new PlayerEntityPortalEvent(e), Environment.NETHER);
- default:
- return false;
- }
+ return switch (e.getCause()) {
+ case END_GATEWAY, END_PORTAL -> processPortal(new PlayerEntityPortalEvent(e), Environment.THE_END);
+ case NETHER_PORTAL -> processPortal(new PlayerEntityPortalEvent(e), Environment.NETHER);
+ default -> false;
+ };
}
@@ -154,18 +153,27 @@ public class PortalTeleportationListener implements Listener {
* @return true if portal happens, false if not
*/
private boolean processPortal(final PlayerEntityPortalEvent e, final Environment env) {
-
World fromWorld = e.getFrom().getWorld();
World overWorld = Util.getWorld(fromWorld);
if (fromWorld == null || !plugin.getIWM().inWorld(overWorld)) {
// Do nothing special
return false;
}
- // 1.14.4 requires explicit cancellation to prevent teleporting to the normal nether
+
if (!isGenerate(overWorld, env)) {
e.setCancelled(true);
return false;
}
+
+ if (!Bukkit.getServer().getAllowNether()) {
+ e.setCancelled(true);
+ }
+
+ if (inTeleport.contains(e.getEntity().getUniqueId())) {
+ return false;
+ }
+ inTeleport.add(e.getEntity().getUniqueId());
+
// STANDARD NETHER OR END
if (!isIslands(overWorld, env)) {
handleStandardNetherOrEnd(e, fromWorld, overWorld, env);
@@ -198,7 +206,6 @@ public class PortalTeleportationListener implements Listener {
&& e.getIsland().filter(i -> !hasPartnerIsland(i, env)).map(i -> {
// No nether island present so paste the default one
e.setCancelled(true);
- inPortal.remove(e.getEntity().getUniqueId());
pasteNewIsland((Player)e.getEntity(), e.getTo(), i, env);
return true;
}).orElse(false)) {
@@ -207,7 +214,6 @@ public class PortalTeleportationListener implements Listener {
}
if (e.getCanCreatePortal()) {
// Let the server teleport
- inPortal.remove(e.getEntity().getUniqueId());
return true;
}
if (env.equals(Environment.THE_END)) {
@@ -216,10 +222,10 @@ public class PortalTeleportationListener implements Listener {
e.getEntity().setFallDistance(0);
}
- // If we do not generate portals, teleporation should happen manually with safe spot builder.
- // Otherwise, we could end up with situations when player is placed in mid air, if teleporation
+ // If we do not generate portals, teleportation should happen manually with safe spot builder.
+ // Otherwise, we could end up with situations when player is placed in mid air, if teleportation
// is done instantly.
- // Our safe spot task is triggered in next tick, however, end teleporation happens in the same tick.
+ // Our safe spot task is triggered in next tick, however, end teleportation happens in the same tick.
// It is placed outside THE_END check, as technically it could happen with the nether portal too.
e.setCancelled(true);
@@ -232,7 +238,6 @@ public class PortalTeleportationListener implements Listener {
.location(e.getTo())
.portal()
.thenRun(() -> {
- inPortal.remove(e.getEntity().getUniqueId());
e.getEntity().setVelocity(new Vector(0,0,0));
e.getEntity().setFallDistance(0);
})
@@ -361,7 +366,6 @@ public class PortalTeleportationListener implements Listener {
e.setTo(e.getFrom().toVector().toLocation(overWorld));
// Find distance from edge of island's protection
plugin.getIslands().getIslandAt(e.getFrom()).ifPresent(i -> setSeachRadius(e, i));
- inPortal.remove(e.getEntity().getUniqueId());
return;
}
// Custom portals
@@ -374,7 +378,6 @@ public class PortalTeleportationListener implements Listener {
.entity(e.getEntity())
.location(to)
.portal()
- .thenRun(() -> inPortal.remove(e.getEntity().getUniqueId()))
.build();
}
@@ -412,7 +415,7 @@ public class PortalTeleportationListener implements Listener {
// From standard nether or end
else if (e.getEntity() instanceof Player){
e.setCancelled(true);
- plugin.getIslands().homeTeleportAsync(overWorld, (Player)e.getEntity()).thenAccept(b -> inPortal.remove(e.getEntity().getUniqueId()));
+ plugin.getIslands().homeTeleportAsync(overWorld, (Player)e.getEntity());
}
}
diff --git a/src/main/java/world/bentobox/bentobox/listeners/StandardSpawnProtectionListener.java b/src/main/java/world/bentobox/bentobox/listeners/StandardSpawnProtectionListener.java
index f07965dfa..737a219a2 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/StandardSpawnProtectionListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/StandardSpawnProtectionListener.java
@@ -111,8 +111,9 @@ public class StandardSpawnProtectionListener implements Listener {
private boolean atSpawn(@NonNull Location location) {
Vector p = location.toVector().multiply(new Vector(1, 0, 1));
Vector spawn = location.getWorld().getSpawnLocation().toVector().multiply(new Vector(1, 0, 1));
- int radiusSquared = plugin.getIWM().getNetherSpawnRadius(location.getWorld()) * plugin.getIWM().getNetherSpawnRadius(location.getWorld());
- return (spawn.distanceSquared(p) < radiusSquared);
+ int radius = plugin.getIWM().getNetherSpawnRadius(location.getWorld());
+ Vector diff = p.subtract(spawn);
+ return Math.abs(diff.getBlockX()) <= radius && Math.abs(diff.getBlockZ()) <= radius;
}
/**
@@ -123,7 +124,7 @@ public class StandardSpawnProtectionListener implements Listener {
* @return true if nothing needs to be done
*/
private boolean noAction(@NonNull Player player) {
- return (player.isOp() || player.getWorld().getEnvironment().equals(World.Environment.NORMAL)
+ return (player.isOp() || player.getWorld().getEnvironment().equals(World.Environment.NORMAL)
|| !plugin.getIWM().inWorld(Util.getWorld(player.getWorld()))
|| (player.getWorld().getEnvironment().equals(World.Environment.NETHER) && plugin.getIWM().isNetherIslands(player.getWorld()))
|| (player.getWorld().getEnvironment().equals(World.Environment.THE_END) && plugin.getIWM().isEndIslands(player.getWorld())));
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/clicklisteners/CommandCycleClick.java b/src/main/java/world/bentobox/bentobox/listeners/flags/clicklisteners/CommandCycleClick.java
index 4d730fe7d..8db7760e7 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/clicklisteners/CommandCycleClick.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/clicklisteners/CommandCycleClick.java
@@ -17,9 +17,9 @@ import world.bentobox.bentobox.managers.RanksManager;
*/
public class CommandCycleClick implements ClickHandler {
- private BentoBox plugin = BentoBox.getInstance();
- private String command;
- private CommandRankClickListener commandRankClickListener;
+ private final BentoBox plugin = BentoBox.getInstance();
+ private final String command;
+ private final CommandRankClickListener commandRankClickListener;
public CommandCycleClick(CommandRankClickListener commandRankClickListener, String c) {
this.commandRankClickListener = commandRankClickListener;
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/clicklisteners/CommandRankClickListener.java b/src/main/java/world/bentobox/bentobox/listeners/flags/clicklisteners/CommandRankClickListener.java
index e98abc574..d5ce0fecc 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/clicklisteners/CommandRankClickListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/clicklisteners/CommandRankClickListener.java
@@ -29,7 +29,7 @@ import world.bentobox.bentobox.util.Util;
*/
public class CommandRankClickListener implements ClickHandler {
- private BentoBox plugin = BentoBox.getInstance();
+ private final BentoBox plugin = BentoBox.getInstance();
/* (non-Javadoc)
* @see world.bentobox.bentobox.api.panels.PanelItem.ClickHandler#onClick(world.bentobox.bentobox.api.panels.Panel, world.bentobox.bentobox.api.user.User, org.bukkit.event.inventory.ClickType, int)
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/package-info.java b/src/main/java/world/bentobox/bentobox/listeners/flags/package-info.java
new file mode 100644
index 000000000..6527fd8ba
--- /dev/null
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/package-info.java
@@ -0,0 +1,7 @@
+/**
+ * Contains listeners specific to settings flags.
+ *
+ * @author tastybento
+ *
+ */
+package world.bentobox.bentobox.listeners.flags;
\ No newline at end of file
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/protection/BlockInteractionListener.java b/src/main/java/world/bentobox/bentobox/listeners/flags/protection/BlockInteractionListener.java
index faf4408ad..98a382cec 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/protection/BlockInteractionListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/protection/BlockInteractionListener.java
@@ -1,7 +1,5 @@
package world.bentobox.bentobox.listeners.flags.protection;
-import java.util.Collections;
-import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
@@ -36,9 +34,7 @@ public class BlockInteractionListener extends FlagListener {
*/
private final static Map stringFlags;
static {
- Map f = new HashMap<>();
- f.put("RESPAWN_ANCHOR", "PLACE_BLOCKS");
- stringFlags = Collections.unmodifiableMap(f);
+ stringFlags = Map.of("RESPAWN_ANCHOR", "PLACE_BLOCKS");
}
/**
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/protection/BreakBlocksListener.java b/src/main/java/world/bentobox/bentobox/listeners/flags/protection/BreakBlocksListener.java
index 35b4bc0ea..391f2605d 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/protection/BreakBlocksListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/protection/BreakBlocksListener.java
@@ -46,9 +46,8 @@ public class BreakBlocksListener extends FlagListener {
checkIsland(e, (Player)e.getRemover(), e.getEntity().getLocation(), Flags.BREAK_BLOCKS);
}
// Check for projectiles
- if (e.getRemover() instanceof Projectile) {
+ if (e.getRemover() instanceof Projectile p) {
// Find out who fired it
- Projectile p = (Projectile)e.getRemover();
if (p.getShooter() instanceof Player) {
checkIsland(e, (Player)p.getShooter(), e.getEntity().getLocation(), Flags.BREAK_BLOCKS);
}
@@ -118,9 +117,8 @@ public class BreakBlocksListener extends FlagListener {
if (e.getDamager() instanceof Player) {
// Check the break blocks flag
notAllowed(e, (Player)e.getDamager(), e.getEntity().getLocation());
- } else if (e.getDamager() instanceof Projectile) {
+ } else if (e.getDamager() instanceof Projectile p) {
// Find out who fired the arrow
- Projectile p = (Projectile) e.getDamager();
if (p.getShooter() instanceof Player && notAllowed(e, (Player)p.getShooter(), e.getEntity().getLocation())) {
e.getEntity().setFireTicks(0);
p.setFireTicks(0);
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/protection/BreedingListener.java b/src/main/java/world/bentobox/bentobox/listeners/flags/protection/BreedingListener.java
index d509d9627..1548535b2 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/protection/BreedingListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/protection/BreedingListener.java
@@ -73,8 +73,7 @@ public class BreedingListener extends FlagListener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onPlayerInteract(final PlayerInteractAtEntityEvent e) {
Player p = e.getPlayer();
- if (e.getRightClicked() instanceof Animals && BREEDING_ITEMS.containsKey(e.getRightClicked().getType())) {
- Animals animal = (Animals) e.getRightClicked();
+ if (e.getRightClicked() instanceof Animals animal && BREEDING_ITEMS.containsKey(e.getRightClicked().getType())) {
ItemStack inHand = p.getInventory().getItemInMainHand();
if (e.getHand().equals(EquipmentSlot.OFF_HAND)) {
inHand = p.getInventory().getItemInOffHand();
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/protection/BucketListener.java b/src/main/java/world/bentobox/bentobox/listeners/flags/protection/BucketListener.java
index 3dd360185..02426ea85 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/protection/BucketListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/protection/BucketListener.java
@@ -40,18 +40,18 @@ public class BucketListener extends FlagListener {
public void onBucketFill(final PlayerBucketFillEvent e) {
// Check filling of various liquids
switch (e.getItemStack().getType()) {
- case LAVA_BUCKET:
- checkIsland(e, e.getPlayer(), e.getBlockClicked().getLocation(), Flags.COLLECT_LAVA);
- return;
- case WATER_BUCKET:
- checkIsland(e, e.getPlayer(), e.getBlockClicked().getLocation(), Flags.COLLECT_WATER);
- return;
- case MILK_BUCKET:
- checkIsland(e, e.getPlayer(), e.getBlockClicked().getLocation(), Flags.MILKING);
- return;
- default:
- // Check general bucket use
- checkIsland(e, e.getPlayer(), e.getBlockClicked().getLocation(), Flags.BUCKET);
+ case LAVA_BUCKET -> {
+ checkIsland(e, e.getPlayer(), e.getBlockClicked().getLocation(), Flags.COLLECT_LAVA);
+ }
+ case WATER_BUCKET -> {
+ checkIsland(e, e.getPlayer(), e.getBlockClicked().getLocation(), Flags.COLLECT_WATER);
+ }
+ case MILK_BUCKET -> {
+ checkIsland(e, e.getPlayer(), e.getBlockClicked().getLocation(), Flags.MILKING);
+ }
+ default ->
+ // Check general bucket use
+ checkIsland(e, e.getPlayer(), e.getBlockClicked().getLocation(), Flags.BUCKET);
}
}
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/protection/ElytraListener.java b/src/main/java/world/bentobox/bentobox/listeners/flags/protection/ElytraListener.java
index 9338e5a9c..f3d4b585c 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/protection/ElytraListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/protection/ElytraListener.java
@@ -18,8 +18,7 @@ public class ElytraListener extends FlagListener {
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onGlide(EntityToggleGlideEvent e) {
- if (e.getEntity() instanceof Player) {
- Player player = (Player) e.getEntity();
+ if (e.getEntity() instanceof Player player) {
if (!checkIsland(e, player, player.getLocation(), Flags.ELYTRA)) {
player.setGliding(false);
}
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/protection/HurtingListener.java b/src/main/java/world/bentobox/bentobox/listeners/flags/protection/HurtingListener.java
index d0e060912..887c278ef 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/protection/HurtingListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/protection/HurtingListener.java
@@ -41,8 +41,8 @@ import world.bentobox.bentobox.versions.ServerCompatibility;
*/
public class HurtingListener extends FlagListener {
- private Map thrownPotions = new HashMap<>();
- private Map firedFireworks = new WeakHashMap<>();
+ private final Map thrownPotions = new HashMap<>();
+ private final Map firedFireworks = new WeakHashMap<>();
/**
* Handles mob and monster protection
@@ -71,9 +71,8 @@ public class HurtingListener extends FlagListener {
// Get the attacker
if (damager instanceof Player) {
checkIsland(e, (Player)damager, damager.getLocation(), flag);
- } else if (damager instanceof Projectile) {
+ } else if (damager instanceof Projectile p) {
// Find out who fired the projectile
- Projectile p = (Projectile) damager;
if (p.getShooter() instanceof Player && !checkIsland(e, (Player)p.getShooter(), damager.getLocation(), flag)) {
e.getEntity().setFireTicks(0);
}
@@ -123,8 +122,7 @@ public class HurtingListener extends FlagListener {
public void onSplashPotionSplash(final PotionSplashEvent e) {
// Try to get the shooter
Projectile projectile = e.getEntity();
- if (projectile.getShooter() instanceof Player) {
- Player attacker = (Player)projectile.getShooter();
+ if (projectile.getShooter() instanceof Player attacker) {
// Run through all the affected entities
for (LivingEntity entity: e.getAffectedEntities()) {
// Self damage
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/protection/InventoryListener.java b/src/main/java/world/bentobox/bentobox/listeners/flags/protection/InventoryListener.java
index f9e5275be..250969322 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/protection/InventoryListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/protection/InventoryListener.java
@@ -72,9 +72,8 @@ public class InventoryListener extends FlagListener {
else if (inventoryHolder instanceof ShulkerBox) {
checkIsland(e, player, e.getInventory().getLocation(), Flags.SHULKER_BOX);
}
- else if (inventoryHolder instanceof Chest) {
+ else if (inventoryHolder instanceof Chest chestInventoryHolder) {
// To differentiate between a Chest and a Trapped Chest we need to get the Block corresponding to the inventory
- Chest chestInventoryHolder = (Chest) inventoryHolder;
try {
if (chestInventoryHolder.getType() == Material.TRAPPED_CHEST) {
checkIsland(e, player, e.getInventory().getLocation(), Flags.TRAPPED_CHEST);
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/protection/PhysicalInteractionListener.java b/src/main/java/world/bentobox/bentobox/listeners/flags/protection/PhysicalInteractionListener.java
index d29e4330b..26ef9d7d8 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/protection/PhysicalInteractionListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/protection/PhysicalInteractionListener.java
@@ -53,10 +53,9 @@ public class PhysicalInteractionListener extends FlagListener {
*/
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onProjectileHit(EntityInteractEvent e) {
- if (!(e.getEntity() instanceof Projectile)) {
+ if (!(e.getEntity() instanceof Projectile p)) {
return;
}
- Projectile p = (Projectile)e.getEntity();
if (p.getShooter() instanceof Player) {
if (Tag.WOODEN_BUTTONS.isTagged(e.getBlock().getType())) {
checkIsland(e, (Player)p.getShooter(), e.getBlock().getLocation(), Flags.BUTTON);
@@ -71,23 +70,10 @@ public class PhysicalInteractionListener extends FlagListener {
}
private boolean isPressurePlate(Material material) {
- switch(material) {
- case STONE_PRESSURE_PLATE:
- case POLISHED_BLACKSTONE_PRESSURE_PLATE:
- case ACACIA_PRESSURE_PLATE:
- case BIRCH_PRESSURE_PLATE:
- case CRIMSON_PRESSURE_PLATE:
- case DARK_OAK_PRESSURE_PLATE:
- case HEAVY_WEIGHTED_PRESSURE_PLATE:
- case JUNGLE_PRESSURE_PLATE:
- case LIGHT_WEIGHTED_PRESSURE_PLATE:
- case OAK_PRESSURE_PLATE:
- case SPRUCE_PRESSURE_PLATE:
- case WARPED_PRESSURE_PLATE:
- return true;
- default:
- return false;
- }
+ return switch (material) {
+ case STONE_PRESSURE_PLATE, POLISHED_BLACKSTONE_PRESSURE_PLATE, ACACIA_PRESSURE_PLATE, BIRCH_PRESSURE_PLATE, CRIMSON_PRESSURE_PLATE, DARK_OAK_PRESSURE_PLATE, HEAVY_WEIGHTED_PRESSURE_PLATE, JUNGLE_PRESSURE_PLATE, LIGHT_WEIGHTED_PRESSURE_PLATE, OAK_PRESSURE_PLATE, SPRUCE_PRESSURE_PLATE, WARPED_PRESSURE_PLATE -> true;
+ default -> false;
+ };
}
}
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/protection/TNTListener.java b/src/main/java/world/bentobox/bentobox/listeners/flags/protection/TNTListener.java
index 514d255bf..1d1b43a2e 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/protection/TNTListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/protection/TNTListener.java
@@ -1,7 +1,5 @@
package world.bentobox.bentobox.listeners.flags.protection;
-import java.util.Arrays;
-import java.util.Collections;
import java.util.List;
import org.bukkit.Location;
@@ -31,13 +29,13 @@ public class TNTListener extends FlagListener {
* Contains {@link EntityType}s that generates an explosion.
* @since 1.5.0
*/
- private static final List TNT_TYPES = Collections.unmodifiableList(Arrays.asList(EntityType.PRIMED_TNT, EntityType.MINECART_TNT));
+ private static final List TNT_TYPES = List.of(EntityType.PRIMED_TNT, EntityType.MINECART_TNT);
/**
* Contains {@link Material}s that can be used to prime a TNT.
* @since 1.5.0
*/
- private static final List PRIMING_ITEMS = Collections.unmodifiableList(Arrays.asList(Material.FLINT_AND_STEEL, Material.FIRE_CHARGE));
+ private static final List PRIMING_ITEMS = List.of(Material.FLINT_AND_STEEL, Material.FIRE_CHARGE);
/**
* Protect TNT from being set light by a fire arrow
@@ -50,8 +48,7 @@ public class TNTListener extends FlagListener {
return false;
}
// Stop TNT from being damaged if it is being caused by a visitor with a flaming arrow
- if (e.getEntity() instanceof Projectile) {
- Projectile projectile = (Projectile) e.getEntity();
+ if (e.getEntity() instanceof Projectile projectile) {
// Find out who fired it
if (projectile.getShooter() instanceof Player && projectile.getFireTicks() > 0
&& !checkIsland(e, (Player)projectile.getShooter(), e.getBlock().getLocation(), Flags.TNT_PRIMING)) {
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/settings/PVPListener.java b/src/main/java/world/bentobox/bentobox/listeners/flags/settings/PVPListener.java
index 0a39e2ad7..2cc2fee54 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/settings/PVPListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/settings/PVPListener.java
@@ -2,11 +2,12 @@ package world.bentobox.bentobox.listeners.flags.settings;
import java.util.HashMap;
import java.util.Map;
+import java.util.Objects;
import java.util.UUID;
import java.util.WeakHashMap;
import org.bukkit.Bukkit;
-import org.bukkit.World;
+import org.bukkit.Sound;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Firework;
import org.bukkit.entity.LivingEntity;
@@ -23,6 +24,7 @@ import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.LingeringPotionSplashEvent;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.event.player.PlayerFishEvent;
+import org.bukkit.event.player.PlayerTeleportEvent;
import world.bentobox.bentobox.api.events.flags.FlagSettingChangeEvent;
import world.bentobox.bentobox.api.flags.Flag;
@@ -38,8 +40,8 @@ import world.bentobox.bentobox.managers.RanksManager;
*/
public class PVPListener extends FlagListener {
- private Map thrownPotions = new HashMap<>();
- private Map firedFireworks = new WeakHashMap<>();
+ private final Map thrownPotions = new HashMap<>();
+ private final Map firedFireworks = new WeakHashMap<>();
/**
* This method protects players from PVP if it is not allowed and from
@@ -54,6 +56,10 @@ public class PVPListener extends FlagListener {
if (e.getEntity().equals(e.getDamager()) || e.getEntity().hasMetadata("NPC")) {
return;
}
+ // Is PVP allowed here?
+ if (this.PVPAllowed(e.getEntity().getLocation())) {
+ return;
+ }
// Protect visitors
if (e.getCause().equals(DamageCause.ENTITY_ATTACK) && protectedVisitor((Player)e.getEntity())) {
if (e.getDamager() instanceof Player) {
@@ -83,9 +89,8 @@ public class PVPListener extends FlagListener {
user.notify(getFlag(damager.getWorld()).getHintReference());
e.setCancelled(true);
}
- } else if (damager instanceof Projectile && ((Projectile)damager).getShooter() instanceof Player) {
+ } else if (damager instanceof Projectile p && ((Projectile)damager).getShooter() instanceof Player) {
// Find out who fired the arrow
- Projectile p = (Projectile) damager;
Player shooter =(Player)p.getShooter();
processDamage(e, damager, shooter, hurtEntity, flag);
} else if (damager instanceof Firework && firedFireworks.containsKey(damager)) {
@@ -116,6 +121,10 @@ public class PVPListener extends FlagListener {
if (e.getCaught().equals(e.getPlayer()) || e.getCaught().hasMetadata("NPC")) {
return;
}
+ // Is PVP allowed here?
+ if (this.PVPAllowed(e.getCaught().getLocation())) {
+ return;
+ }
// Protect visitors
if (protectedVisitor((Player)e.getCaught())) {
User.getInstance(e.getPlayer()).notify(Flags.INVINCIBLE_VISITORS.getHintReference());
@@ -136,6 +145,10 @@ public class PVPListener extends FlagListener {
public void onSplashPotionSplash(final PotionSplashEvent e) {
if (e.getEntity().getShooter() instanceof Player && getPlugin().getIWM().inWorld(e.getEntity().getWorld())) {
User user = User.getInstance((Player)e.getEntity().getShooter());
+ // Is PVP allowed here?
+ if (this.PVPAllowed(e.getEntity().getLocation())) {
+ return;
+ }
// Run through affected entities and cancel the splash for protected players
for (LivingEntity le : e.getAffectedEntities()) {
if (!le.getUniqueId().equals(user.getUniqueId()) && blockPVP(user, le, e, getFlag(e.getEntity().getWorld()))) {
@@ -197,17 +210,6 @@ public class PVPListener extends FlagListener {
}
}
- private Flag getFlag(World w) {
- switch (w.getEnvironment()) {
- case NETHER:
- return Flags.PVP_NETHER;
- case THE_END:
- return Flags.PVP_END;
- default:
- return Flags.PVP_OVERWORLD;
- }
- }
-
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled=true)
public void onPlayerShootFireworkEvent(final EntityShootBowEvent e) {
// Only care about players shooting fireworks
@@ -228,4 +230,35 @@ public class PVPListener extends FlagListener {
e.getIsland().getMemberSet(RanksManager.COOP_RANK).forEach(member -> User.getInstance(member).sendMessage(message));
}
}
+
+ /**
+ * Warn visitors if the island they are teleporting to has PVP on
+ * @param e teleport event
+ */
+ @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled=true)
+ public void onPlayerTeleport(PlayerTeleportEvent e) {
+ if (e.getTo() == null) {
+ return;
+ }
+ getIslands().getIslandAt(e.getTo()).ifPresent(island -> {
+ if (island.getMemberSet(RanksManager.COOP_RANK).contains(e.getPlayer().getUniqueId())) {
+ return;
+ }
+ if (island.isAllowed(Flags.PVP_OVERWORLD)) {
+ alertUser(e.getPlayer(), Flags.PVP_OVERWORLD);
+ }
+ if (island.isAllowed(Flags.PVP_NETHER)) {
+ alertUser(e.getPlayer(), Flags.PVP_NETHER);
+ }
+ if (island.isAllowed(Flags.PVP_END)) {
+ alertUser(e.getPlayer(), Flags.PVP_END);
+ }
+ });
+ }
+
+ private void alertUser(Player player, Flag flag) {
+ String message = "protection.flags." + flag.getID() + ".enabled";
+ Objects.requireNonNull(User.getInstance(player)).sendMessage(message);
+ player.playSound(player.getLocation(), Sound.ENTITY_ARROW_HIT_PLAYER,2F, 1F);
+ }
}
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/CleanSuperFlatListener.java b/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/CleanSuperFlatListener.java
index 0a4390815..ed28ece90 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/CleanSuperFlatListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/CleanSuperFlatListener.java
@@ -31,14 +31,14 @@ import world.bentobox.bentobox.util.Pair;
*/
public class CleanSuperFlatListener extends FlagListener {
- private BentoBox plugin = BentoBox.getInstance();
+ private final BentoBox plugin = BentoBox.getInstance();
/**
* Stores pairs of X,Z coordinates of chunks that need to be regenerated.
* @since 1.1
*/
@NonNull
- private Queue<@NonNull Pair<@NonNull Integer, @NonNull Integer>> chunkQueue = new LinkedList<>();
+ private final Queue<@NonNull Pair<@NonNull Integer, @NonNull Integer>> chunkQueue = new LinkedList<>();
/**
* Task that runs each tick to regenerate chunks that are in the {@link #chunkQueue}.
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/CreeperListener.java b/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/CreeperListener.java
index e70571b83..814c982ed 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/CreeperListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/CreeperListener.java
@@ -41,8 +41,7 @@ public class CreeperListener extends FlagListener {
}
// Check for griefing
Creeper creeper = (Creeper)e.getEntity();
- if (!Flags.CREEPER_GRIEFING.isSetForWorld(e.getLocation().getWorld()) && creeper.getTarget() instanceof Player) {
- Player target = (Player)creeper.getTarget();
+ if (!Flags.CREEPER_GRIEFING.isSetForWorld(e.getLocation().getWorld()) && creeper.getTarget() instanceof Player target) {
if (!getIslands().locationIsOnIsland(target, e.getLocation())) {
User user = User.getInstance(target);
user.notify("protection.protected", TextVariables.DESCRIPTION, user.getTranslation(Flags.CREEPER_GRIEFING.getHintReference()));
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/GeoLimitMobsListener.java b/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/GeoLimitMobsListener.java
index bded3d444..ae536c2f7 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/GeoLimitMobsListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/GeoLimitMobsListener.java
@@ -24,7 +24,7 @@ import world.bentobox.bentobox.database.objects.Island;
*/
public class GeoLimitMobsListener extends FlagListener {
- private Map mobSpawnTracker = new WeakHashMap<>();
+ private final Map mobSpawnTracker = new WeakHashMap<>();
/**
* Start the tracker when the plugin is loaded
@@ -69,8 +69,7 @@ public class GeoLimitMobsListener extends FlagListener {
public void onProjectileExplode(final ExplosionPrimeEvent e) {
if (e.getEntity() instanceof Projectile && getIWM().inWorld(e.getEntity().getLocation())) {
ProjectileSource source = ((Projectile)e.getEntity()).getShooter();
- if (source instanceof Entity) {
- Entity shooter = (Entity)source;
+ if (source instanceof Entity shooter) {
if (mobSpawnTracker.containsKey(shooter)
&& !mobSpawnTracker.get(shooter).onIsland(e.getEntity().getLocation())) {
e.getEntity().remove();
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/InvincibleVisitorsListener.java b/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/InvincibleVisitorsListener.java
index 87bbb4379..d8890723a 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/InvincibleVisitorsListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/InvincibleVisitorsListener.java
@@ -124,16 +124,17 @@ public class InvincibleVisitorsListener extends FlagListener implements ClickHan
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onVisitorGetDamage(EntityDamageEvent e) {
World world = e.getEntity().getWorld();
- if (!(e.getEntity() instanceof Player)
+ if (!(e.getEntity() instanceof Player p)
|| !getIWM().inWorld(world)
|| e.getEntity().hasMetadata("NPC")
|| !getIWM().getIvSettings(world).contains(e.getCause().name())
- || getIslands().userIsOnIsland(world, User.getInstance(e.getEntity()))) {
+ || getIslands().userIsOnIsland(world, User.getInstance(e.getEntity()))
+ || PVPAllowed(p.getLocation())
+ ) {
return;
}
// Player is a visitor and should be protected from damage
e.setCancelled(true);
- Player p = (Player) e.getEntity();
// Handle the void - teleport player back to island in a safe spot
if(e.getCause().equals(DamageCause.VOID)) {
if (getIslands().getIslandAt(p.getLocation()).isPresent()) {
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/LiquidsFlowingOutListener.java b/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/LiquidsFlowingOutListener.java
index 9cb5b6e3a..3c533adbf 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/LiquidsFlowingOutListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/LiquidsFlowingOutListener.java
@@ -38,7 +38,7 @@ public class LiquidsFlowingOutListener extends FlagListener {
// Only prevent if it is flowing into the area between islands or into another island.
Optional fromIsland = getIslands().getProtectedIslandAt(from.getLocation());
Optional toIsland = getIslands().getProtectedIslandAt(to.getLocation());
- if (!toIsland.isPresent() || (fromIsland.isPresent() && !fromIsland.equals(toIsland))) {
+ if (toIsland.isEmpty() || (fromIsland.isPresent() && !fromIsland.equals(toIsland))) {
e.setCancelled(true);
}
}
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/NaturalSpawningOutsideRangeListener.java b/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/NaturalSpawningOutsideRangeListener.java
index 769078eae..ade03ed48 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/NaturalSpawningOutsideRangeListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/NaturalSpawningOutsideRangeListener.java
@@ -23,7 +23,7 @@ public class NaturalSpawningOutsideRangeListener extends FlagListener {
}
// If it is a natural spawn and there is no protected island at the location, block the spawn.
- if (e.getSpawnReason() == CreatureSpawnEvent.SpawnReason.NATURAL && !getIslands().getProtectedIslandAt(e.getLocation()).isPresent()) {
+ if (e.getSpawnReason() == CreatureSpawnEvent.SpawnReason.NATURAL && getIslands().getProtectedIslandAt(e.getLocation()).isEmpty()) {
e.setCancelled(true);
}
}
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/ObsidianScoopingListener.java b/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/ObsidianScoopingListener.java
index bcff672a1..b312edab4 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/ObsidianScoopingListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/ObsidianScoopingListener.java
@@ -5,6 +5,7 @@ import java.util.HashMap;
import java.util.List;
import org.bukkit.Bukkit;
+import org.bukkit.FluidCollisionMode;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.Sound;
@@ -51,7 +52,13 @@ public class ObsidianScoopingListener extends FlagListener {
private boolean lookForLava(PlayerInteractEvent e) {
Player player = e.getPlayer();
ItemStack bucket = e.getItem();
- Block b = e.getClickedBlock();
+
+ // Get block player is looking at
+ Block b = e.getPlayer().rayTraceBlocks(5, FluidCollisionMode.ALWAYS).getHitBlock();
+ if (!b.getType().equals(Material.OBSIDIAN)) {
+ // This should not be needed but might catch some attempts
+ return false;
+ }
User user = User.getInstance(player);
if (getIslands().userIsOnIsland(user.getWorld(), user)) {
// Look around to see if this is a lone obsidian block
@@ -61,15 +68,14 @@ public class ObsidianScoopingListener extends FlagListener {
}
user.sendMessage("protection.flags.OBSIDIAN_SCOOPING.scooping");
player.getWorld().playSound(player.getLocation(), Sound.ITEM_BUCKET_FILL_LAVA, 1F, 1F);
- b.setType(Material.AIR);
e.setCancelled(true);
- Bukkit.getScheduler().runTask(BentoBox.getInstance(), () -> givePlayerLava(player, bucket));
+ Bukkit.getScheduler().runTask(BentoBox.getInstance(), () -> givePlayerLava(player, b, bucket));
return true;
}
return false;
}
- private void givePlayerLava(Player player, ItemStack bucket) {
+ private void givePlayerLava(Player player, Block b, ItemStack bucket) {
if (bucket.getAmount() == 1) {
// Needs some special handling when there is only 1 bucket in the stack
bucket.setType(Material.LAVA_BUCKET);
@@ -81,6 +87,8 @@ public class ObsidianScoopingListener extends FlagListener {
map.values().forEach(i -> player.getWorld().dropItem(player.getLocation(), i));
}
}
+ // Set block to air only after giving bucket
+ b.setType(Material.AIR);
}
private List getBlocksAround(Block b) {
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/PetTeleportListener.java b/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/PetTeleportListener.java
index 379c44de3..ced124ed8 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/PetTeleportListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/PetTeleportListener.java
@@ -25,9 +25,8 @@ public class PetTeleportListener extends FlagListener {
if (e.getTo() == null
|| !getIWM().inWorld(e.getFrom())
|| !Flags.PETS_STAY_AT_HOME.isSetForWorld(e.getFrom().getWorld())
- || !(e.getEntity() instanceof Tameable)
+ || !(e.getEntity() instanceof Tameable t)
) return;
- Tameable t = (Tameable)e.getEntity();
if (t.isTamed() && t.getOwner() != null) {
// Get where the pet is going
e.setCancelled(getIslands().getProtectedIslandAt(e.getTo())
diff --git a/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/TreesGrowingOutsideRangeListener.java b/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/TreesGrowingOutsideRangeListener.java
index e927acd07..9f77ec728 100644
--- a/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/TreesGrowingOutsideRangeListener.java
+++ b/src/main/java/world/bentobox/bentobox/listeners/flags/worldsettings/TreesGrowingOutsideRangeListener.java
@@ -24,14 +24,14 @@ public class TreesGrowingOutsideRangeListener extends FlagListener {
}
// If there is no protected island at the location of the sapling, just cancel the event (prevents the sapling from growing).
- if (!getIslands().getProtectedIslandAt(e.getLocation()).isPresent()) {
+ if (getIslands().getProtectedIslandAt(e.getLocation()).isEmpty()) {
e.setCancelled(true);
return;
}
// Now, run through all the blocks that will be generated and if there is no protected island at their location, turn them into AIR.
e.getBlocks().stream()
- .filter(blockState -> !getIslands().getProtectedIslandAt(blockState.getLocation()).isPresent())
+ .filter(blockState -> getIslands().getProtectedIslandAt(blockState.getLocation()).isEmpty())
.forEach(blockState -> blockState.setType(Material.AIR));
}
@@ -45,13 +45,13 @@ public class TreesGrowingOutsideRangeListener extends FlagListener {
}
// If there is no protected island at the location of the chorus flower, just cancel the event (prevents the flower from growing).
- if (!getIslands().getProtectedIslandAt(e.getSource().getLocation()).isPresent()) {
+ if (getIslands().getProtectedIslandAt(e.getSource().getLocation()).isEmpty()) {
e.setCancelled(true);
return;
}
// Now prevent the flower to grow if this is growing outside the island
- if (!getIslands().getProtectedIslandAt(e.getBlock().getLocation()).isPresent()) {
+ if (getIslands().getProtectedIslandAt(e.getBlock().getLocation()).isEmpty()) {
e.setCancelled(true);
}
}
diff --git a/src/main/java/world/bentobox/bentobox/lists/Flags.java b/src/main/java/world/bentobox/bentobox/lists/Flags.java
index 057082afe..ec832e32c 100644
--- a/src/main/java/world/bentobox/bentobox/lists/Flags.java
+++ b/src/main/java/world/bentobox/bentobox/lists/Flags.java
@@ -422,7 +422,7 @@ public final class Flags {
.listener(new PistonPushListener())
.build();
- private static InvincibleVisitorsListener ilv = new InvincibleVisitorsListener();
+ private static final InvincibleVisitorsListener ilv = new InvincibleVisitorsListener();
public static final Flag INVINCIBLE_VISITORS = new Flag.Builder("INVINCIBLE_VISITORS", Material.DIAMOND_CHESTPLATE).type(Type.WORLD_SETTING)
.listener(ilv).clickHandler(ilv).usePanel(true).build();
diff --git a/src/main/java/world/bentobox/bentobox/lists/GameModePlaceholder.java b/src/main/java/world/bentobox/bentobox/lists/GameModePlaceholder.java
index 6378569dd..13bf14790 100644
--- a/src/main/java/world/bentobox/bentobox/lists/GameModePlaceholder.java
+++ b/src/main/java/world/bentobox/bentobox/lists/GameModePlaceholder.java
@@ -319,11 +319,11 @@ public enum GameModePlaceholder {
*/
OWNS_ISLAND("owns_island", (addon, user, island) -> String.valueOf(island != null && user != null && user.getUniqueId().equals(island.getOwner())));
- private String placeholder;
+ private final String placeholder;
/**
* @since 1.5.0
*/
- private GameModePlaceholderReplacer replacer;
+ private final GameModePlaceholderReplacer replacer;
GameModePlaceholder(String placeholder, GameModePlaceholderReplacer replacer) {
this.placeholder = placeholder;
diff --git a/src/main/java/world/bentobox/bentobox/lists/package-info.java b/src/main/java/world/bentobox/bentobox/lists/package-info.java
new file mode 100644
index 000000000..d50fe1765
--- /dev/null
+++ b/src/main/java/world/bentobox/bentobox/lists/package-info.java
@@ -0,0 +1,7 @@
+/**
+ * This is where lists of things are put. For example Flags.
+ *
+ * @author tastybento, Poslovitch
+ *
+ */
+package world.bentobox.bentobox.lists;
\ No newline at end of file
diff --git a/src/main/java/world/bentobox/bentobox/managers/AddonsManager.java b/src/main/java/world/bentobox/bentobox/managers/AddonsManager.java
index 9e0ae0d45..b7853161d 100644
--- a/src/main/java/world/bentobox/bentobox/managers/AddonsManager.java
+++ b/src/main/java/world/bentobox/bentobox/managers/AddonsManager.java
@@ -62,14 +62,18 @@ public class AddonsManager {
private static final String GAMEMODE = "[gamemode].";
@NonNull
- private List addons;
+ private final List addons;
@NonNull
- private Map<@NonNull Addon, @Nullable AddonClassLoader> loaders;
+ private final Map<@NonNull Addon, @Nullable AddonClassLoader> loaders;
+ @NonNull
+ private final Map<@NonNull Addon, @Nullable Plugin> pladdons;
@NonNull
private final Map> classes;
- private BentoBox plugin;
- private @NonNull Map<@NonNull String, @Nullable GameModeAddon> worldNames;
- private @NonNull Map<@NonNull Addon, @NonNull List> listeners;
+ private final BentoBox plugin;
+ private @NonNull
+ final Map<@NonNull String, @Nullable GameModeAddon> worldNames;
+ private @NonNull
+ final Map<@NonNull Addon, @NonNull List> listeners;
private final PluginLoader pluginLoader;
@@ -77,6 +81,7 @@ public class AddonsManager {
this.plugin = plugin;
addons = new ArrayList<>();
loaders = new HashMap<>();
+ pladdons = new HashMap<>();
classes = new HashMap<>();
listeners = new HashMap<>();
worldNames = new HashMap<>();
@@ -159,6 +164,9 @@ public class AddonsManager {
if (pladdon instanceof Pladdon) {
addon = ((Pladdon) pladdon).getAddon();
addon.setDescription(AddonClassLoader.asDescription(data));
+ // Mark pladdon as enabled.
+ ((Pladdon) pladdon).setEnabled();
+ pladdons.put(addon, pladdon);
} else {
plugin.logError("Could not load pladdon!");
return;
@@ -211,8 +219,7 @@ public class AddonsManager {
// Run the onLoad.
addon.onLoad();
// if game mode, get the world name and generate
- if (addon instanceof GameModeAddon && !addon.getState().equals(State.DISABLED)) {
- GameModeAddon gameMode = (GameModeAddon) addon;
+ if (addon instanceof GameModeAddon gameMode && !addon.getState().equals(State.DISABLED)) {
if (!gameMode.getWorldSettings().getWorldName().isEmpty()) {
worldNames.put(gameMode.getWorldSettings().getWorldName().toLowerCase(Locale.ENGLISH), gameMode);
}
@@ -282,8 +289,7 @@ public class AddonsManager {
plugin.log("Enabling " + addon.getDescription().getName() + " (" + addon.getDescription().getVersion() + ")...");
try {
// If this is a GameModeAddon create the worlds, register it and load the blueprints
- if (addon instanceof GameModeAddon) {
- GameModeAddon gameMode = (GameModeAddon) addon;
+ if (addon instanceof GameModeAddon gameMode) {
// Create the gameWorlds
gameMode.createWorlds();
plugin.getIWM().addGameMode(gameMode);
@@ -296,8 +302,7 @@ public class AddonsManager {
plugin.log(addon.getDescription().getName() + " is disabled.");
return;
}
- if (addon instanceof GameModeAddon) {
- GameModeAddon gameMode = (GameModeAddon) addon;
+ if (addon instanceof GameModeAddon gameMode) {
// Set the worlds for the commands
gameMode.getPlayerCommand().ifPresent(c -> c.setWorld(gameMode.getOverWorld()));
gameMode.getAdminCommand().ifPresent(c -> c.setWorld(gameMode.getOverWorld()));
@@ -327,7 +332,7 @@ public class AddonsManager {
plugin.logWarning("NOTE: DO NOT report this as a bug from BentoBox.");
StringBuilder a = new StringBuilder();
addon.getDescription().getAuthors().forEach(author -> a.append(author).append(" "));
- plugin.getLogger().log(Level.SEVERE, "Please report this stack trace to the addon's author(s): " + a.toString(), e);
+ plugin.getLogger().log(Level.SEVERE, "Please report this stack trace to the addon's author(s): " + a, e);
}
@@ -404,6 +409,7 @@ public class AddonsManager {
plugin.getCommandsManager().unregisterCommands();
// Clear all maps
listeners.clear();
+ pladdons.clear();
addons.clear();
loaders.clear();
classes.clear();
@@ -605,7 +611,7 @@ public class AddonsManager {
try {
addon.onDisable();
} catch (Exception e) {
- plugin.logError("Error occured when disabling addon " + addon.getDescription().getName());
+ plugin.logError("Error occurred when disabling addon " + addon.getDescription().getName());
plugin.logError("Report this to the addon's author(s)");
addon.getDescription().getAuthors().forEach(plugin::logError);
plugin.logStacktrace(e);
@@ -621,7 +627,11 @@ public class AddonsManager {
addon.setState(State.DISABLED);
loaders.remove(addon);
}
-
+ // Disable pladdons
+ if (pladdons.containsKey(addon)) {
+ this.pluginLoader.disablePlugin(Objects.requireNonNull(this.pladdons.get(addon)));
+ pladdons.remove(addon);
+ }
// Remove it from the addons list
addons.remove(addon);
}
diff --git a/src/main/java/world/bentobox/bentobox/managers/BlueprintClipboardManager.java b/src/main/java/world/bentobox/bentobox/managers/BlueprintClipboardManager.java
index a14612107..2c852c593 100644
--- a/src/main/java/world/bentobox/bentobox/managers/BlueprintClipboardManager.java
+++ b/src/main/java/world/bentobox/bentobox/managers/BlueprintClipboardManager.java
@@ -35,13 +35,13 @@ public class BlueprintClipboardManager {
private static final String LOAD_ERROR = "Could not load blueprint file - does not exist : ";
- private File blueprintFolder;
+ private final File blueprintFolder;
private BlueprintClipboard clipboard;
private Gson gson;
- private BentoBox plugin;
+ private final BentoBox plugin;
public BlueprintClipboardManager(BentoBox plugin, File blueprintFolder) {
this(plugin, blueprintFolder, null);
@@ -77,7 +77,7 @@ public class BlueprintClipboardManager {
/**
* Load a file to clipboard
* @param fileName - filename in blueprints folder
- * @throws IOException - if there's a load error with unziping or name
+ * @throws IOException - if there's a load error with unzipping or name
*/
public void load(String fileName) throws IOException {
clipboard = new BlueprintClipboard(loadBlueprint(fileName));
diff --git a/src/main/java/world/bentobox/bentobox/managers/BlueprintsManager.java b/src/main/java/world/bentobox/bentobox/managers/BlueprintsManager.java
index 8d7978686..6ef338ee2 100644
--- a/src/main/java/world/bentobox/bentobox/managers/BlueprintsManager.java
+++ b/src/main/java/world/bentobox/bentobox/managers/BlueprintsManager.java
@@ -67,13 +67,15 @@ public class BlueprintsManager {
* Inner map's key is the uniqueId of the blueprint bundle so it's
* easy to get from a UI
*/
- private @NonNull Map> blueprintBundles;
+ private @NonNull
+ final Map> blueprintBundles;
/**
* Map of blueprints. There can be many blueprints per game mode addon
* Inner map's key is the blueprint's name so it's easy to get from a UI
*/
- private @NonNull Map> blueprints;
+ private @NonNull
+ final Map> blueprints;
/**
* Gson used for serializing/deserializing the bundle class
@@ -82,7 +84,8 @@ public class BlueprintsManager {
private final @NonNull BentoBox plugin;
- private @NonNull Set blueprintsLoaded;
+ private @NonNull
+ final Set blueprintsLoaded;
public BlueprintsManager(@NonNull BentoBox plugin) {
diff --git a/src/main/java/world/bentobox/bentobox/managers/CommandsManager.java b/src/main/java/world/bentobox/bentobox/managers/CommandsManager.java
index 73e9297a9..571ed90bc 100644
--- a/src/main/java/world/bentobox/bentobox/managers/CommandsManager.java
+++ b/src/main/java/world/bentobox/bentobox/managers/CommandsManager.java
@@ -18,7 +18,7 @@ import world.bentobox.bentobox.api.commands.CompositeCommand;
public class CommandsManager {
@NonNull
- private Map<@NonNull String, @NonNull CompositeCommand> commands = new HashMap<>();
+ private final Map<@NonNull String, @NonNull CompositeCommand> commands = new HashMap<>();
private SimpleCommandMap commandMap;
public void registerCommand(@NonNull CompositeCommand command) {
diff --git a/src/main/java/world/bentobox/bentobox/managers/FlagsManager.java b/src/main/java/world/bentobox/bentobox/managers/FlagsManager.java
index 49bcd4d85..1c35ab0a7 100644
--- a/src/main/java/world/bentobox/bentobox/managers/FlagsManager.java
+++ b/src/main/java/world/bentobox/bentobox/managers/FlagsManager.java
@@ -23,8 +23,9 @@ import world.bentobox.bentobox.lists.Flags;
*/
public class FlagsManager {
- private @NonNull BentoBox plugin;
- private Map<@NonNull Flag, @Nullable Addon> flags = new HashMap<>();
+ private @NonNull
+ final BentoBox plugin;
+ private final Map<@NonNull Flag, @Nullable Addon> flags = new HashMap<>();
/**
* Stores the flag listeners that have already been registered into Bukkit's API to avoid duplicates.
@@ -32,7 +33,7 @@ public class FlagsManager {
* This helps to make sure each flag listener is loaded correctly.
* @see #registerListeners()
*/
- private Map<@NonNull Listener, @NonNull Boolean> registeredListeners = new HashMap<>();
+ private final Map<@NonNull Listener, @NonNull Boolean> registeredListeners = new HashMap<>();
public FlagsManager(@NonNull BentoBox plugin) {
this.plugin = plugin;
diff --git a/src/main/java/world/bentobox/bentobox/managers/GameModePlaceholderManager.java b/src/main/java/world/bentobox/bentobox/managers/GameModePlaceholderManager.java
index 3bab214d4..ba044cd1f 100644
--- a/src/main/java/world/bentobox/bentobox/managers/GameModePlaceholderManager.java
+++ b/src/main/java/world/bentobox/bentobox/managers/GameModePlaceholderManager.java
@@ -19,7 +19,7 @@ import world.bentobox.bentobox.lists.GameModePlaceholder;
@Deprecated
public class GameModePlaceholderManager {
- private BentoBox plugin;
+ private final BentoBox plugin;
public GameModePlaceholderManager(BentoBox plugin) {
this.plugin = plugin;
diff --git a/src/main/java/world/bentobox/bentobox/managers/HooksManager.java b/src/main/java/world/bentobox/bentobox/managers/HooksManager.java
index 9aa59843b..409fa73a5 100644
--- a/src/main/java/world/bentobox/bentobox/managers/HooksManager.java
+++ b/src/main/java/world/bentobox/bentobox/managers/HooksManager.java
@@ -14,11 +14,11 @@ import world.bentobox.bentobox.api.hooks.Hook;
*/
public class HooksManager {
- private BentoBox plugin;
+ private final BentoBox plugin;
/**
* List of successfully registered hooks.
*/
- private List hooks;
+ private final List hooks;
public HooksManager(BentoBox plugin) {
this.plugin = plugin;
diff --git a/src/main/java/world/bentobox/bentobox/managers/IslandDeletionManager.java b/src/main/java/world/bentobox/bentobox/managers/IslandDeletionManager.java
index 9f7e959eb..99206a296 100644
--- a/src/main/java/world/bentobox/bentobox/managers/IslandDeletionManager.java
+++ b/src/main/java/world/bentobox/bentobox/managers/IslandDeletionManager.java
@@ -26,12 +26,12 @@ import world.bentobox.bentobox.util.Util;
*/
public class IslandDeletionManager implements Listener {
- private BentoBox plugin;
+ private final BentoBox plugin;
/**
* Queue of islands to delete
*/
- private Database handler;
- private Set inDeletion;
+ private final Database handler;
+ private final Set inDeletion;
public IslandDeletionManager(BentoBox plugin) {
this.plugin = plugin;
@@ -52,7 +52,7 @@ public class IslandDeletionManager implements Listener {
plugin.log("There are " + toBeDeleted.size() + " islands pending deletion.");
toBeDeleted.forEach(di -> {
if (di.getLocation() == null || di.getLocation().getWorld() == null) {
- plugin.logError("Island queued for deletion refers to a non-existant game world. Skipping...");
+ plugin.logError("Island queued for deletion refers to a non-existent game world. Skipping...");
toBeRemoved.add(di);
} else {
plugin.log("Resuming deletion of island at " + di.getLocation().getWorld().getName() + " " + Util.xyz(di.getLocation().toVector()));
diff --git a/src/main/java/world/bentobox/bentobox/managers/IslandWorldManager.java b/src/main/java/world/bentobox/bentobox/managers/IslandWorldManager.java
index 18de91cb6..10a2f363a 100644
--- a/src/main/java/world/bentobox/bentobox/managers/IslandWorldManager.java
+++ b/src/main/java/world/bentobox/bentobox/managers/IslandWorldManager.java
@@ -34,11 +34,11 @@ import world.bentobox.bentobox.lists.Flags;
*/
public class IslandWorldManager {
- private BentoBox plugin;
+ private final BentoBox plugin;
/**
* Map associating Worlds (Overworld, Nether and End) with the GameModeAddon that creates them.
*/
- private Map<@NonNull World, @NonNull GameModeAddon> gameModes;
+ private final Map<@NonNull World, @NonNull GameModeAddon> gameModes;
/**
* Manages worlds registered with BentoBox
diff --git a/src/main/java/world/bentobox/bentobox/managers/IslandsManager.java b/src/main/java/world/bentobox/bentobox/managers/IslandsManager.java
index bc0bfb1d8..b7c433759 100644
--- a/src/main/java/world/bentobox/bentobox/managers/IslandsManager.java
+++ b/src/main/java/world/bentobox/bentobox/managers/IslandsManager.java
@@ -66,7 +66,7 @@ import world.bentobox.bentobox.util.teleport.SafeSpotTeleport;
*/
public class IslandsManager {
- private BentoBox plugin;
+ private final BentoBox plugin;
// Tree species to boat material map
private static final Map TREE_TO_BOAT = ImmutableMap.builder().
@@ -81,7 +81,7 @@ public class IslandsManager {
* One island can be spawn, this is the one - otherwise, this value is null
*/
@NonNull
- private Map<@NonNull World, @Nullable Island> spawn;
+ private final Map<@NonNull World, @Nullable Island> spawn;
@NonNull
private Database handler;
@@ -90,20 +90,22 @@ public class IslandsManager {
* The last locations where an island were put.
* This is not stored persistently and resets when the server starts
*/
- private Map last;
+ private final Map last;
// Island Cache
@NonNull
private IslandCache islandCache;
// Quarantined islands
@NonNull
- private Map> quarantineCache;
+ private final Map> quarantineCache;
// Deleted islands
@NonNull
- private List deletedIslands;
+ private final List deletedIslands;
private boolean isSaveTaskRunning;
+ private final Set goingHome;
+
/**
* Islands Manager
* @param plugin - plugin
@@ -119,6 +121,8 @@ public class IslandsManager {
// This list should always be empty unless database deletion failed
// In that case a purge utility may be required in the future
deletedIslands = new ArrayList<>();
+ // Mid-teleport players going home
+ goingHome = new HashSet<>();
}
/**
@@ -144,7 +148,7 @@ public class IslandsManager {
depth = i;
} else {
Optional island = getIslandAt(l);
- if (!island.isPresent()) {
+ if (island.isEmpty()) {
return null;
}
i = island.get().getProtectionRange();
@@ -270,31 +274,12 @@ public class IslandsManager {
return false;
}
// Known unsafe blocks
- switch (ground) {
+ return switch (ground) {
// Unsafe
- case ANVIL:
- case BARRIER:
- case CACTUS:
- case END_PORTAL:
- case END_ROD:
- case FIRE:
- case FLOWER_POT:
- case LADDER:
- case LEVER:
- case TALL_GRASS:
- case PISTON_HEAD:
- case MOVING_PISTON:
- case TORCH:
- case WALL_TORCH:
- case TRIPWIRE:
- case WATER:
- case COBWEB:
- case NETHER_PORTAL:
- case MAGMA_BLOCK:
- return false;
- default:
- return true;
- }
+ case ANVIL, BARRIER, CACTUS, END_PORTAL, END_ROD, FIRE, FLOWER_POT, LADDER, LEVER, TALL_GRASS, PISTON_HEAD,
+ MOVING_PISTON, TORCH, WALL_TORCH, TRIPWIRE, WATER, COBWEB, NETHER_PORTAL, MAGMA_BLOCK -> false;
+ default -> true;
+ };
}
/**
@@ -324,7 +309,7 @@ public class IslandsManager {
// This should never happen, so although this is a potential infinite loop I'm going to leave it here because
// it will be bad if this does occur and the server should crash.
plugin.logWarning("Duplicate island UUID occurred");
- island.setUniqueId(gmName + UUID.randomUUID().toString());
+ island.setUniqueId(gmName + UUID.randomUUID());
}
if (islandCache.addIsland(island)) {
return island;
@@ -453,7 +438,7 @@ public class IslandsManager {
*
* @param world - world to check
* @param uuid - the player's UUID
- * @return Location of the center of the player's protection area or null if an island does not exist.
+ * @return Location of the center of the player's protection area or null if an island does not exist.
* Returns an island location OR a team island location
*/
@Nullable
@@ -503,7 +488,7 @@ public class IslandsManager {
* Will update the value based on world settings or island owner permissions (if online).
* If the island is unowned, then this value will be 0.
* @param island - island
- * @param rank {@link RanksManager.MEMBER_RANK}, {@link RanksManager.COOP_RANK}, or {@link RanksManager.TRUSTED_RANK}
+ * @param rank {@link RanksManager#MEMBER_RANK}, {@link RanksManager#COOP_RANK}, or {@link RanksManager#TRUSTED_RANK}
* @return max number of members. If negative, then this means unlimited.
* @since 1.16.0
*/
@@ -540,7 +525,7 @@ public class IslandsManager {
/**
* Sets the island max member size.
* @param island - island
- * @param rank {@link RanksManager.MEMBER_RANK}, {@link RanksManager.COOP_RANK}, or {@link RanksManager.TRUSTED_RANK}
+ * @param rank {@link RanksManager#MEMBER_RANK}, {@link RanksManager#COOP_RANK}, or {@link RanksManager#TRUSTED_RANK}
* @param maxMembers - max number of members. If negative, then this means unlimited. Null means the world
* default will be used.
* @since 1.16.0
@@ -875,7 +860,7 @@ public class IslandsManager {
}
if (island.getOwner().equals(uuid)) {
// Owner
- island.setHomes(homes.entrySet().stream().collect(Collectors.toMap(this::getHomeName, Map.Entry::getKey)));
+ island.setHomes(homes.entrySet().stream().collect(Collectors.toMap(this::getHomeName, Map.Entry::getKey)));
plugin.getPlayers().clearHomeLocations(world, uuid);
}
}
@@ -919,7 +904,7 @@ public class IslandsManager {
* @since 1.16.0
*/
public boolean removeHomeLocation(@Nullable Island island, String name) {
- return island == null ? false : island.removeHome(name);
+ return island != null && island.removeHome(name);
}
/**
@@ -930,7 +915,7 @@ public class IslandsManager {
* @return true if successful, false if not
*/
public boolean renameHomeLocation(@Nullable Island island, String oldName, String newName) {
- return island == null ? false : island.renameHome(oldName, newName);
+ return island != null && island.renameHome(oldName, newName);
}
/**
@@ -1076,6 +1061,7 @@ public class IslandsManager {
CompletableFuture result = new CompletableFuture<>();
User user = User.getInstance(player);
user.sendMessage("commands.island.go.teleport");
+ goingHome.add(user.getUniqueId());
// Stop any gliding
player.setGliding(false);
// Check if the player is a passenger in a boat
@@ -1172,7 +1158,13 @@ public class IslandsManager {
if (plugin.getIWM().isOnJoinResetXP(world)) {
user.getPlayer().setTotalExperience(0);
}
+
+ // Set the game mode
+ user.setGameMode(plugin.getIWM().getDefaultGameMode(world));
+
}
+ // Remove from mid-teleport set
+ goingHome.remove(user.getUniqueId());
}
/**
@@ -1200,7 +1192,7 @@ public class IslandsManager {
player.leaveVehicle();
// Remove the boat so they don't lie around everywhere
boat.remove();
- Material boatMat = Material.getMaterial(((Boat) boat).getWoodType().toString() + "_BOAT");
+ Material boatMat = Material.getMaterial(((Boat) boat).getWoodType() + "_BOAT");
if (boatMat == null) {
boatMat = Material.OAK_BOAT;
}
@@ -1796,7 +1788,7 @@ public class IslandsManager {
* @since 1.7.0
*/
public boolean nameExists(@NonNull World world, @NonNull String name) {
- return getIslands(world).stream().filter(island -> island.getName() != null).map(Island::getName)
+ return getIslands(world).stream().map(Island::getName).filter(Objects::nonNull)
.anyMatch(n -> ChatColor.stripColor(n).equals(ChatColor.stripColor(name)));
}
@@ -1898,4 +1890,12 @@ public class IslandsManager {
return r;
}
+ /**
+ * Is user mid home teleport?
+ * @return true or false
+ */
+ public boolean isGoingHome(User user) {
+ return goingHome.contains(user.getUniqueId());
+ }
+
}
diff --git a/src/main/java/world/bentobox/bentobox/managers/LocalesManager.java b/src/main/java/world/bentobox/bentobox/managers/LocalesManager.java
index 9f0a4838e..934148c78 100644
--- a/src/main/java/world/bentobox/bentobox/managers/LocalesManager.java
+++ b/src/main/java/world/bentobox/bentobox/managers/LocalesManager.java
@@ -35,8 +35,8 @@ import world.bentobox.bentobox.util.Util;
*/
public class LocalesManager {
- private BentoBox plugin;
- private Map languages = new HashMap<>();
+ private final BentoBox plugin;
+ private final Map languages = new HashMap<>();
private static final String LOCALE_FOLDER = "locales";
private static final String BENTOBOX = "BentoBox";
private static final String SPACER = "*************************************************";
diff --git a/src/main/java/world/bentobox/bentobox/managers/PlaceholdersManager.java b/src/main/java/world/bentobox/bentobox/managers/PlaceholdersManager.java
index bf5d8b9ca..b7e538c04 100644
--- a/src/main/java/world/bentobox/bentobox/managers/PlaceholdersManager.java
+++ b/src/main/java/world/bentobox/bentobox/managers/PlaceholdersManager.java
@@ -21,7 +21,7 @@ import world.bentobox.bentobox.lists.GameModePlaceholder;
*/
public class PlaceholdersManager {
- private BentoBox plugin;
+ private final BentoBox plugin;
public PlaceholdersManager(BentoBox plugin) {
this.plugin = plugin;
diff --git a/src/main/java/world/bentobox/bentobox/managers/PlayersManager.java b/src/main/java/world/bentobox/bentobox/managers/PlayersManager.java
index 5d5c260c9..03609dd48 100644
--- a/src/main/java/world/bentobox/bentobox/managers/PlayersManager.java
+++ b/src/main/java/world/bentobox/bentobox/managers/PlayersManager.java
@@ -28,12 +28,12 @@ import world.bentobox.bentobox.util.Util;
public class PlayersManager {
- private BentoBox plugin;
+ private final BentoBox plugin;
private Database handler;
- private Database names;
+ private final Database names;
- private Map playerCache;
- private Set inTeleport;
+ private final Map playerCache;
+ private final Set inTeleport;
private boolean isSaveTaskRunning;
diff --git a/src/main/java/world/bentobox/bentobox/managers/WebManager.java b/src/main/java/world/bentobox/bentobox/managers/WebManager.java
index d06c236b7..dbd5ef1d5 100644
--- a/src/main/java/world/bentobox/bentobox/managers/WebManager.java
+++ b/src/main/java/world/bentobox/bentobox/managers/WebManager.java
@@ -34,11 +34,15 @@ import world.bentobox.bentobox.web.credits.Contributor;
*/
public class WebManager {
- private @NonNull BentoBox plugin;
+ private @NonNull
+ final BentoBox plugin;
private @Nullable GitHubWebAPI gitHub;
- private @NonNull List addonsCatalog;
- private @NonNull List gamemodesCatalog;
- private @NonNull Map> contributors;
+ private @NonNull
+ final List addonsCatalog;
+ private @NonNull
+ final List gamemodesCatalog;
+ private @NonNull
+ final Map> contributors;
public WebManager(@NonNull BentoBox plugin) {
this.plugin = plugin;
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 11d3a117f..532699419 100644
--- a/src/main/java/world/bentobox/bentobox/managers/island/DefaultNewIslandLocationStrategy.java
+++ b/src/main/java/world/bentobox/bentobox/managers/island/DefaultNewIslandLocationStrategy.java
@@ -23,7 +23,7 @@ import world.bentobox.bentobox.util.Util;
public class DefaultNewIslandLocationStrategy implements NewIslandLocationStrategy {
/**
- * The amount times to tolerate island check returning blocks without kwnon
+ * The amount times to tolerate island check returning blocks without known
* island.
*/
protected static final Integer MAX_UNOWNED_ISLANDS = 20;
@@ -102,7 +102,7 @@ public class DefaultNewIslandLocationStrategy implements NewIslandLocationStrate
// Block check
if (plugin.getIWM().isCheckForBlocks(world)
&& !plugin.getIWM().isUseOwnGenerator(world)
- && Arrays.asList(BlockFace.values()).stream().anyMatch(bf ->
+ && Arrays.stream(BlockFace.values()).anyMatch(bf ->
!location.getBlock().getRelative(bf).isEmpty()
&& !location.getBlock().getRelative(bf).getType().equals(Material.WATER))) {
// Block found
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 c0cf5278c..a577d601d 100644
--- a/src/main/java/world/bentobox/bentobox/managers/island/IslandCache.java
+++ b/src/main/java/world/bentobox/bentobox/managers/island/IslandCache.java
@@ -1,15 +1,12 @@
package world.bentobox.bentobox.managers.island;
-import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
-import java.util.stream.Collectors;
import org.bukkit.Location;
import org.bukkit.World;
@@ -115,7 +112,7 @@ public class IslandCache {
grids.putIfAbsent(island.getWorld(), new IslandGrid());
return grids.get(island.getWorld()).removeFromGrid(island);
}
-
+
/**
* Delete island from the cache by ID. Does not remove blocks.
* @param uniqueId - island unique ID
@@ -180,12 +177,10 @@ public class IslandCache {
@NonNull
public Collection getIslands(@NonNull World world) {
World overworld = Util.getWorld(world);
- List islandsInWorld = islandsByLocation.entrySet().stream()
- .filter(entry -> overworld.equals(Util.getWorld(entry.getKey().getWorld()))) // shouldn't make NPEs
- .map(Map.Entry::getValue)
- .collect(Collectors.toCollection(ArrayList::new));
- return Collections.unmodifiableCollection(islandsInWorld);
+ return islandsByLocation.entrySet().stream()
+ .filter(entry -> overworld.equals(Util.getWorld(entry.getKey().getWorld()))) // shouldn't make NPEs
+ .map(Map.Entry::getValue).toList();
}
/**
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 bf49c8dd3..db404f1a3 100644
--- a/src/main/java/world/bentobox/bentobox/managers/island/IslandGrid.java
+++ b/src/main/java/world/bentobox/bentobox/managers/island/IslandGrid.java
@@ -12,8 +12,8 @@ import world.bentobox.bentobox.database.objects.Island;
*
*/
class IslandGrid {
- private TreeMap> grid = new TreeMap<>();
- private BentoBox plugin = BentoBox.getInstance();
+ private final TreeMap> grid = new TreeMap<>();
+ private final BentoBox plugin = BentoBox.getInstance();
/**
* Adds island to grid
@@ -39,7 +39,7 @@ class IslandGrid {
if (firstLoaded.getOwner().equals(island.getOwner())) {
// Find out which one is the original
if (firstLoaded.getCreatedDate() > island.getCreatedDate()) {
- plugin.logError("Same owner duplicate. Swaping based on creation date.");
+ plugin.logError("Same owner duplicate. Swapping based on creation date.");
// FirstLoaded is the newer
firstLoaded = new Island(island);
zEntry.put(island.getMinZ(), firstLoaded);
diff --git a/src/main/java/world/bentobox/bentobox/managers/island/NewIsland.java b/src/main/java/world/bentobox/bentobox/managers/island/NewIsland.java
index 5ccc74dbe..80c2cd9bf 100644
--- a/src/main/java/world/bentobox/bentobox/managers/island/NewIsland.java
+++ b/src/main/java/world/bentobox/bentobox/managers/island/NewIsland.java
@@ -26,14 +26,14 @@ import world.bentobox.bentobox.managers.BlueprintsManager;
*
*/
public class NewIsland {
- private BentoBox plugin;
+ private final BentoBox plugin;
private Island island;
private final User user;
private final Reason reason;
private final World world;
private String name;
private final boolean noPaste;
- private GameModeAddon addon;
+ private final GameModeAddon addon;
private NewIslandLocationStrategy locationStrategy;
diff --git a/src/main/java/world/bentobox/bentobox/nms/NMSAbstraction.java b/src/main/java/world/bentobox/bentobox/nms/NMSAbstraction.java
index 24bca0842..f2e30c157 100644
--- a/src/main/java/world/bentobox/bentobox/nms/NMSAbstraction.java
+++ b/src/main/java/world/bentobox/bentobox/nms/NMSAbstraction.java
@@ -16,6 +16,6 @@ public interface NMSAbstraction {
* @param blockData - block data to set the block
* @param applyPhysics - apply physics or not
*/
- public void setBlockInNativeChunk(Chunk chunk, int x, int y, int z, BlockData blockData, boolean applyPhysics);
+ void setBlockInNativeChunk(Chunk chunk, int x, int y, int z, BlockData blockData, boolean applyPhysics);
}
diff --git a/src/main/java/world/bentobox/bentobox/nms/package-info.java b/src/main/java/world/bentobox/bentobox/nms/package-info.java
new file mode 100644
index 000000000..f0a4744d3
--- /dev/null
+++ b/src/main/java/world/bentobox/bentobox/nms/package-info.java
@@ -0,0 +1,12 @@
+/**
+ * Contains NMS related classes.
+ *
+ *
+ * Due to limitations in Maven and public building on CI's, only the most recent version of Minecraft
+ * is supported.
+ *
+ *
+ * @author tastybento
+ *
+ */
+package world.bentobox.bentobox.nms;
\ No newline at end of file
diff --git a/src/main/java/world/bentobox/bentobox/panels/BlueprintManagementPanel.java b/src/main/java/world/bentobox/bentobox/panels/BlueprintManagementPanel.java
index 304ae8c79..cee6b2d2f 100644
--- a/src/main/java/world/bentobox/bentobox/panels/BlueprintManagementPanel.java
+++ b/src/main/java/world/bentobox/bentobox/panels/BlueprintManagementPanel.java
@@ -9,7 +9,6 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
-import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.World;
@@ -53,7 +52,7 @@ public class BlueprintManagementPanel {
public static final int MAX_BP_SLOT = 35;
private static final String INSTRUCTION = "instruction";
private Entry selected;
- private Map blueprints = new HashMap<>();
+ private final Map blueprints = new HashMap<>();
private final User user;
private final GameModeAddon addon;
@@ -242,7 +241,7 @@ public class BlueprintManagementPanel {
protected PanelItem getBundleIcon(BlueprintBundle bb) {
return new PanelItemBuilder()
.name(t("edit-description"))
- .description(bb.getDescription().stream().map(l -> ChatColor.translateAlternateColorCodes('&', l)).collect(Collectors.toList()))
+ .description(bb.getDescription().stream().map(Util::translateColorCodes).collect(Collectors.toList()))
.icon(bb.getIcon())
.clickHandler((panel, u, clickType, slot) -> {
u.closeInventory();
@@ -257,21 +256,22 @@ public class BlueprintManagementPanel {
Material icon;
String worldName;
switch (env) {
- case NORMAL:
+ case NORMAL -> {
icon = Material.GRASS_BLOCK;
worldName = normalBlueprint.getName();
- break;
- case NETHER:
+ }
+ case NETHER -> {
icon = Material.NETHERRACK;
worldName = netherBlueprint.getName();
- break;
- case THE_END:
+ }
+ case THE_END -> {
icon = Material.END_STONE;
worldName = endBlueprint.getName();
- break;
- default:
+ }
+ default -> {
icon = Material.STONE;
worldName = Util.prettifyText(env.name());
+ }
}
return new PanelItemBuilder()
@@ -339,7 +339,7 @@ public class BlueprintManagementPanel {
protected PanelItem getBlueprintItem(GameModeAddon addon, int pos, BlueprintBundle bb, Blueprint blueprint) {
// Create description
List desc = blueprint.getDescription() == null ? new ArrayList<>() : blueprint.getDescription();
- desc = desc.stream().map(l -> ChatColor.translateAlternateColorCodes('&', l)).collect(Collectors.toList());
+ desc = desc.stream().map(Util::translateColorCodes).collect(Collectors.toList());
if ((!blueprint.equals(endBlueprint) && !blueprint.equals(normalBlueprint) && !blueprint.equals(netherBlueprint))) {
if ((pos > MIN_WORLD_SLOT && pos < MAX_WORLD_SLOT)) {
desc.add(t("remove"));
diff --git a/src/main/java/world/bentobox/bentobox/panels/IconChanger.java b/src/main/java/world/bentobox/bentobox/panels/IconChanger.java
index 7b138e65a..809b15455 100644
--- a/src/main/java/world/bentobox/bentobox/panels/IconChanger.java
+++ b/src/main/java/world/bentobox/bentobox/panels/IconChanger.java
@@ -21,10 +21,10 @@ import world.bentobox.bentobox.blueprints.dataobjects.BlueprintBundle;
*/
public class IconChanger implements PanelListener {
- private GameModeAddon addon;
- private BlueprintBundle bb;
- private BlueprintManagementPanel blueprintManagementPanel;
- private BentoBox plugin;
+ private final GameModeAddon addon;
+ private final BlueprintBundle bb;
+ private final BlueprintManagementPanel blueprintManagementPanel;
+ private final BentoBox plugin;
/**
* Change the icon of a blueprint bundle or blueprint
diff --git a/src/main/java/world/bentobox/bentobox/panels/IslandCreationPanel.java b/src/main/java/world/bentobox/bentobox/panels/IslandCreationPanel.java
index b4d5a21d5..b1a002bc6 100644
--- a/src/main/java/world/bentobox/bentobox/panels/IslandCreationPanel.java
+++ b/src/main/java/world/bentobox/bentobox/panels/IslandCreationPanel.java
@@ -5,7 +5,6 @@ import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
-import org.bukkit.ChatColor;
import org.eclipse.jdt.annotation.NonNull;
import world.bentobox.bentobox.BentoBox;
@@ -16,6 +15,8 @@ import world.bentobox.bentobox.api.panels.builders.PanelItemBuilder;
import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.blueprints.dataobjects.BlueprintBundle;
import world.bentobox.bentobox.managers.BlueprintsManager;
+import world.bentobox.bentobox.util.Util;
+
/**
* Displays the available BlueprintBundles to pick up as the island.
@@ -49,7 +50,7 @@ public class IslandCreationPanel {
// Add an item
PanelItem item = new PanelItemBuilder()
.name(bb.getDisplayName())
- .description(bb.getDescription().stream().map(l -> ChatColor.translateAlternateColorCodes('&', l)).collect(Collectors.toList()))
+ .description(bb.getDescription().stream().map(Util::translateColorCodes).collect(Collectors.toList()))
.icon(bb.getIcon()).clickHandler((panel, user1, clickType, slot1) -> {
user1.closeInventory();
command.execute(user1, label, Collections.singletonList(bb.getUniqueId()));
diff --git a/src/main/java/world/bentobox/bentobox/panels/LanguagePanel.java b/src/main/java/world/bentobox/bentobox/panels/LanguagePanel.java
index cf4c2e830..ca2e96ef0 100644
--- a/src/main/java/world/bentobox/bentobox/panels/LanguagePanel.java
+++ b/src/main/java/world/bentobox/bentobox/panels/LanguagePanel.java
@@ -1,6 +1,7 @@
package world.bentobox.bentobox.panels;
import java.util.Locale;
+import java.util.Objects;
import org.apache.commons.lang.WordUtils;
import org.bukkit.ChatColor;
@@ -38,11 +39,8 @@ public class LanguagePanel {
BentoBoxLocale language = localesManager.getLanguages().get(locale);
ItemStack localeBanner = language.getBanner();
- if (localeBanner != null) {
- localeIcon.icon(localeBanner);
- } else {
- localeIcon.icon(new ItemStack(Material.WHITE_BANNER, 1)); // Set to a blank banner.
- }
+ // Set to a blank banner.
+ localeIcon.icon(Objects.requireNonNullElseGet(localeBanner, () -> new ItemStack(Material.WHITE_BANNER, 1)));
localeIcon.name(ChatColor.WHITE + WordUtils.capitalize(locale.getDisplayName(user.getLocale())))
.clickHandler((panel, u, click, slot) -> {
BentoBox.getInstance().getPlayers().setLocale(u.getUniqueId(), locale.toLanguageTag());
diff --git a/src/main/java/world/bentobox/bentobox/panels/ManagementPanel.java b/src/main/java/world/bentobox/bentobox/panels/ManagementPanel.java
index b1f5a0e6e..3c6293c6a 100644
--- a/src/main/java/world/bentobox/bentobox/panels/ManagementPanel.java
+++ b/src/main/java/world/bentobox/bentobox/panels/ManagementPanel.java
@@ -53,86 +53,86 @@ public class ManagementPanel {
int i = 0;
List extends Addon> addons;
switch (view) {
- case GAMEMODES:
- addons = plugin.getAddonsManager().getGameModeAddons();
- if (addons.isEmpty()) {
- looksEmpty(builder, user);
- break;
- }
- for (Addon addon : addons) {
- GameModeAddon gameModeAddon = (GameModeAddon) addon;
- PanelItem addonItem = new PanelItemBuilder()
- .icon(addon.getDescription().getIcon())
- .name(user.getTranslation(LOCALE_REF + "views.gamemodes.gamemode.name", TextVariables.NAME, addon.getDescription().getName()))
- .description(user.getTranslation(LOCALE_REF + "views.gamemodes.gamemode.description",
- "[islands]", String.valueOf(addon.getIslands().getIslandCount(gameModeAddon.getOverWorld()))))
- .clickHandler((panel, user1, clickType, slot) -> {
- if (clickType.equals(ClickType.MIDDLE)) {
- CreditsPanel.openPanel(user, addon);
- }
- return true;
- })
- .build();
+ case GAMEMODES -> {
+ addons = plugin.getAddonsManager().getGameModeAddons();
+ if (addons.isEmpty()) {
+ looksEmpty(builder, user);
+ break;
+ }
+ for (Addon addon : addons) {
+ GameModeAddon gameModeAddon = (GameModeAddon) addon;
+ PanelItem addonItem = new PanelItemBuilder()
+ .icon(addon.getDescription().getIcon())
+ .name(user.getTranslation(LOCALE_REF + "views.gamemodes.gamemode.name", TextVariables.NAME, addon.getDescription().getName()))
+ .description(user.getTranslation(LOCALE_REF + "views.gamemodes.gamemode.description",
+ "[islands]", String.valueOf(addon.getIslands().getIslandCount(gameModeAddon.getOverWorld()))))
+ .clickHandler((panel, user1, clickType, slot) -> {
+ if (clickType.equals(ClickType.MIDDLE)) {
+ CreditsPanel.openPanel(user, addon);
+ }
+ return true;
+ })
+ .build();
- builder.item(startSlot + i, addonItem);
+ builder.item(startSlot + i, addonItem);
- PanelItem blueprints = new PanelItemBuilder()
- .icon(Material.STRUCTURE_BLOCK)
- .name(user.getTranslation(LOCALE_REF + "views.gamemodes.blueprints.name"))
- .description(user.getTranslation(LOCALE_REF + "views.gamemodes.blueprints.description"))
- .clickHandler((panel, user1, clickType, slot) -> {
- new BlueprintManagementPanel(plugin, user, gameModeAddon).openPanel();
- return true;
- })
- .build();
+ PanelItem blueprints = new PanelItemBuilder()
+ .icon(Material.STRUCTURE_BLOCK)
+ .name(user.getTranslation(LOCALE_REF + "views.gamemodes.blueprints.name"))
+ .description(user.getTranslation(LOCALE_REF + "views.gamemodes.blueprints.description"))
+ .clickHandler((panel, user1, clickType, slot) -> {
+ new BlueprintManagementPanel(plugin, user, gameModeAddon).openPanel();
+ return true;
+ })
+ .build();
- builder.item(startSlot + i + 9, blueprints);
- i++;
- }
- break;
- case ADDONS:
- addons = plugin.getAddonsManager().getEnabledAddons().stream().filter(addon -> !(addon instanceof GameModeAddon)).collect(Collectors.toList());
- if (addons.isEmpty()) {
- looksEmpty(builder, user);
- break;
- }
- for (Addon addon : addons) {
- PanelItem addonItem = new PanelItemBuilder()
- .icon(addon.getDescription().getIcon())
- .name(ChatColor.WHITE + addon.getDescription().getName())
- .clickHandler((panel, user1, clickType, slot) -> {
- if (clickType.equals(ClickType.MIDDLE)) {
- CreditsPanel.openPanel(user, addon);
- }
- return true;
- })
- .build();
-
- builder.item(startSlot + i, addonItem);
- i++;
- if (builder.slotOccupied(startSlot + i)) {
- i = i+2;
+ builder.item(startSlot + i + 9, blueprints);
+ i++;
}
}
- break;
- case HOOKS:
- if (plugin.getHooks().getHooks().isEmpty()) {
- looksEmpty(builder, user);
- break;
- }
- for (Hook hook : plugin.getHooks().getHooks()) {
- PanelItem hookItem = new PanelItemBuilder()
- .icon(hook.getIcon())
- .name(ChatColor.WHITE + hook.getPluginName())
- .build();
+ case ADDONS -> {
+ addons = plugin.getAddonsManager().getEnabledAddons().stream().filter(addon -> !(addon instanceof GameModeAddon)).collect(Collectors.toList());
+ if (addons.isEmpty()) {
+ looksEmpty(builder, user);
+ break;
+ }
+ for (Addon addon : addons) {
+ PanelItem addonItem = new PanelItemBuilder()
+ .icon(addon.getDescription().getIcon())
+ .name(ChatColor.WHITE + addon.getDescription().getName())
+ .clickHandler((panel, user1, clickType, slot) -> {
+ if (clickType.equals(ClickType.MIDDLE)) {
+ CreditsPanel.openPanel(user, addon);
+ }
+ return true;
+ })
+ .build();
- builder.item(startSlot + i, hookItem);
- i++;
- if (builder.slotOccupied(startSlot + i)) {
- i = i+2;
+ builder.item(startSlot + i, addonItem);
+ i++;
+ if (builder.slotOccupied(startSlot + i)) {
+ i = i + 2;
+ }
+ }
+ }
+ case HOOKS -> {
+ if (plugin.getHooks().getHooks().isEmpty()) {
+ looksEmpty(builder, user);
+ break;
+ }
+ for (Hook hook : plugin.getHooks().getHooks()) {
+ PanelItem hookItem = new PanelItemBuilder()
+ .icon(hook.getIcon())
+ .name(ChatColor.WHITE + hook.getPluginName())
+ .build();
+
+ builder.item(startSlot + i, hookItem);
+ i++;
+ if (builder.slotOccupied(startSlot + i)) {
+ i = i + 2;
+ }
}
}
- break;
}
// Setup a few more buttons
@@ -196,15 +196,9 @@ public class ManagementPanel {
});
switch (view) {
- case GAMEMODES:
- gamemodesIconBuilder.glow(true);
- break;
- case ADDONS:
- addonsIconBuilder.glow(true);
- break;
- case HOOKS:
- hooksIconBuilder.glow(true);
- break;
+ case GAMEMODES -> gamemodesIconBuilder.glow(true);
+ case ADDONS -> addonsIconBuilder.glow(true);
+ case HOOKS -> hooksIconBuilder.glow(true);
}
builder.item(1, gamemodesIconBuilder.build());
@@ -235,16 +229,9 @@ public class ManagementPanel {
TextVariables.VERSION, serverVersion != null ? serverVersion.toString() : user.getTranslation("general.invalid")));
switch (compatibility) {
- case COMPATIBLE:
- case SUPPORTED:
- compatibilityItemBuilder.icon(Material.GREEN_CONCRETE);
- break;
- case NOT_SUPPORTED:
- compatibilityItemBuilder.icon(Material.ORANGE_CONCRETE);
- break;
- case INCOMPATIBLE:
- compatibilityItemBuilder.icon(Material.RED_CONCRETE);
- break;
+ case COMPATIBLE, SUPPORTED -> compatibilityItemBuilder.icon(Material.GREEN_CONCRETE);
+ case NOT_SUPPORTED -> compatibilityItemBuilder.icon(Material.ORANGE_CONCRETE);
+ case INCOMPATIBLE -> compatibilityItemBuilder.icon(Material.RED_CONCRETE);
}
builder.item(7, compatibilityItemBuilder.build());
diff --git a/src/main/java/world/bentobox/bentobox/panels/package-info.java b/src/main/java/world/bentobox/bentobox/panels/package-info.java
new file mode 100644
index 000000000..48ad3f9c2
--- /dev/null
+++ b/src/main/java/world/bentobox/bentobox/panels/package-info.java
@@ -0,0 +1,11 @@
+/**
+ * Contains non-API panel implementations used by BentoBox
+ *
+ *
+ * These are GUIs such as the settings, blueprints, island creation panels, etc.
+ * They use the Panel API.
+ *
+ * @author tastybento
+ *
+ */
+package world.bentobox.bentobox.panels;
\ No newline at end of file
diff --git a/src/main/java/world/bentobox/bentobox/panels/settings/SettingsTab.java b/src/main/java/world/bentobox/bentobox/panels/settings/SettingsTab.java
index 9e9e2d97c..cc3dcbcd7 100644
--- a/src/main/java/world/bentobox/bentobox/panels/settings/SettingsTab.java
+++ b/src/main/java/world/bentobox/bentobox/panels/settings/SettingsTab.java
@@ -135,27 +135,22 @@ public class SettingsTab implements Tab, ClickHandler {
icons.put(5, Flags.LOCK.toPanelItem(plugin, user, island, false));
}
// Add the mode icon
- switch(plugin.getPlayers().getFlagsDisplayMode(user.getUniqueId())) {
- case ADVANCED:
- icons.put(7, new PanelItemBuilder().icon(Material.GOLD_INGOT)
+ switch (plugin.getPlayers().getFlagsDisplayMode(user.getUniqueId())) {
+ case ADVANCED -> icons.put(7, new PanelItemBuilder().icon(Material.GOLD_INGOT)
.name(user.getTranslation(PROTECTION_PANEL + "mode.advanced.name"))
.description(user.getTranslation(PROTECTION_PANEL + "mode.advanced.description"), "",
user.getTranslation(CLICK_TO_SWITCH,
TextVariables.NEXT, user.getTranslation(PROTECTION_PANEL + "mode.expert.name")))
.clickHandler(this)
.build());
- break;
- case EXPERT:
- icons.put(7, new PanelItemBuilder().icon(Material.NETHER_BRICK)
+ case EXPERT -> icons.put(7, new PanelItemBuilder().icon(Material.NETHER_BRICK)
.name(user.getTranslation(PROTECTION_PANEL + "mode.expert.name"))
.description(user.getTranslation(PROTECTION_PANEL + "mode.expert.description"), "",
user.getTranslation(CLICK_TO_SWITCH,
TextVariables.NEXT, user.getTranslation(PROTECTION_PANEL + "mode.basic.name")))
.clickHandler(this)
.build());
- break;
- default:
- icons.put(7, new PanelItemBuilder().icon(Material.IRON_INGOT)
+ default -> icons.put(7, new PanelItemBuilder().icon(Material.IRON_INGOT)
.name(user.getTranslation(PROTECTION_PANEL + "mode.basic.name"))
.description(user.getTranslation(PROTECTION_PANEL + "mode.basic.description"), "",
user.getTranslation(CLICK_TO_SWITCH,
@@ -219,8 +214,7 @@ public class SettingsTab implements Tab, ClickHandler {
public boolean onClick(Panel panel, User user, ClickType clickType, int slot) {
// Cycle the mode
plugin.getPlayers().setFlagsDisplayMode(user.getUniqueId(), plugin.getPlayers().getFlagsDisplayMode(user.getUniqueId()).getNext());
- if (panel instanceof TabbedPanel) {
- TabbedPanel tp = ((TabbedPanel)panel);
+ if (panel instanceof TabbedPanel tp) {
tp.setActivePage(0);
tp.refreshPanel();
user.getPlayer().playSound(user.getLocation(), Sound.BLOCK_STONE_BUTTON_CLICK_OFF, 1F, 1F);
diff --git a/src/main/java/world/bentobox/bentobox/util/DeleteIslandChunks.java b/src/main/java/world/bentobox/bentobox/util/DeleteIslandChunks.java
index fc81f2104..593b550d8 100644
--- a/src/main/java/world/bentobox/bentobox/util/DeleteIslandChunks.java
+++ b/src/main/java/world/bentobox/bentobox/util/DeleteIslandChunks.java
@@ -7,7 +7,6 @@ import java.util.concurrent.CompletableFuture;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
-import org.bukkit.World.Environment;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.generator.ChunkGenerator;
@@ -33,22 +32,38 @@ public class DeleteIslandChunks {
private int chunkX;
private int chunkZ;
private BukkitTask task;
- private IslandDeletion di;
+ private final IslandDeletion di;
private boolean inDelete;
- private BentoBox plugin;
+ private final BentoBox plugin;
private NMSAbstraction nms;
+ private final World netherWorld;
+ private final World endWorld;
public DeleteIslandChunks(BentoBox plugin, IslandDeletion di) {
this.plugin = plugin;
this.chunkX = di.getMinXChunk();
this.chunkZ = di.getMinZChunk();
this.di = di;
+ // Nether
+ if (plugin.getIWM().isNetherGenerate(di.getWorld()) && plugin.getIWM().isNetherIslands(di.getWorld())) {
+ netherWorld = plugin.getIWM().getNetherWorld(di.getWorld());
+ } else {
+ netherWorld = null;
+ }
+ // End
+ if (plugin.getIWM().isEndGenerate(di.getWorld()) && plugin.getIWM().isEndIslands(di.getWorld())) {
+ endWorld = plugin.getIWM().getEndWorld(di.getWorld());
+ } else {
+ endWorld = null;
+ }
+ // NMS
try {
this.nms = Util.getNMS();
} catch (Exception e) {
plugin.logError("Could not delete chunks because of NMS error");
return;
}
+
// Fire event
IslandEvent.builder().deletedIslandInfo(di).reason(Reason.DELETE_CHUNKS).build();
regenerateChunks();
@@ -62,13 +77,15 @@ public class DeleteIslandChunks {
inDelete = true;
for (int i = 0; i < plugin.getSettings().getDeleteSpeed(); i++) {
boolean last = i == plugin.getSettings().getDeleteSpeed() -1;
+ final int x = chunkX;
+ final int z = chunkZ;
plugin.getIWM().getAddon(di.getWorld()).ifPresent(gm ->
// Overworld
- processChunk(gm, Environment.NORMAL, chunkX, chunkZ).thenRun(() ->
+ processChunk(gm, di.getWorld(), x, z).thenRun(() ->
// Nether
- processChunk(gm, Environment.NETHER, chunkX, chunkZ).thenRun(() ->
+ processChunk(gm, netherWorld, x, z).thenRun(() ->
// End
- processChunk(gm, Environment.THE_END, chunkX, chunkZ).thenRun(() -> finish(last)))));
+ processChunk(gm, endWorld, x, z).thenRun(() -> finish(last, x)))));
chunkZ++;
if (chunkZ > di.getMaxZChunk()) {
chunkZ = di.getMinZChunk();
@@ -79,8 +96,8 @@ public class DeleteIslandChunks {
}
- private void finish(boolean last) {
- if (chunkX > di.getMaxXChunk()) {
+ private void finish(boolean last, int x) {
+ if (x > di.getMaxXChunk()) {
// Fire event
IslandEvent.builder().deletedIslandInfo(di).reason(Reason.DELETED).build();
// We're done
@@ -91,41 +108,26 @@ public class DeleteIslandChunks {
}
}
- private CompletableFuture processChunk(GameModeAddon gm, Environment env, int x, int z) {
- World world = di.getWorld();
- switch (env) {
- case NETHER:
- // Nether
- if (plugin.getIWM().isNetherGenerate(di.getWorld()) && plugin.getIWM().isNetherIslands(di.getWorld())) {
- world = plugin.getIWM().getNetherWorld(di.getWorld());
- } else {
- return CompletableFuture.completedFuture(false);
- }
- break;
- case THE_END:
- // End
- if (plugin.getIWM().isEndGenerate(di.getWorld()) && plugin.getIWM().isEndIslands(di.getWorld())) {
- world = plugin.getIWM().getEndWorld(di.getWorld());
- } else {
- return CompletableFuture.completedFuture(false);
- }
- break;
- default:
- break;
- }
- if (PaperLib.isChunkGenerated(world, x, z)) {
+ private CompletableFuture processChunk(GameModeAddon gm, World world, int x, int z) {
+ if (world != null) {
CompletableFuture r = new CompletableFuture<>();
- PaperLib.getChunkAtAsync(world, x, z).thenAccept(chunk -> regenerateChunk(r, gm, chunk));
+ PaperLib.getChunkAtAsync(world, x, z).thenAccept(chunk -> regenerateChunk(r, gm, chunk, x, z));
return r;
}
return CompletableFuture.completedFuture(false);
}
- private void regenerateChunk(CompletableFuture r, GameModeAddon gm, Chunk chunk) {
+ private void regenerateChunk(CompletableFuture r, GameModeAddon gm, Chunk chunk, int x, int z) {
// Clear all inventories
Arrays.stream(chunk.getTileEntities()).filter(te -> (te instanceof InventoryHolder))
.filter(te -> di.inBounds(te.getLocation().getBlockX(), te.getLocation().getBlockZ()))
.forEach(te -> ((InventoryHolder)te).getInventory().clear());
+ // Remove all entities
+ for (Entity e : chunk.getEntities()) {
+ if (!(e instanceof Player)) {
+ e.remove();
+ }
+ }
// Reset blocks
MyBiomeGrid grid = new MyBiomeGrid(chunk.getWorld().getEnvironment());
ChunkGenerator cg = gm.getDefaultWorldGenerator(chunk.getWorld().getName(), "delete");
diff --git a/src/main/java/world/bentobox/bentobox/util/FileLister.java b/src/main/java/world/bentobox/bentobox/util/FileLister.java
index 836ad575b..42e027d12 100644
--- a/src/main/java/world/bentobox/bentobox/util/FileLister.java
+++ b/src/main/java/world/bentobox/bentobox/util/FileLister.java
@@ -20,7 +20,7 @@ import org.bukkit.plugin.java.JavaPlugin;
* @author Poslovitch
*/
public class FileLister{
- private Plugin plugin;
+ private final Plugin plugin;
public FileLister(Plugin level){
plugin = level;
diff --git a/src/main/java/world/bentobox/bentobox/util/IslandInfo.java b/src/main/java/world/bentobox/bentobox/util/IslandInfo.java
new file mode 100644
index 000000000..99886efd0
--- /dev/null
+++ b/src/main/java/world/bentobox/bentobox/util/IslandInfo.java
@@ -0,0 +1,140 @@
+package world.bentobox.bentobox.util;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.UUID;
+
+import org.bukkit.Bukkit;
+import org.bukkit.World;
+import org.bukkit.util.Vector;
+import org.eclipse.jdt.annotation.Nullable;
+
+import world.bentobox.bentobox.BentoBox;
+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.RanksManager;
+
+/**
+ * @author tastybento
+ * @since 1.17.3
+ */
+public class IslandInfo {
+
+ private final BentoBox plugin;
+ private final Island island;
+ private final @Nullable UUID owner;
+ private final World world;
+
+
+ /**
+ * @param plugin
+ * @param island Island to show info
+ */
+ public IslandInfo(Island island) {
+ this.plugin = BentoBox.getInstance();
+ this.island = island;
+ this.owner = island.getOwner();
+ this.world = island.getWorld();
+ }
+
+ /**
+ * Shows admin info of this island
+ * @param user user asking
+ */
+ public void showAdminInfo(User user) {
+ user.sendMessage("commands.admin.info.title");
+ user.sendMessage("commands.admin.info.island-uuid", "[uuid]", island.getUniqueId());
+ if (owner == null) {
+ user.sendMessage("commands.admin.info.unowned");
+ } else {
+ user.sendMessage("commands.admin.info.owner", "[owner]", plugin.getPlayers().getName(owner), "[uuid]", owner.toString());
+
+ // Fixes #getLastPlayed() returning 0 when it is the owner's first connection.
+ long lastPlayed = (Bukkit.getOfflinePlayer(owner).getLastPlayed() != 0) ?
+ Bukkit.getOfflinePlayer(owner).getLastPlayed() : Bukkit.getOfflinePlayer(owner).getFirstPlayed();
+ String formattedDate;
+ try {
+ String dateTimeFormat = plugin.getLocalesManager().get("commands.admin.info.last-login-date-time-format");
+ formattedDate = new SimpleDateFormat(dateTimeFormat).format(new Date(lastPlayed));
+ } catch (NullPointerException | IllegalArgumentException ignored) {
+ formattedDate = new Date(lastPlayed).toString();
+ }
+ user.sendMessage("commands.admin.info.last-login","[date]", formattedDate);
+
+ user.sendMessage("commands.admin.info.deaths", "[number]", String.valueOf(plugin.getPlayers().getDeaths(world, owner)));
+ String resets = String.valueOf(plugin.getPlayers().getResets(world, owner));
+ String total = plugin.getIWM().getResetLimit(world) < 0 ? "Unlimited" : String.valueOf(plugin.getIWM().getResetLimit(world));
+ user.sendMessage("commands.admin.info.resets-left", "[number]", resets, "[total]", total);
+ // Show team members
+ showMembers(user);
+ }
+ Vector location = island.getProtectionCenter().toVector();
+ user.sendMessage("commands.admin.info.island-protection-center", TextVariables.XYZ, Util.xyz(location));
+ user.sendMessage("commands.admin.info.island-center", TextVariables.XYZ, Util.xyz(island.getCenter().toVector()));
+ user.sendMessage("commands.admin.info.island-coords", "[xz1]", Util.xyz(new Vector(island.getMinX(), 0, island.getMinZ())), "[xz2]", Util.xyz(new Vector(island.getMaxX(), 0, island.getMaxZ())));
+ user.sendMessage("commands.admin.info.protection-range", "[range]", String.valueOf(island.getProtectionRange()));
+ user.sendMessage("commands.admin.info.max-protection-range", "[range]", String.valueOf(island.getMaxEverProtectionRange()));
+ user.sendMessage("commands.admin.info.protection-coords", "[xz1]", Util.xyz(new Vector(island.getMinProtectedX(), 0, island.getMinProtectedZ())), "[xz2]", Util.xyz(new Vector(island.getMaxProtectedX(), 0, island.getMaxProtectedZ())));
+ if (island.isSpawn()) {
+ user.sendMessage("commands.admin.info.is-spawn");
+ }
+ if (!island.getBanned().isEmpty()) {
+ user.sendMessage("commands.admin.info.banned-players");
+ island.getBanned().forEach(u -> user.sendMessage("commands.admin.info.banned-format", TextVariables.NAME, plugin.getPlayers().getName(u)));
+ }
+ if (island.getPurgeProtected()) {
+ user.sendMessage("commands.admin.info.purge-protected");
+ }
+ }
+
+
+ /**
+ * Shows info of this island to this user.
+ * @param user the User who is requesting it
+ * @return always true
+ */
+ public boolean showInfo(User user) {
+ user.sendMessage("commands.admin.info.title");
+ if (owner == null) {
+ user.sendMessage("commands.admin.info.unowned");
+ } else {
+ user.sendMessage("commands.admin.info.owner", "[owner]", plugin.getPlayers().getName(owner));
+ user.sendMessage("commands.admin.info.deaths", "[number]", String.valueOf(plugin.getPlayers().getDeaths(world, owner)));
+ String resets = String.valueOf(plugin.getPlayers().getResets(world, owner));
+ String total = plugin.getIWM().getResetLimit(world) < 0 ? "Unlimited" : String.valueOf(plugin.getIWM().getResetLimit(world));
+ user.sendMessage("commands.admin.info.resets-left", "[number]", resets, "[total]", total);
+ // Show team members
+ showMembers(user);
+ }
+ Vector location = island.getProtectionCenter().toVector();
+ user.sendMessage("commands.admin.info.island-center", TextVariables.XYZ, Util.xyz(location));
+ user.sendMessage("commands.admin.info.protection-range", "[range]", String.valueOf(island.getProtectionRange()));
+ user.sendMessage("commands.admin.info.protection-coords", "[xz1]", Util.xyz(new Vector(island.getMinProtectedX(), 0, island.getMinProtectedZ())), "[xz2]", Util.xyz(new Vector(island.getMaxProtectedX(), 0, island.getMaxProtectedZ())));
+ if (island.isSpawn()) {
+ user.sendMessage("commands.admin.info.is-spawn");
+ }
+ if (!island.getBanned().isEmpty()) {
+ user.sendMessage("commands.admin.info.banned-players");
+ island.getBanned().forEach(u -> user.sendMessage("commands.admin.info.banned-format", TextVariables.NAME, plugin.getPlayers().getName(u)));
+ }
+ return true;
+ }
+
+ /**
+ * Shows the members of this island to this user.
+ * @param user the User who is requesting it
+ */
+ public void showMembers(User user) {
+ user.sendMessage("commands.admin.info.team-members-title");
+ island.getMembers().forEach((u, i) -> {
+ if (owner.equals(u)) {
+ user.sendMessage("commands.admin.info.team-owner-format", TextVariables.NAME, plugin.getPlayers().getName(u)
+ , "[rank]", user.getTranslation(plugin.getRanksManager().getRank(i)));
+ } else if (i > RanksManager.VISITOR_RANK){
+ user.sendMessage("commands.admin.info.team-member-format", TextVariables.NAME, plugin.getPlayers().getName(u)
+ , "[rank]", user.getTranslation(plugin.getRanksManager().getRank(i)));
+ }
+ });
+ }
+}
diff --git a/src/main/java/world/bentobox/bentobox/util/ItemParser.java b/src/main/java/world/bentobox/bentobox/util/ItemParser.java
index 7b751483b..feb21ae42 100644
--- a/src/main/java/world/bentobox/bentobox/util/ItemParser.java
+++ b/src/main/java/world/bentobox/bentobox/util/ItemParser.java
@@ -1,17 +1,25 @@
package world.bentobox.bentobox.util;
+import com.mojang.authlib.GameProfile;
+import com.mojang.authlib.properties.Property;
+import org.bukkit.Bukkit;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.block.banner.Pattern;
import org.bukkit.block.banner.PatternType;
import org.bukkit.inventory.ItemStack;
-import org.bukkit.inventory.meta.BannerMeta;
-import org.bukkit.inventory.meta.PotionMeta;
+import org.bukkit.inventory.meta.*;
import org.bukkit.potion.PotionData;
import org.bukkit.potion.PotionType;
+import org.eclipse.jdt.annotation.Nullable;
+
+import java.lang.reflect.Field;
+import java.util.MissingFormatArgumentException;
+import java.util.UUID;
import world.bentobox.bentobox.BentoBox;
+
/**
* Utility class that parses a String into an ItemStack.
* It is used for converting config file entries to objects.
@@ -20,63 +28,123 @@ import world.bentobox.bentobox.BentoBox;
*/
public class ItemParser {
- private ItemParser() {}
-
- public static ItemStack parse(String s){
- if (s == null) {
- return null;
- }
- String[] part = s.split(":");
-
- // Material-specific handling
- if (part[0].contains("POTION") || part[0].equalsIgnoreCase("TIPPED_ARROW")) {
- return potion(part);
- } else if (part[0].contains("BANNER")) {
- return banner(part);
- }
-
- // Generic handling
- if (part.length == 2) {
- // Material:Qty
- return two(part);
- } else if (part.length == 3) {
- // Material:Durability:Qty
- return three(part);
- }
- return null;
+ /**
+ * Parse given string to ItemStack.
+ * @param text String value of item stack.
+ * @return ItemStack of parsed item or null.
+ */
+ public static ItemStack parse(String text) {
+ return ItemParser.parse(text, null);
}
- private static ItemStack two(String[] part) {
- int reqAmount;
- try {
- reqAmount = Integer.parseInt(part[1]);
- } catch (Exception e) {
- return null;
+
+ /**
+ * Parse given string to ItemStack.
+ * @param text String value of item stack.
+ * @param defaultItemStack Material that should be returned if parsing failed.
+ * @return ItemStack of parsed item or defaultItemStack.
+ */
+ @Nullable
+ public static ItemStack parse(@Nullable String text, @Nullable ItemStack defaultItemStack) {
+ if (text == null || text.isBlank()) {
+ // Text does not exist or is empty.
+ return defaultItemStack;
}
- Material reqItem = Material.getMaterial(part[0].toUpperCase(java.util.Locale.ENGLISH));
- if (reqItem == null) {
- return null;
+ String[] part = text.split(":");
+
+ try {
+ // Check if there are more properties for the item stack
+ if (part.length == 1) {
+ // Parse material directly. It does not have any extra properties.
+ return new ItemStack(Material.valueOf(text.toUpperCase()));
+ }
+ // Material-specific handling
+ else if (part[0].contains("POTION") || part[0].equalsIgnoreCase("TIPPED_ARROW")) {
+ // Parse Potions and Tipped Arrows
+ return parsePotion(part);
+ } else if (part[0].contains("BANNER")) {
+ // Parse Banners
+ return parseBanner(part);
+ } else if (part[0].equalsIgnoreCase("PLAYER_HEAD")) {
+ // Parse Player Heads
+ return parsePlayerHead(part);
+ }
+ // Generic handling
+ else if (part.length == 2) {
+ // Material:Qty
+ return parseItemQuantity(part);
+ } else if (part.length == 3) {
+ // Material:Durability:Qty
+ return parseItemDurabilityAndQuantity(part);
+ }
+ } catch (Exception exception) {
+ BentoBox.getInstance().logError("Could not parse item " + text + " " + exception.getLocalizedMessage());
}
+
+ return defaultItemStack;
+ }
+
+
+ /**
+ * This method parses array of 2 items into an item stack.
+ * First array element is material, while second array element is integer, that represents item count.
+ * Example:
+ * DIAMOND:20
+ * @param part String array that contains 2 elements.
+ * @return ItemStack with material from first array element and amount based on second array element.
+ */
+ private static ItemStack parseItemQuantity(String[] part) {
+ int reqAmount = Integer.parseInt(part[1]);
+ Material reqItem = Material.getMaterial(part[0].toUpperCase(java.util.Locale.ENGLISH));
+
+ if (reqItem == null) {
+ throw new IllegalArgumentException(part[0] + " is not a valid Material.");
+ }
+
return new ItemStack(reqItem, reqAmount);
}
- private static ItemStack three(String[] part) {
+
+ /**
+ * This method parses array of 3 items into an item stack.
+ * First array element is material, while second and third array element are integers.
+ * The middle element represents durability, while third element represents quantity.
+ * Example:
+ * IRON_SWORD:20:1
+ * @param part String array that contains 3 elements.
+ * @return ItemStack with material from first array element, durability from second element and amount based on third array element.
+ */
+ private static ItemStack parseItemDurabilityAndQuantity(String[] part) {
// Rearrange
- String[] twoer = {part[0], part[2]};
- return two(twoer);
+ String[] parsable = {part[0], part[2]};
+ ItemStack durability = parseItemQuantity(parsable);
+
+ ItemMeta meta = durability.getItemMeta();
+
+ if (meta instanceof Damageable) {
+ ((Damageable) meta).setDamage(Integer.parseInt(part[1]));
+ durability.setItemMeta(meta);
+ }
+
+ return durability;
}
- private static ItemStack potion(String[] part) {
+
+ /**
+ * This method parses array of 6 items into an item stack.
+ * Format:
+ * POTION:NAME::::QTY
+ * Example:
+ * POTION:STRENGTH:1:EXTENDED:SPLASH:1
+ * @param part String array that contains 6 elements.
+ * @return Potion with given properties.
+ */
+ private static ItemStack parsePotion(String[] part) {
if (part.length != 6) {
- return null;
- }
- int reqAmount;
- try {
- reqAmount = Integer.parseInt(part[5]);
- } catch (Exception e) {
- return null;
+ throw new MissingFormatArgumentException("Potion parsing requires 6 parts.");
}
+
/*
* # Format POTION:NAME::::QTY
# LEVEL, EXTENDED, SPLASH, LINGER are optional.
@@ -103,35 +171,118 @@ public class ItemParser {
boolean isExtended = part[3].equalsIgnoreCase("EXTENDED");
PotionData data = new PotionData(type, isExtended, isUpgraded);
potionMeta.setBasePotionData(data);
-
- result.setAmount(reqAmount);
+ result.setItemMeta(potionMeta);
+ result.setAmount(Integer.parseInt(part[5]));
return result;
}
- private static ItemStack banner(String[] part) {
- try {
- if (part.length >= 2) {
- Material bannerMat = Material.getMaterial(part[0]);
- if (bannerMat == null) {
- BentoBox.getInstance().logError("Could not parse banner item " + part[0] + " so using a white banner.");
- bannerMat = Material.WHITE_BANNER;
- }
- ItemStack result = new ItemStack(bannerMat, Integer.parseInt(part[1]));
- BannerMeta meta = (BannerMeta) result.getItemMeta();
- if (meta != null) {
- for (int i = 2; i < part.length; i += 2) {
- meta.addPattern(new Pattern(DyeColor.valueOf(part[i + 1]), PatternType.valueOf(part[i])));
- }
- result.setItemMeta(meta);
- }
-
- return result;
- } else {
- return null;
+ /**
+ * This method parses array of multiple elements for the Banner.
+ * @param part String array that contains at least 2 elements.
+ * @return Banner as item stack.
+ */
+ private static ItemStack parseBanner(String[] part) {
+ if (part.length >= 2) {
+ Material bannerMat = Material.getMaterial(part[0]);
+ if (bannerMat == null) {
+ BentoBox.getInstance().logError("Could not parse banner item " + part[0] + " so using a white banner.");
+ bannerMat = Material.WHITE_BANNER;
}
- } catch (Exception e) {
- return null;
+ ItemStack result = new ItemStack(bannerMat, Integer.parseInt(part[1]));
+
+ BannerMeta meta = (BannerMeta) result.getItemMeta();
+ if (meta != null) {
+ for (int i = 2; i < part.length; i += 2) {
+ meta.addPattern(new Pattern(DyeColor.valueOf(part[i + 1]), PatternType.valueOf(part[i])));
+ }
+ result.setItemMeta(meta);
+ }
+
+ return result;
+ } else {
+ throw new MissingFormatArgumentException("Banner parsing requires at least 2 parts.");
+ }
+ }
+
+
+ /**
+ * This method parses array of 2 to 3 elements that represents player head.
+ * Format:
+ * PLAYER_HEAD::QTY
+ * PLAYER_HEAD:
+ * PLAYER_HEAD:QTY
+ * Example:
+ * PLAYER_HEAD:1
+ * PLAYER_HEAD:BONNe1704
+ * PLAYER_HEAD:eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYWY1ZjE1OTg4NmNjNTMxZmZlYTBkOGFhNWY5MmVkNGU1ZGE2NWY3MjRjMDU3MGFmODZhOTBiZjAwYzY3YzQyZSJ9fX0:1
+ * @param part String array that contains at least 2 elements.
+ * @return Player head with given properties.
+ */
+ @SuppressWarnings("deprecation")
+ private static ItemStack parsePlayerHead(String[] part) {
+ ItemStack playerHead;
+
+ if (part.length == 3) {
+ String[] parsable = {part[0], part[2]};
+ // create parse item and quantity.
+ playerHead = parseItemQuantity(parsable);
+ } else if (isNumeric(part[1])) {
+ // there is no meta item for player head.
+ return parseItemQuantity(part);
+ } else {
+ // create new player head item stack.
+ playerHead = new ItemStack(Material.PLAYER_HEAD);
+ }
+
+ // Set correct Skull texture
+ try {
+ SkullMeta meta = (SkullMeta) playerHead.getItemMeta();
+
+ if (part[1].length() < 17) {
+ // Minecraft player names are in length between 3 and 16 chars.
+ meta.setOwner(part[1]);
+ } else if (part[1].length() == 32) {
+ // trimmed UUID length are 32 chars.
+ meta.setOwningPlayer(Bukkit.getOfflinePlayer(
+ UUID.fromString(part[1].replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5"))));
+ } else if (part[1].length() == 36) {
+ // full UUID length are 36 chars.
+ meta.setOwningPlayer(Bukkit.getOfflinePlayer(UUID.fromString(part[1])));
+ } else {
+ // If chars are more than 36, apparently it is base64 encoded texture.
+ GameProfile profile = new GameProfile(UUID.randomUUID(), "");
+ profile.getProperties().put("textures", new Property("textures", part[1]));
+
+ // Null pointer will be caught and ignored.
+ Field profileField = meta.getClass().getDeclaredField("profile");
+ profileField.setAccessible(true);
+ profileField.set(meta, profile);
+ }
+
+ // Apply new meta to the item.
+ playerHead.setItemMeta(meta);
+ } catch (Exception ignored) {}
+
+ return playerHead;
+ }
+
+
+ /**
+ * Check if given sting is an integer.
+ * @param string Value that must be checked.
+ * @return {@code true} if value is integer, {@code false} otherwise.
+ */
+ private static boolean isNumeric(String string) {
+ if(string == null || string.equals("")) {
+ return false;
+ }
+
+ try {
+ Integer.parseInt(string);
+ return true;
+ } catch (NumberFormatException e) {
+ return false;
}
}
}
diff --git a/src/main/java/world/bentobox/bentobox/util/Pair.java b/src/main/java/world/bentobox/bentobox/util/Pair.java
index 775c5f111..d2109480a 100644
--- a/src/main/java/world/bentobox/bentobox/util/Pair.java
+++ b/src/main/java/world/bentobox/bentobox/util/Pair.java
@@ -67,10 +67,9 @@ public class Pair {
if (obj == null) {
return false;
}
- if (!(obj instanceof Pair)) {
+ if (!(obj instanceof Pair, ?> other)) {
return false;
}
- Pair, ?> other = (Pair, ?>) obj;
if (x == null) {
if (other.x != null) {
return false;
diff --git a/src/main/java/world/bentobox/bentobox/util/Util.java b/src/main/java/world/bentobox/bentobox/util/Util.java
index 82eda60b5..953952dcb 100644
--- a/src/main/java/world/bentobox/bentobox/util/Util.java
+++ b/src/main/java/world/bentobox/bentobox/util/Util.java
@@ -11,6 +11,8 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang.Validate;
@@ -55,7 +57,10 @@ import world.bentobox.bentobox.nms.NMSAbstraction;
* @author Poslovitch
*/
public class Util {
-
+ /**
+ * Use standard color code definition: &.
+ */
+ private static final Pattern HEX_PATTERN = Pattern.compile("([a-fA-F0-9]{6}|[a-fA-F0-9]{3})");
private static final String NETHER = "_nether";
private static final String THE_END = "_the_end";
private static String serverVersion = null;
@@ -278,38 +283,23 @@ public class Util {
* @return degrees
*/
public static float blockFaceToFloat(BlockFace face) {
- switch (face) {
- case EAST:
- return 90F;
- case EAST_NORTH_EAST:
- return 67.5F;
- case NORTH_EAST:
- return 45F;
- case NORTH_NORTH_EAST:
- return 22.5F;
- case NORTH_NORTH_WEST:
- return 337.5F;
- case NORTH_WEST:
- return 315F;
- case SOUTH:
- return 180F;
- case SOUTH_EAST:
- return 135F;
- case SOUTH_SOUTH_EAST:
- return 157.5F;
- case SOUTH_SOUTH_WEST:
- return 202.5F;
- case SOUTH_WEST:
- return 225F;
- case WEST:
- return 270F;
- case WEST_NORTH_WEST:
- return 292.5F;
- case WEST_SOUTH_WEST:
- return 247.5F;
- default:
- return 0F;
- }
+ return switch (face) {
+ case EAST -> 90F;
+ case EAST_NORTH_EAST -> 67.5F;
+ case NORTH_EAST -> 45F;
+ case NORTH_NORTH_EAST -> 22.5F;
+ case NORTH_NORTH_WEST -> 337.5F;
+ case NORTH_WEST -> 315F;
+ case SOUTH -> 180F;
+ case SOUTH_EAST -> 135F;
+ case SOUTH_SOUTH_EAST -> 157.5F;
+ case SOUTH_SOUTH_WEST -> 202.5F;
+ case SOUTH_WEST -> 225F;
+ case WEST -> 270F;
+ case WEST_NORTH_WEST -> 292.5F;
+ case WEST_SOUTH_WEST -> 247.5F;
+ default -> 0F;
+ };
}
/**
@@ -538,6 +528,44 @@ public class Util {
return false;
}
+
+ /**
+ * This method translates color codes in given string and strips whitespace after them.
+ * This code parses both: hex and old color codes.
+ * @param textToColor Text which color codes must be parsed.
+ * @return String text with parsed colors and stripped whitespaces after them.
+ */
+ @NonNull
+ public static String translateColorCodes(@NonNull String textToColor) {
+ // Use matcher to find hex patterns in given text.
+ Matcher matcher = HEX_PATTERN.matcher(textToColor);
+ // Increase buffer size by 32 like it is in bungee cord api. Use buffer because it is sync.
+ StringBuilder buffer = new StringBuilder(textToColor.length() + 32);
+
+ while (matcher.find()) {
+ String group = matcher.group(1);
+
+ if (group.length() == 6) {
+ // Parses #ffffff to a color text.
+ matcher.appendReplacement(buffer, ChatColor.COLOR_CHAR + "x"
+ + ChatColor.COLOR_CHAR + group.charAt(0) + ChatColor.COLOR_CHAR + group.charAt(1)
+ + ChatColor.COLOR_CHAR + group.charAt(2) + ChatColor.COLOR_CHAR + group.charAt(3)
+ + ChatColor.COLOR_CHAR + group.charAt(4) + ChatColor.COLOR_CHAR + group.charAt(5));
+ } else {
+ // Parses #fff to a color text.
+ matcher.appendReplacement(buffer, ChatColor.COLOR_CHAR + "x"
+ + ChatColor.COLOR_CHAR + group.charAt(0) + ChatColor.COLOR_CHAR + group.charAt(0)
+ + ChatColor.COLOR_CHAR + group.charAt(1) + ChatColor.COLOR_CHAR + group.charAt(1)
+ + ChatColor.COLOR_CHAR + group.charAt(2) + ChatColor.COLOR_CHAR + group.charAt(2));
+ }
+ }
+
+ // transform normal codes and strip spaces after color code.
+ return Util.stripSpaceAfterColorCodes(
+ ChatColor.translateAlternateColorCodes('&', matcher.appendTail(buffer).toString()));
+ }
+
+
/**
* Strips spaces immediately after color codes. Used by {@link User#getTranslation(String, String...)}.
* @param textToStrip - text to strip
diff --git a/src/main/java/world/bentobox/bentobox/util/heads/HeadGetter.java b/src/main/java/world/bentobox/bentobox/util/heads/HeadGetter.java
index e171b9c79..04012b0e1 100644
--- a/src/main/java/world/bentobox/bentobox/util/heads/HeadGetter.java
+++ b/src/main/java/world/bentobox/bentobox/util/heads/HeadGetter.java
@@ -72,7 +72,7 @@ public class HeadGetter {
HeadCache cache = cachedHeads.get(panelItem.getPlayerHeadName());
- // Get value from config. Multiply value to 60 000 as internally it uses miliseconds.
+ // Get value from config. Multiply value to 60 000 as internally it uses milliseconds.
// Config value stores minutes.
long cacheTimeout = BentoBox.getInstance().getSettings().getPlayerHeadCacheTime() * 60 * 1000;
diff --git a/src/main/java/world/bentobox/bentobox/util/package-info.java b/src/main/java/world/bentobox/bentobox/util/package-info.java
new file mode 100644
index 000000000..3b6d6e5c3
--- /dev/null
+++ b/src/main/java/world/bentobox/bentobox/util/package-info.java
@@ -0,0 +1,12 @@
+/**
+ * API that provides useful (and not so useful) utility functions.
+ *
+ *
+ * Look here before you write your own utility function. If it isn't here, but would be useful
+ * the submit a PR so others can avoid duplicating code!
+ *
+ *
+ * @author various
+ *
+ */
+package world.bentobox.bentobox.util;
\ No newline at end of file
diff --git a/src/main/java/world/bentobox/bentobox/util/teleport/SafeSpotTeleport.java b/src/main/java/world/bentobox/bentobox/util/teleport/SafeSpotTeleport.java
index 7136461e4..9879cb469 100644
--- a/src/main/java/world/bentobox/bentobox/util/teleport/SafeSpotTeleport.java
+++ b/src/main/java/world/bentobox/bentobox/util/teleport/SafeSpotTeleport.java
@@ -300,7 +300,7 @@ public class SafeSpotTeleport {
private String failureMessage = "";
private Location location;
private Runnable runnable;
- private CompletableFuture result = new CompletableFuture<>();
+ private final CompletableFuture result = new CompletableFuture<>();
public Builder(BentoBox plugin) {
this.plugin = plugin;
@@ -380,7 +380,7 @@ public class SafeSpotTeleport {
/**
* Try to teleport the player
- * @return CompletableFuture that will become true if successfull and false if not
+ * @return CompletableFuture that will become true if successful and false if not
* @since 1.14.0
*/
@Nullable
diff --git a/src/main/java/world/bentobox/bentobox/versions/ServerCompatibility.java b/src/main/java/world/bentobox/bentobox/versions/ServerCompatibility.java
index 54b365fab..fb966c959 100644
--- a/src/main/java/world/bentobox/bentobox/versions/ServerCompatibility.java
+++ b/src/main/java/world/bentobox/bentobox/versions/ServerCompatibility.java
@@ -17,7 +17,7 @@ public class ServerCompatibility {
// ---- SINGLETON ----
- private static ServerCompatibility instance = new ServerCompatibility();
+ private static final ServerCompatibility instance = new ServerCompatibility();
public static ServerCompatibility getInstance() {
return instance;
@@ -54,7 +54,7 @@ public class ServerCompatibility {
*/
INCOMPATIBLE(false);
- private boolean canLaunch;
+ private final boolean canLaunch;
Compatibility(boolean canLaunch) {
this.canLaunch = canLaunch;
@@ -85,7 +85,7 @@ public class ServerCompatibility {
*/
UNKNOWN(Compatibility.INCOMPATIBLE);
- private Compatibility compatibility;
+ private final Compatibility compatibility;
/**
* @since 1.14.0
*/
@@ -190,7 +190,7 @@ public class ServerCompatibility {
V1_17_1(Compatibility.COMPATIBLE)
;
- private Compatibility compatibility;
+ private final Compatibility compatibility;
ServerVersion(Compatibility compatibility) {
this.compatibility = compatibility;
@@ -308,9 +308,9 @@ public class ServerCompatibility {
}
/**
- * Returns whether the server runs on the specified softwares.
+ * Returns whether the server runs on the specified software.
* @param softwares the {@link ServerSoftware}s to check.
- * @return {@code true} if the server runs on on of these softwares, {@code false} otherwise.
+ * @return {@code true} if the server runs on on of these software, {@code false} otherwise.
* @since 1.5.0
*/
public boolean isSoftware(@NonNull ServerSoftware... softwares) {
diff --git a/src/main/java/world/bentobox/bentobox/versions/package-info.java b/src/main/java/world/bentobox/bentobox/versions/package-info.java
new file mode 100644
index 000000000..65cd12b0e
--- /dev/null
+++ b/src/main/java/world/bentobox/bentobox/versions/package-info.java
@@ -0,0 +1,11 @@
+/**
+ * Holds a class that decides whether BentoBox is compatible with the server or not.
+ *
+ *
+ * This has to be updated with each new release of the server.
+ *
+ *
+ * @author Poslovich
+ *
+ */
+package world.bentobox.bentobox.versions;
\ No newline at end of file
diff --git a/src/main/java/world/bentobox/bentobox/web/catalog/CatalogEntry.java b/src/main/java/world/bentobox/bentobox/web/catalog/CatalogEntry.java
index fea1bc1cf..2a73ffd6c 100644
--- a/src/main/java/world/bentobox/bentobox/web/catalog/CatalogEntry.java
+++ b/src/main/java/world/bentobox/bentobox/web/catalog/CatalogEntry.java
@@ -13,16 +13,22 @@ import com.google.gson.JsonObject;
*/
public class CatalogEntry {
- private int slot;
+ private final int slot;
/**
* Defaults to {@link Material#PAPER}.
*/
- private @NonNull Material icon;
- private @NonNull String name;
- private @NonNull String description;
- private @Nullable String topic;
- private @Nullable String tag;
- private @NonNull String repository;
+ private @NonNull
+ final Material icon;
+ private @NonNull
+ final String name;
+ private @NonNull
+ final String description;
+ private @Nullable
+ final String topic;
+ private @Nullable
+ final String tag;
+ private @NonNull
+ final String repository;
public CatalogEntry(@NonNull JsonObject object) {
this.slot = object.get("slot").getAsInt();
diff --git a/src/main/java/world/bentobox/bentobox/web/credits/Contributor.java b/src/main/java/world/bentobox/bentobox/web/credits/Contributor.java
index c6d2f28ff..8d0bf328b 100644
--- a/src/main/java/world/bentobox/bentobox/web/credits/Contributor.java
+++ b/src/main/java/world/bentobox/bentobox/web/credits/Contributor.java
@@ -9,8 +9,9 @@ import org.eclipse.jdt.annotation.NonNull;
*/
public class Contributor {
- private @NonNull String name;
- private int commits;
+ private @NonNull
+ final String name;
+ private final int commits;
public Contributor(@NonNull String name, int commits) {
this.name = name;
diff --git a/src/main/java/world/bentobox/bentobox/web/package-info.java b/src/main/java/world/bentobox/bentobox/web/package-info.java
new file mode 100644
index 000000000..ec8c9b812
--- /dev/null
+++ b/src/main/java/world/bentobox/bentobox/web/package-info.java
@@ -0,0 +1,7 @@
+/**
+ * Fetches data from the web, such as the catalog.
+ *
+ * @author Poslovitch
+ *
+ */
+package world.bentobox.bentobox.web;
\ No newline at end of file
diff --git a/src/main/resources/locales/de.yml b/src/main/resources/locales/de.yml
index f35bbb9b4..ce5daf42a 100644
--- a/src/main/resources/locales/de.yml
+++ b/src/main/resources/locales/de.yml
@@ -3,7 +3,7 @@ meta:
authors:
- xXjojojXx
- Poslovitch
- banner: RED_BANNER:1:STRIPE_RIGHT:BLACK:LEFT_STRIPE:YELLOW
+ banner: RED_BANNER:1:STRIPE_RIGHT:BLACK:STRIPE_LEFT:YELLOW
commands:
admin:
setrank:
diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml
index f080ab77f..351640149 100644
--- a/src/main/resources/plugin.yml
+++ b/src/main/resources/plugin.yml
@@ -10,9 +10,10 @@ description: ${project.description}
load: STARTUP
-loadbefore: [Multiverse-Core, Residence]
+loadbefore: [Pladdon, Multiverse-Core, Residence]
softdepend:
+ - Citizens
- Vault
- PlaceholderAPI
- dynmap
diff --git a/src/test/java/world/bentobox/bentobox/api/addons/AddonTest.java b/src/test/java/world/bentobox/bentobox/api/addons/AddonTest.java
index d4e684c5b..6bb9c3e84 100644
--- a/src/test/java/world/bentobox/bentobox/api/addons/AddonTest.java
+++ b/src/test/java/world/bentobox/bentobox/api/addons/AddonTest.java
@@ -301,7 +301,7 @@ public class AddonTest {
* Utility methods
*/
private void createJarArchive(File archiveFile, List tobeJaredList) {
- byte buffer[] = new byte[BUFFER_SIZE];
+ byte[] buffer = new byte[BUFFER_SIZE];
// Open archive file
try (FileOutputStream stream = new FileOutputStream(archiveFile)) {
try (JarOutputStream out = new JarOutputStream(stream, new Manifest())) {
diff --git a/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminInfoCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminInfoCommandTest.java
index 1f5c90a81..4cf7dad10 100644
--- a/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminInfoCommandTest.java
+++ b/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminInfoCommandTest.java
@@ -1,27 +1,35 @@
package world.bentobox.bentobox.api.commands.admin;
+import static org.junit.Assert.assertEquals;
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.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-import java.util.ArrayList;
import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
+import java.util.Collections;
import java.util.Optional;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.Location;
+import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
-import org.bukkit.scheduler.BukkitScheduler;
+import org.bukkit.util.Vector;
+import org.eclipse.jdt.annotation.NonNull;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.Mock;
import org.mockito.Mockito;
+import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@@ -35,7 +43,9 @@ import world.bentobox.bentobox.managers.CommandsManager;
import world.bentobox.bentobox.managers.IslandWorldManager;
import world.bentobox.bentobox.managers.IslandsManager;
import world.bentobox.bentobox.managers.LocalesManager;
+import world.bentobox.bentobox.managers.PlaceholdersManager;
import world.bentobox.bentobox.managers.PlayersManager;
+import world.bentobox.bentobox.managers.RanksManager;
import world.bentobox.bentobox.util.Util;
/**
@@ -43,16 +53,32 @@ import world.bentobox.bentobox.util.Util;
*
*/
@RunWith(PowerMockRunner.class)
-@PrepareForTest({Bukkit.class, BentoBox.class, User.class })
+@PrepareForTest({Bukkit.class, BentoBox.class, Util.class})
public class AdminInfoCommandTest {
- private BentoBox plugin;
- private CompositeCommand ac;
- private UUID uuid;
+ @Mock
+ private CompositeCommand ic;
+ @Mock
private User user;
+ @Mock
private IslandsManager im;
+ @Mock
private PlayersManager pm;
- private UUID notUUID;
+
+ private Island island;
+
+ private AdminInfoCommand iic;
+
+ @Mock
+ private Player player;
+ @Mock
+ private World world;
+ @Mock
+ private PlaceholdersManager phm;
+ @Mock
+ private @NonNull Location location;
+ @Mock
+ private IslandWorldManager iwm;
/**
* @throws java.lang.Exception
@@ -60,69 +86,62 @@ public class AdminInfoCommandTest {
@Before
public void setUp() throws Exception {
// Set up plugin
- plugin = mock(BentoBox.class);
+ BentoBox plugin = mock(BentoBox.class);
Whitebox.setInternalState(BentoBox.class, "instance", plugin);
- Util.setPlugin(plugin);
+ // IWM
+ when(plugin.getIWM()).thenReturn(iwm);
+ when(plugin.getRanksManager()).thenReturn(new RanksManager());
+ // Bukkit
+ PowerMockito.mockStatic(Bukkit.class, Mockito.RETURNS_MOCKS);
// Command manager
CommandsManager cm = mock(CommandsManager.class);
when(plugin.getCommandsManager()).thenReturn(cm);
// Player
- Player p = mock(Player.class);
- // Sometimes use Mockito.withSettings().verboseLogging()
- user = mock(User.class);
- when(user.isOp()).thenReturn(false);
- uuid = UUID.randomUUID();
- notUUID = UUID.randomUUID();
- while(notUUID.equals(uuid)) {
- notUUID = UUID.randomUUID();
- }
+ when(player.isOp()).thenReturn(false);
+ UUID uuid = UUID.randomUUID();
when(user.getUniqueId()).thenReturn(uuid);
- when(user.getPlayer()).thenReturn(p);
when(user.getName()).thenReturn("tastybento");
+ when(user.getWorld()).thenReturn(world);
+ when(user.getPlayer()).thenReturn(player);
+ when(user.isPlayer()).thenReturn(true);
+ //user = User.getInstance(player);
+ // Set the User class plugin as this one
User.setPlugin(plugin);
- // Parent command has no aliases
- ac = mock(CompositeCommand.class);
- when(ac.getSubCommandAliases()).thenReturn(new HashMap<>());
-
- // Island World Manager
- IslandWorldManager iwm = mock(IslandWorldManager.class);
- when(iwm.getFriendlyName(Mockito.any())).thenReturn("BSkyBlock");
- when(plugin.getIWM()).thenReturn(iwm);
-
-
- // Player has island to begin with
- im = mock(IslandsManager.class);
- when(im.hasIsland(Mockito.any(), Mockito.any(UUID.class))).thenReturn(true);
- when(im.hasIsland(Mockito.any(), Mockito.any(User.class))).thenReturn(true);
- when(im.isOwner(Mockito.any(),Mockito.any())).thenReturn(true);
- when(im.getOwner(Mockito.any(),Mockito.any())).thenReturn(uuid);
- when(plugin.getIslands()).thenReturn(im);
-
- // Has team
- pm = mock(PlayersManager.class);
- when(im.inTeam(Mockito.any(), Mockito.eq(uuid))).thenReturn(true);
-
- when(plugin.getPlayers()).thenReturn(pm);
-
- // Server & Scheduler
- BukkitScheduler sch = mock(BukkitScheduler.class);
- PowerMockito.mockStatic(Bukkit.class);
- when(Bukkit.getScheduler()).thenReturn(sch);
-
// Locales
LocalesManager lm = mock(LocalesManager.class);
- when(lm.get(Mockito.any(), Mockito.any())).thenReturn("mock translation");
+ when(lm.get(any(), any())).thenAnswer((Answer) invocation -> invocation.getArgument(1, String.class));
when(plugin.getLocalesManager()).thenReturn(lm);
+ // Return the same string
+ when(phm.replacePlaceholders(any(), anyString())).thenAnswer((Answer) invocation -> invocation.getArgument(1, String.class));
+ when(plugin.getPlaceholdersManager()).thenReturn(phm);
+ // Translate
+ when(user.getTranslation(anyString())).thenAnswer((Answer) invocation -> invocation.getArgument(0, String.class));
+ when(user.getTranslation(anyString(), anyString(), anyString())).thenAnswer((Answer) invocation -> invocation.getArgument(0, String.class));
- // Addon
- when(iwm.getAddon(Mockito.any())).thenReturn(Optional.empty());
+ // Island manager
+ island = new Island(location, uuid, 100);
+ when(location.toVector()).thenReturn(new Vector(1,2,3));
+ when(plugin.getIslands()).thenReturn(im);
+ Optional optionalIsland = Optional.of(island);
+ when(im.getIslandAt(any())).thenReturn(optionalIsland);
+ when(im.getIsland(any(), any(UUID.class))).thenReturn(island);
+ // Players manager
+ when(plugin.getPlayers()).thenReturn(pm);
+ when(pm.getUUID(any())).thenReturn(uuid);
+
+
+ // Command
+ iic = new AdminInfoCommand(ic);
}
+ /**
+ * @throws java.lang.Exception
+ */
@After
public void tearDown() {
User.clearUsers();
@@ -130,93 +149,111 @@ public class AdminInfoCommandTest {
}
/**
- * Test method for {@link AdminInfoCommand#execute(User, String, List)}.
+ * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#setup()}.
*/
@Test
- public void testExecuteNoTargetConsole() {
- AdminInfoCommand itl = new AdminInfoCommand(ac);
- CommandSender sender = mock(CommandSender.class);
- User console = User.getInstance(sender);
- assertFalse(itl.execute(console, itl.getLabel(), new ArrayList<>()));
- // Show help
+ public void testSetup() {
+ assertEquals("mod.info", iic.getPermission());
+ assertFalse(iic.isOnlyPlayer());
+ assertEquals("commands.admin.info.parameters", iic.getParameters());
+ assertEquals("commands.admin.info.description", iic.getDescription());
}
/**
- * Test method for {@link world.bentobox.bentobox.api.commands.admin.AdminInfoCommand#execute(User, String, List)} .
+ * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}.
*/
@Test
- public void testExecuteUnknownPlayer() {
- AdminInfoCommand itl = new AdminInfoCommand(ac);
- String[] name = {"tastybento"};
- when(pm.getUUID(Mockito.any())).thenReturn(null);
- assertFalse(itl.execute(user, itl.getLabel(), Arrays.asList(name)));
- Mockito.verify(user).sendMessage("general.errors.unknown-player", "[name]", name[0]);
+ public void testExecuteUserStringListOfStringTooManyArgs() {
+ assertFalse(iic.execute(user, "", Arrays.asList("hdhh", "hdhdhd")));
+ verify(user).sendMessage("commands.help.header", "[label]", "commands.help.console");
}
/**
- * Test method for .
+ * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}.
*/
@Test
- public void testExecutePlayerHasNoIsland() {
- AdminInfoCommand itl = new AdminInfoCommand(ac);
- String[] name = {"tastybento"};
- when(pm.getUUID(Mockito.any())).thenReturn(notUUID);
- when(im.hasIsland(Mockito.any(), Mockito.any(UUID.class))).thenReturn(false);
- when(im.inTeam(Mockito.any(), Mockito.any())).thenReturn(false);
- when(im.getIsland(Mockito.any(), Mockito.any(UUID.class))).thenReturn(null);
- assertFalse(itl.execute(user, itl.getLabel(), Arrays.asList(name)));
- Mockito.verify(user).sendMessage(Mockito.eq("general.errors.player-has-no-island"));
+ public void testExecuteUserStringListOfStringNoArgsConsole() {
+ CommandSender console = mock(CommandSender.class);
+ User sender = User.getInstance(console);
+ assertFalse(iic.execute(sender, "", Collections.emptyList()));
+ verify(user, never()).sendMessage("commands.help.header", "[label]", "commands.help.console");
}
/**
- * Test method for {@link world.bentobox.bentobox.api.commands.admin.AdminInfoCommand#execute(User, String, List)}.
+ * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}.
*/
@Test
- public void testExecuteSuccess() {
- AdminInfoCommand itl = new AdminInfoCommand(ac);
- String[] name = {"tastybento"};
- when(pm.getUUID(Mockito.any())).thenReturn(notUUID);
- when(im.hasIsland(Mockito.any(), Mockito.any(UUID.class))).thenReturn(true);
- Island is = mock(Island.class);
- when(im.getIsland(Mockito.any(), Mockito.eq(notUUID))).thenReturn(is);
- assertTrue(itl.execute(user, itl.getLabel(), Arrays.asList(name)));
- Mockito.verify(is).showInfo(Mockito.eq(user));
+ public void testExecuteUserStringListOfStringNoArgsNoIsland() {
+ when(im.getIslandAt(any())).thenReturn(Optional.empty());
+ assertTrue(iic.execute(user, "", Collections.emptyList()));
+ verify(user).sendMessage("commands.admin.info.no-island");
}
/**
- * Test method for {@link world.bentobox.bentobox.api.commands.admin.AdminInfoCommand#execute(User, String, List)}.
+ * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}.
*/
@Test
- public void testExecuteUserNotOnIsland() {
- when(user.isPlayer()).thenReturn(true);
- AdminInfoCommand itl = new AdminInfoCommand(ac);
- // No island here
- when(im.getIslandAt(Mockito.any())).thenReturn(Optional.empty());
- assertFalse(itl.execute(user, itl.getLabel(), new ArrayList<>()));
- // Confirm other verifications
- Mockito.verify(user).sendMessage("commands.admin.info.no-island");
+ public void testExecuteUserStringListOfStringNoArgsSuccess() {
+ assertTrue(iic.execute(user, "", Collections.emptyList()));
+ verify(user).sendMessage("commands.admin.info.title");
+ verify(user).sendMessage(eq("commands.admin.info.island-uuid"), eq("[uuid]"), any());
+ verify(user).sendMessage(eq("commands.admin.info.owner"), eq("[owner]"), eq(null), eq("[uuid]"), any());
+ verify(user).sendMessage(eq("commands.admin.info.last-login"), eq("[date]"), any());
+ verify(user).sendMessage("commands.admin.info.deaths", "[number]", "0");
+ verify(user).sendMessage("commands.admin.info.resets-left", "[number]", "0", "[total]", "0");
+ verify(user).sendMessage("commands.admin.info.team-members-title");
+ verify(user).sendMessage("commands.admin.info.team-owner-format", "[name]", null, "[rank]", "ranks.owner");
+ verify(user).sendMessage("commands.admin.info.island-protection-center", "[xyz]", "0,0,0");
+ verify(user).sendMessage("commands.admin.info.island-center", "[xyz]", "0,0,0");
+ verify(user).sendMessage("commands.admin.info.island-coords", "[xz1]", "0,0,0", "[xz2]", "0,0,0");
+ verify(user).sendMessage("commands.admin.info.protection-range", "[range]", "100");
+ verify(user).sendMessage("commands.admin.info.max-protection-range", "[range]", "100");
+ verify(user).sendMessage("commands.admin.info.protection-coords", "[xz1]", "0,0,0", "[xz2]", "0,0,0");
}
/**
- * Test method for {@link world.bentobox.bentobox.api.commands.admin.AdminInfoCommand#execute(User, String, List)}.
+ * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}.
*/
@Test
- public void testExecuteSuccessUserOnIsland() {
- when(user.isPlayer()).thenReturn(true);
- AdminInfoCommand itl = new AdminInfoCommand(ac);
- Location loc = mock(Location.class);
+ public void testExecuteUserStringListOfStringArgsSuccess() {
+ assertTrue(iic.execute(user, "", Collections.singletonList("tastybento")));
+ verify(user).sendMessage("commands.admin.info.title");
+ verify(user).sendMessage(eq("commands.admin.info.island-uuid"), eq("[uuid]"), any());
+ verify(user).sendMessage(eq("commands.admin.info.owner"), eq("[owner]"), eq(null), eq("[uuid]"), any());
+ verify(user).sendMessage(eq("commands.admin.info.last-login"), eq("[date]"), any());
+ verify(user).sendMessage("commands.admin.info.deaths", "[number]", "0");
+ verify(user).sendMessage("commands.admin.info.resets-left", "[number]", "0", "[total]", "0");
+ verify(user).sendMessage("commands.admin.info.team-members-title");
+ verify(user).sendMessage("commands.admin.info.team-owner-format", "[name]", null, "[rank]", "ranks.owner");
+ verify(user).sendMessage("commands.admin.info.island-protection-center", "[xyz]", "0,0,0");
+ verify(user).sendMessage("commands.admin.info.island-center", "[xyz]", "0,0,0");
+ verify(user).sendMessage("commands.admin.info.island-coords", "[xz1]", "0,0,0", "[xz2]", "0,0,0");
+ verify(user).sendMessage("commands.admin.info.protection-range", "[range]", "100");
+ verify(user).sendMessage("commands.admin.info.max-protection-range", "[range]", "100");
+ verify(user).sendMessage("commands.admin.info.protection-coords", "[xz1]", "0,0,0", "[xz2]", "0,0,0");
- // Island has owner
- Island is = mock(Island.class);
- when(is.getOwner()).thenReturn(uuid);
- when(is.showInfo(Mockito.any())).thenReturn(true);
- Optional opi = Optional.of(is);
- when(im.getIslandAt(Mockito.any())).thenReturn(opi);
- when(user.getLocation()).thenReturn(loc);
-
-
- assertTrue(itl.execute(user, itl.getLabel(), new ArrayList<>()));
- // Confirm other verifications
- Mockito.verify(is).showInfo(Mockito.eq(user));
}
-}
\ No newline at end of file
+
+ /**
+ * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}.
+ */
+ @Test
+ public void testExecuteUserStringListOfStringArgsNoIsland() {
+ when(im.getIsland(any(), any(UUID.class))).thenReturn(null);
+ assertFalse(iic.execute(user, "", Collections.singletonList("tastybento")));
+ verify(user).sendMessage("general.errors.player-has-no-island");
+ }
+
+ /**
+ * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}.
+ */
+ @Test
+ public void testExecuteUserStringListOfStringArgsUnknownPlayer() {
+ PowerMockito.mockStatic(Util.class);
+ when(Util.getUUID(any())).thenReturn(null);
+ assertFalse(iic.execute(user, "", Collections.singletonList("tastybento")));
+ verify(user).sendMessage("general.errors.unknown-player", "[name]", "tastybento");
+
+ }
+
+}
diff --git a/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminResetFlagsCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminResetFlagsCommandTest.java
index 22d7b7178..4f5e64f4f 100644
--- a/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminResetFlagsCommandTest.java
+++ b/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminResetFlagsCommandTest.java
@@ -58,7 +58,7 @@ public class AdminResetFlagsCommandTest {
@Mock
private CompositeCommand ac;
- private UUID uuid = UUID.randomUUID();
+ private final UUID uuid = UUID.randomUUID();
@Mock
private IslandsManager im;
@Mock
diff --git a/src/test/java/world/bentobox/bentobox/api/commands/admin/team/AdminTeamAddCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/admin/team/AdminTeamAddCommandTest.java
index 15f13eddd..c44e696ab 100644
--- a/src/test/java/world/bentobox/bentobox/api/commands/admin/team/AdminTeamAddCommandTest.java
+++ b/src/test/java/world/bentobox/bentobox/api/commands/admin/team/AdminTeamAddCommandTest.java
@@ -2,7 +2,10 @@ package world.bentobox.bentobox.api.commands.admin.team;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
@@ -90,15 +93,15 @@ public class AdminTeamAddCommandTest {
// Player has island to begin with
im = mock(IslandsManager.class);
- when(im.hasIsland(Mockito.any(), Mockito.any(User.class))).thenReturn(true);
- when(im.hasIsland(Mockito.any(), Mockito.any(UUID.class))).thenReturn(true);
- when(im.isOwner(Mockito.any(), Mockito.any())).thenReturn(true);
- when(im.getOwner(Mockito.any(), Mockito.any())).thenReturn(uuid);
+ when(im.hasIsland(any(), any(User.class))).thenReturn(true);
+ when(im.hasIsland(any(), any(UUID.class))).thenReturn(true);
+ when(im.isOwner(any(), any())).thenReturn(true);
+ when(im.getOwner(any(), any())).thenReturn(uuid);
when(plugin.getIslands()).thenReturn(im);
// Has team
pm = mock(PlayersManager.class);
- when(im.inTeam(Mockito.any(), Mockito.eq(uuid))).thenReturn(true);
+ when(im.inTeam(any(), eq(uuid))).thenReturn(true);
when(plugin.getPlayers()).thenReturn(pm);
@@ -112,16 +115,16 @@ public class AdminTeamAddCommandTest {
// Locales
LocalesManager lm = mock(LocalesManager.class);
- when(lm.get(Mockito.any(), Mockito.any())).thenReturn("mock translation");
+ when(lm.get(any(), any())).thenReturn("mock translation");
when(plugin.getLocalesManager()).thenReturn(lm);
// Island World Manager
IslandWorldManager iwm = mock(IslandWorldManager.class);
- when(iwm.getFriendlyName(Mockito.any())).thenReturn("BSkyBlock");
+ when(iwm.getFriendlyName(any())).thenReturn("BSkyBlock");
when(plugin.getIWM()).thenReturn(iwm);
// Addon
- when(iwm.getAddon(Mockito.any())).thenReturn(Optional.empty());
+ when(iwm.getAddon(any())).thenReturn(Optional.empty());
}
@@ -158,16 +161,16 @@ public class AdminTeamAddCommandTest {
String[] name = {"tastybento", "poslovich"};
// Unknown owner
- when(pm.getUUID(Mockito.eq("tastybento"))).thenReturn(null);
- when(pm.getUUID(Mockito.eq("poslovich"))).thenReturn(notUUID);
+ when(pm.getUUID(eq("tastybento"))).thenReturn(null);
+ when(pm.getUUID(eq("poslovich"))).thenReturn(notUUID);
assertFalse(itl.execute(user, ac.getLabel(), Arrays.asList(name)));
- Mockito.verify(user).sendMessage("general.errors.unknown-player", "[name]", "tastybento");
+ verify(user).sendMessage("general.errors.unknown-player", "[name]", "tastybento");
// Unknown target
- when(pm.getUUID(Mockito.eq("tastybento"))).thenReturn(uuid);
- when(pm.getUUID(Mockito.eq("poslovich"))).thenReturn(null);
+ when(pm.getUUID(eq("tastybento"))).thenReturn(uuid);
+ when(pm.getUUID(eq("poslovich"))).thenReturn(null);
assertFalse(itl.execute(user, ac.getLabel(), Arrays.asList(name)));
- Mockito.verify(user).sendMessage("general.errors.unknown-player", "[name]", "poslovich");
+ verify(user).sendMessage("general.errors.unknown-player", "[name]", "poslovich");
}
/**
@@ -178,13 +181,13 @@ public class AdminTeamAddCommandTest {
AdminTeamAddCommand itl = new AdminTeamAddCommand(ac);
String[] name = {"tastybento", "poslovich"};
- when(pm.getUUID(Mockito.eq("tastybento"))).thenReturn(uuid);
- when(pm.getUUID(Mockito.eq("poslovich"))).thenReturn(notUUID);
+ when(pm.getUUID(eq("tastybento"))).thenReturn(uuid);
+ when(pm.getUUID(eq("poslovich"))).thenReturn(notUUID);
- when(im.inTeam(Mockito.any(), Mockito.eq(notUUID))).thenReturn(true);
+ when(im.inTeam(any(), eq(notUUID))).thenReturn(true);
assertFalse(itl.execute(user, itl.getLabel(), Arrays.asList(name)));
- Mockito.verify(user).sendMessage(Mockito.eq("commands.island.team.invite.errors.already-on-team"));
+ verify(user).sendMessage(eq("commands.island.team.invite.errors.already-on-team"));
}
@@ -196,14 +199,14 @@ public class AdminTeamAddCommandTest {
AdminTeamAddCommand itl = new AdminTeamAddCommand(ac);
String[] name = {"tastybento", "poslovich"};
- when(pm.getUUID(Mockito.eq("tastybento"))).thenReturn(uuid);
- when(pm.getUUID(Mockito.eq("poslovich"))).thenReturn(notUUID);
+ when(pm.getUUID(eq("tastybento"))).thenReturn(uuid);
+ when(pm.getUUID(eq("poslovich"))).thenReturn(notUUID);
// No island,
- when(im.hasIsland(Mockito.any(), Mockito.eq(uuid))).thenReturn(false);
+ when(im.hasIsland(any(), eq(uuid))).thenReturn(false);
assertFalse(itl.execute(user, itl.getLabel(), Arrays.asList(name)));
- Mockito.verify(user).sendMessage("general.errors.player-has-no-island");
+ verify(user).sendMessage("general.errors.player-has-no-island");
}
@@ -215,21 +218,21 @@ public class AdminTeamAddCommandTest {
AdminTeamAddCommand itl = new AdminTeamAddCommand(ac);
String[] name = {"tastybento", "poslovich"};
- when(pm.getUUID(Mockito.eq("tastybento"))).thenReturn(uuid);
- when(pm.getUUID(Mockito.eq("poslovich"))).thenReturn(notUUID);
+ when(pm.getUUID(eq("tastybento"))).thenReturn(uuid);
+ when(pm.getUUID(eq("poslovich"))).thenReturn(notUUID);
// Has island, has team, but not an owner
- when(im.hasIsland(Mockito.any(),Mockito.eq(uuid))).thenReturn(true);
- when(im.inTeam(Mockito.any(),Mockito.eq(uuid))).thenReturn(true);
- when(im.getOwner(Mockito.any(),Mockito.eq(uuid))).thenReturn(notUUID);
+ when(im.hasIsland(any(),eq(uuid))).thenReturn(true);
+ when(im.inTeam(any(),eq(uuid))).thenReturn(true);
+ when(im.getOwner(any(),eq(uuid))).thenReturn(notUUID);
// Island
Island island = mock(Island.class);
- when(im.getIsland(Mockito.any(), Mockito.eq(uuid))).thenReturn(island);
+ when(im.getIsland(any(), eq(uuid))).thenReturn(island);
assertFalse(itl.execute(user, itl.getLabel(), Arrays.asList(name)));
- Mockito.verify(user).sendMessage("commands.admin.team.add.name-not-owner", "[name]", "tastybento");
- Mockito.verify(island).showMembers(Mockito.any());
+ verify(user).sendMessage("commands.admin.team.add.name-not-owner", "[name]", "tastybento");
+ verify(user).sendMessage("commands.admin.info.team-members-title");
}
/**
@@ -240,19 +243,19 @@ public class AdminTeamAddCommandTest {
AdminTeamAddCommand itl = new AdminTeamAddCommand(ac);
String[] name = {"tastybento", "poslovich"};
- when(pm.getUUID(Mockito.eq("tastybento"))).thenReturn(uuid);
- when(pm.getUUID(Mockito.eq("poslovich"))).thenReturn(notUUID);
+ when(pm.getUUID(eq("tastybento"))).thenReturn(uuid);
+ when(pm.getUUID(eq("poslovich"))).thenReturn(notUUID);
// Has island, has team, is owner
- when(im.hasIsland(Mockito.any(),Mockito.eq(uuid))).thenReturn(true);
- when(im.inTeam(Mockito.any(),Mockito.eq(uuid))).thenReturn(true);
- when(im.getOwner(Mockito.any(), Mockito.eq(uuid))).thenReturn(uuid);
+ when(im.hasIsland(any(),eq(uuid))).thenReturn(true);
+ when(im.inTeam(any(),eq(uuid))).thenReturn(true);
+ when(im.getOwner(any(), eq(uuid))).thenReturn(uuid);
// Target has island
- when(im.hasIsland(Mockito.any(), Mockito.eq(notUUID))).thenReturn(true);
+ when(im.hasIsland(any(), eq(notUUID))).thenReturn(true);
assertFalse(itl.execute(user, itl.getLabel(), Arrays.asList(name)));
- Mockito.verify(user).sendMessage("commands.admin.team.add.name-has-island", "[name]", "poslovich");
+ verify(user).sendMessage("commands.admin.team.add.name-has-island", "[name]", "poslovich");
}
@@ -264,18 +267,18 @@ public class AdminTeamAddCommandTest {
AdminTeamAddCommand itl = new AdminTeamAddCommand(ac);
String[] name = {"tastybento", "poslovich"};
- when(pm.getUUID(Mockito.eq("tastybento"))).thenReturn(uuid);
- when(pm.getUUID(Mockito.eq("poslovich"))).thenReturn(notUUID);
+ when(pm.getUUID(eq("tastybento"))).thenReturn(uuid);
+ when(pm.getUUID(eq("poslovich"))).thenReturn(notUUID);
// Has island, no team
- when(im.hasIsland(Mockito.any(), Mockito.eq(uuid))).thenReturn(true);
- when(im.inTeam(Mockito.any(), Mockito.eq(uuid))).thenReturn(false);
+ when(im.hasIsland(any(), eq(uuid))).thenReturn(true);
+ when(im.inTeam(any(), eq(uuid))).thenReturn(false);
// Target has island
- when(im.hasIsland(Mockito.any(), Mockito.eq(notUUID))).thenReturn(true);
+ when(im.hasIsland(any(), eq(notUUID))).thenReturn(true);
assertFalse(itl.execute(user, itl.getLabel(), Arrays.asList(name)));
- Mockito.verify(user).sendMessage("commands.admin.team.add.name-has-island", "[name]", "poslovich");
+ verify(user).sendMessage("commands.admin.team.add.name-has-island", "[name]", "poslovich");
}
@@ -287,29 +290,29 @@ public class AdminTeamAddCommandTest {
AdminTeamAddCommand itl = new AdminTeamAddCommand(ac);
String[] name = {"tastybento", "poslovich"};
- when(pm.getUUID(Mockito.eq("tastybento"))).thenReturn(uuid);
- when(pm.getUUID(Mockito.eq("poslovich"))).thenReturn(notUUID);
+ when(pm.getUUID(eq("tastybento"))).thenReturn(uuid);
+ when(pm.getUUID(eq("poslovich"))).thenReturn(notUUID);
// Has island, no team
- when(im.hasIsland(Mockito.any(), Mockito.eq(uuid))).thenReturn(true);
- when(im.inTeam(Mockito.any(), Mockito.eq(uuid))).thenReturn(false);
+ when(im.hasIsland(any(), eq(uuid))).thenReturn(true);
+ when(im.inTeam(any(), eq(uuid))).thenReturn(false);
// Target has no island
- when(im.hasIsland(Mockito.any(), Mockito.eq(notUUID))).thenReturn(false);
+ when(im.hasIsland(any(), eq(notUUID))).thenReturn(false);
// Island
Island island = mock(Island.class);
- when(im.getIsland(Mockito.any(), Mockito.eq(uuid))).thenReturn(island);
+ when(im.getIsland(any(), eq(uuid))).thenReturn(island);
// Player name
- when(pm.getName(Mockito.eq(uuid))).thenReturn("tastybento");
- when(pm.getName(Mockito.eq(notUUID))).thenReturn("poslovich");
+ when(pm.getName(eq(uuid))).thenReturn("tastybento");
+ when(pm.getName(eq(notUUID))).thenReturn("poslovich");
when(plugin.getPlayers()).thenReturn(pm);
// Success
assertTrue(itl.execute(user, itl.getLabel(), Arrays.asList(name)));
- Mockito.verify(im).setJoinTeam(Mockito.eq(island), Mockito.eq(notUUID));
- Mockito.verify(user).sendMessage("commands.admin.team.add.success", TextVariables.NAME, name[1], "[owner]", name[0]);
+ verify(im).setJoinTeam(eq(island), eq(notUUID));
+ verify(user).sendMessage("commands.admin.team.add.success", TextVariables.NAME, name[1], "[owner]", name[0]);
}
}
diff --git a/src/test/java/world/bentobox/bentobox/api/commands/admin/team/AdminTeamKickCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/admin/team/AdminTeamKickCommandTest.java
index 6161b07a4..aed70d1c0 100644
--- a/src/test/java/world/bentobox/bentobox/api/commands/admin/team/AdminTeamKickCommandTest.java
+++ b/src/test/java/world/bentobox/bentobox/api/commands/admin/team/AdminTeamKickCommandTest.java
@@ -190,7 +190,7 @@ public class AdminTeamKickCommandTest {
assertTrue(itl.canExecute(user, itl.getLabel(), Collections.singletonList("tastybento")));
assertFalse(itl.execute(user, itl.getLabel(), Collections.singletonList("tastybento")));
verify(user).sendMessage(eq("commands.admin.team.kick.cannot-kick-owner"));
- verify(is).showMembers(any());
+ verify(user).sendMessage("commands.admin.info.team-members-title");
verify(im, never()).removePlayer(eq(world), eq(notUUID));
verify(pm, never()).clearHomeLocations(eq(world), eq(notUUID));
verify(user, never()).sendMessage(eq("commands.admin.team.kick.success"), anyString(), anyString(), anyString(), anyString());
diff --git a/src/test/java/world/bentobox/bentobox/api/commands/island/IslandGoCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/island/IslandGoCommandTest.java
index ce858a90c..a9a2c752f 100644
--- a/src/test/java/world/bentobox/bentobox/api/commands/island/IslandGoCommandTest.java
+++ b/src/test/java/world/bentobox/bentobox/api/commands/island/IslandGoCommandTest.java
@@ -162,7 +162,7 @@ public class IslandGoCommandTest {
// Locales
LocalesManager lm = mock(LocalesManager.class);
- when(lm.get(Mockito.any(), Mockito.any())).thenAnswer((Answer) invocation -> invocation.getArgument(1, String.class));
+ when(lm.get(any(), any())).thenAnswer((Answer) invocation -> invocation.getArgument(1, String.class));
when(plugin.getLocalesManager()).thenReturn(lm);
// Return the same string
PlaceholdersManager phm = mock(PlaceholdersManager.class);
@@ -172,8 +172,8 @@ public class IslandGoCommandTest {
// Notifier
when(plugin.getNotifier()).thenReturn(notifier);
- // Util strip spaces
- when(Util.stripSpaceAfterColorCodes(anyString())).thenCallRealMethod();
+ // Util translate color codes (used in user translate methods)
+ when(Util.translateColorCodes(anyString())).thenAnswer((Answer