Merge pull request #181 from BentoBoxWorld/develop

Release 1.20.1
This commit is contained in:
tastybento 2024-01-19 13:58:59 -08:00 committed by GitHub
commit 0dbd451c33
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 750 additions and 682 deletions

View File

@ -11,21 +11,22 @@ jobs:
name: Build name: Build
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v3
with: with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- name: Set up JDK 17 - name: Set up JDK 17
uses: actions/setup-java@v1 uses: actions/setup-java@v3
with: with:
distribution: 'adopt'
java-version: 17 java-version: 17
- name: Cache SonarCloud packages - name: Cache SonarCloud packages
uses: actions/cache@v1 uses: actions/cache@v3
with: with:
path: ~/.sonar/cache path: ~/.sonar/cache
key: ${{ runner.os }}-sonar key: ${{ runner.os }}-sonar
restore-keys: ${{ runner.os }}-sonar restore-keys: ${{ runner.os }}-sonar
- name: Cache Maven packages - name: Cache Maven packages
uses: actions/cache@v1 uses: actions/cache@v3
with: with:
path: ~/.m2 path: ~/.m2
key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}

10
pom.xml
View File

@ -57,14 +57,14 @@
<!-- Non-minecraft related dependencies --> <!-- Non-minecraft related dependencies -->
<powermock.version>2.0.9</powermock.version> <powermock.version>2.0.9</powermock.version>
<!-- More visible way how to change dependency versions --> <!-- More visible way how to change dependency versions -->
<spigot.version>1.19.4-R0.1-SNAPSHOT</spigot.version> <spigot.version>1.20.4-R0.1-SNAPSHOT</spigot.version>
<bentobox.version>1.23.0</bentobox.version> <bentobox.version>2.0.0-SNAPSHOT</bentobox.version>
<!-- Revision variable removes warning about dynamic version --> <!-- Revision variable removes warning about dynamic version -->
<revision>${build.version}-SNAPSHOT</revision> <revision>${build.version}-SNAPSHOT</revision>
<!-- Do not change unless you want different name for local builds. --> <!-- Do not change unless you want different name for local builds. -->
<build.number>-LOCAL</build.number> <build.number>-LOCAL</build.number>
<!-- This allows to change between versions. --> <!-- This allows to change between versions. -->
<build.version>1.19.1</build.version> <build.version>1.20.1</build.version>
<sonar.projectKey>BentoBoxWorld_Limits</sonar.projectKey> <sonar.projectKey>BentoBoxWorld_Limits</sonar.projectKey>
<sonar.organization>bentobox-world</sonar.organization> <sonar.organization>bentobox-world</sonar.organization>
<sonar.host.url>https://sonarcloud.io</sonar.host.url> <sonar.host.url>https://sonarcloud.io</sonar.host.url>
@ -251,13 +251,15 @@
<plugin> <plugin>
<groupId>org.jacoco</groupId> <groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId> <artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.7</version> <version>0.8.10</version>
<configuration> <configuration>
<append>true</append> <append>true</append>
<excludes> <excludes>
<!-- This is required to prevent Jacoco from adding <!-- This is required to prevent Jacoco from adding
synthetic fields to a JavaBean class (causes errors in testing) --> synthetic fields to a JavaBean class (causes errors in testing) -->
<exclude>**/*Names*</exclude> <exclude>**/*Names*</exclude>
<!-- Prevents the Material is too large to mock error -->
<exclude>org/bukkit/Material*</exclude>
</excludes> </excludes>
</configuration> </configuration>
<executions> <executions>

View File

@ -180,7 +180,7 @@ public class EntityLimitListener implements Listener {
if (island.isSpawn() || !res.hit()) { if (island.isSpawn() || !res.hit()) {
// Allowed // Allowed
if (async) { if (async) {
Bukkit.getScheduler().runTask(BentoBox.getInstance(), () -> l.getWorld().spawn(l, e.getClass(), entity -> preSpawn(entity, reason, l))); Bukkit.getScheduler().runTask(BentoBox.getInstance(), () -> preSpawn(e.getType(), reason, l));
} // else do nothing } // else do nothing
} else { } else {
if (async) { if (async) {
@ -195,21 +195,23 @@ public class EntityLimitListener implements Listener {
return true; return true;
} }
private void preSpawn(Entity entity, SpawnReason reason, Location l) { private void preSpawn(EntityType entityType, SpawnReason reason, Location l) {
justSpawned.add(entity.getUniqueId());
// Check for entities that need cleanup // Check for entities that need cleanup
switch (reason) { switch (reason) {
case BUILD_IRONGOLEM -> detectIronGolem(l); case BUILD_IRONGOLEM -> detectIronGolem(l);
case BUILD_SNOWMAN -> detectSnowman(l); case BUILD_SNOWMAN -> detectSnowman(l);
case BUILD_WITHER -> { case BUILD_WITHER -> {
detectWither(l); detectWither(l);
}
default -> throw new IllegalArgumentException("Unexpected value: " + reason);
}
Entity entity = l.getWorld().spawnEntity(l, entityType);
justSpawned.add(entity.getUniqueId());
if (reason == SpawnReason.BUILD_WITHER) {
// Create explosion // Create explosion
l.getWorld().createExplosion(l, 7F, true, true, entity); l.getWorld().createExplosion(l, 7F, true, true, entity);
} }
default -> {
// Do nothing
}
}
} }
private void detectIronGolem(Location l) { private void detectIronGolem(Location l) {
@ -246,7 +248,6 @@ public class EntityLimitListener implements Listener {
} }
} }
} }
} }
private void detectSnowman(Location l) { private void detectSnowman(Location l) {

View File

@ -30,6 +30,7 @@ import world.bentobox.limits.objects.IslandBlockCount;
/** /**
* Sets block limits based on player permission * Sets block limits based on player permission
*
* @author tastybento * @author tastybento
* *
*/ */
@ -42,7 +43,9 @@ public class JoinListener implements Listener {
} }
/** /**
* Check and set the permissions of the player and how they affect the island limits * Check and set the permissions of the player and how they affect the island
* limits
*
* @param player - player * @param player - player
* @param permissionPrefix - permission prefix for this game mode * @param permissionPrefix - permission prefix for this game mode
* @param islandId - island string id * @param islandId - island string id
@ -58,21 +61,23 @@ public class JoinListener implements Listener {
ibc.getBlockLimits().clear(); ibc.getBlockLimits().clear();
} }
for (PermissionAttachmentInfo perms : player.getEffectivePermissions()) { for (PermissionAttachmentInfo perms : player.getEffectivePermissions()) {
if (!perms.getValue() if (!perms.getValue() || !perms.getPermission().startsWith(permissionPrefix)
|| !perms.getPermission().startsWith(permissionPrefix)
|| badSyntaxCheck(perms, player.getName(), permissionPrefix)) { || badSyntaxCheck(perms, player.getName(), permissionPrefix)) {
continue; continue;
} }
// Check formatting // Check formatting
String[] split = perms.getPermission().split("\\."); String[] split = perms.getPermission().split("\\.");
// Entities & materials // Entities & materials
EntityType et = Arrays.stream(EntityType.values()).filter(t -> t.name().equalsIgnoreCase(split[3])).findFirst().orElse(null); EntityType et = Arrays.stream(EntityType.values()).filter(t -> t.name().equalsIgnoreCase(split[3]))
Material m = Arrays.stream(Material.values()).filter(t -> t.name().equalsIgnoreCase(split[3])).findFirst().orElse(null); .findFirst().orElse(null);
Material m = Arrays.stream(Material.values()).filter(t -> t.name().equalsIgnoreCase(split[3])).findFirst()
.orElse(null);
EntityGroup entgroup = addon.getSettings().getGroupLimitDefinitions().stream() EntityGroup entgroup = addon.getSettings().getGroupLimitDefinitions().stream()
.filter(t -> t.getName().equalsIgnoreCase(split[3])).findFirst().orElse(null); .filter(t -> t.getName().equalsIgnoreCase(split[3])).findFirst().orElse(null);
if (entgroup == null && et == null && m == null) { if (entgroup == null && et == null && m == null) {
logError(player.getName(), perms.getPermission(), split[3].toUpperCase(Locale.ENGLISH) + " is not a valid material or entity type/group."); logError(player.getName(), perms.getPermission(),
split[3].toUpperCase(Locale.ENGLISH) + " is not a valid material or entity type/group.");
break; break;
} }
// Make an ibc if required // Make an ibc if required
@ -100,8 +105,10 @@ public class JoinListener implements Listener {
runNullCheckAndSet(ibc, l); runNullCheckAndSet(ibc, l);
} }
// Check removed permissions // Check removed permissions
// If any changes have been made then store it - don't make files unless they are needed // If any changes have been made then store it - don't make files unless they
if (ibc != null) addon.getBlockLimitListener().setIsland(islandId, ibc); // are needed
if (ibc != null)
addon.getBlockLimitListener().setIsland(islandId, ibc);
} }
private boolean badSyntaxCheck(PermissionAttachmentInfo perms, String name, String permissionPrefix) { private boolean badSyntaxCheck(PermissionAttachmentInfo perms, String name, String permissionPrefix) {
@ -113,13 +120,14 @@ public class JoinListener implements Listener {
// Check formatting // Check formatting
String[] split = perms.getPermission().split("\\."); String[] split = perms.getPermission().split("\\.");
if (split.length != 5) { if (split.length != 5) {
logError(name, perms.getPermission(), "format must be '" + permissionPrefix + "MATERIAL.NUMBER', '" + permissionPrefix + "ENTITY-TYPE.NUMBER', or '" + permissionPrefix + "ENTITY-GROUP.NUMBER'"); logError(name, perms.getPermission(), "format must be '" + permissionPrefix + "MATERIAL.NUMBER', '"
+ permissionPrefix + "ENTITY-TYPE.NUMBER', or '" + permissionPrefix + "ENTITY-GROUP.NUMBER'");
return true; return true;
} }
// Check value // Check value
try { try {
Integer.parseInt(split[4]); Integer.parseInt(split[4]);
} catch(Exception e) { } catch (Exception e) {
logError(name, perms.getPermission(), "the last part MUST be an integer!"); logError(name, perms.getPermission(), "the last part MUST be an integer!");
return true; return true;
} }
@ -152,7 +160,7 @@ public class JoinListener implements Listener {
addon.log("Setting block limit " + m + " " + v); addon.log("Setting block limit " + m + " " + v);
// Material limit // Material limit
ibc.setBlockLimit(m, v); ibc.setBlockLimit(m, v);
} else if (et != null){ } else if (et != null) {
int v = Math.max(ibc.getEntityLimit(et), value); int v = Math.max(ibc.getEntityLimit(et), value);
addon.log("Setting entity limit " + et + " " + v); addon.log("Setting entity limit " + et + " " + v);
// This is an entity setting // This is an entity setting
@ -172,8 +180,7 @@ public class JoinListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onNewIsland(IslandEvent e) { public void onNewIsland(IslandEvent e) {
if (!e.getReason().equals(Reason.CREATED) if (!e.getReason().equals(Reason.CREATED) && !e.getReason().equals(Reason.RESETTED)
&& !e.getReason().equals(Reason.RESETTED)
&& !e.getReason().equals(Reason.REGISTERED)) { && !e.getReason().equals(Reason.REGISTERED)) {
return; return;
} }
@ -186,24 +193,24 @@ public class JoinListener implements Listener {
setOwnerPerms(e.getIsland(), e.getNewOwner()); setOwnerPerms(e.getIsland(), e.getNewOwner());
} }
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPlayerJoin(PlayerJoinEvent e) { public void onPlayerJoin(PlayerJoinEvent e) {
// Check if player has any islands in the game modes // Check if player has any islands in the game modes
addon.getGameModes().forEach(gm -> { addon.getGameModes().forEach(gm -> {
if (addon.getIslands().hasIsland(gm.getOverWorld(), e.getPlayer().getUniqueId())) { addon.getIslands().getIslands(gm.getOverWorld(), e.getPlayer().getUniqueId()).stream()
String islandId = Objects.requireNonNull(addon.getIslands().getIsland(gm.getOverWorld(), e.getPlayer().getUniqueId())).getUniqueId(); .map(Island::getUniqueId).forEach(islandId -> {
IslandBlockCount ibc = addon.getBlockLimitListener().getIsland(islandId); IslandBlockCount ibc = addon.getBlockLimitListener().getIsland(islandId);
if (joinEventCheck(e.getPlayer(), islandId, ibc)) { if (!joinEventCheck(e.getPlayer(), islandId, ibc)) {
return; checkPerms(e.getPlayer(), gm.getPermissionPrefix() + "island.limit.", islandId,
} gm.getDescription().getName());
checkPerms(e.getPlayer(), gm.getPermissionPrefix() + "island.limit.", islandId, gm.getDescription().getName());
} }
}); });
});
} }
/** /**
* Fire event so other addons can cancel this permissions change * Fire event so other addons can cancel this permissions change
*
* @param player player * @param player player
* @param islandId island id * @param islandId island id
* @param ibc island block count * @param ibc island block count
@ -218,7 +225,8 @@ public class JoinListener implements Listener {
} }
// Get ibc from event if it has changed // Get ibc from event if it has changed
ibc = e.getIbc(); ibc = e.getIbc();
// If perms should be ignored, but the IBC given in the event used, then set it and return // If perms should be ignored, but the IBC given in the event used, then set it
// and return
if (e.isIgnorePerms() && ibc != null) { if (e.isIgnorePerms() && ibc != null) {
addon.getBlockLimitListener().setIsland(islandId, ibc); addon.getBlockLimitListener().setIsland(islandId, ibc);
return true; return true;
@ -258,7 +266,8 @@ public class JoinListener implements Listener {
String prefix = addon.getGameModePermPrefix(world); String prefix = addon.getGameModePermPrefix(world);
String name = addon.getGameModeName(world); String name = addon.getGameModeName(world);
if (!prefix.isEmpty() && !name.isEmpty() && owner.getPlayer() != null) { if (!prefix.isEmpty() && !name.isEmpty() && owner.getPlayer() != null) {
checkPerms(Objects.requireNonNull(owner.getPlayer()), prefix + "island.limit.", island.getUniqueId(), name); checkPerms(Objects.requireNonNull(owner.getPlayer()), prefix + "island.limit.",
island.getUniqueId(), name);
} }
} }
} }

View File

@ -3,6 +3,7 @@ package world.bentobox.limits.objects;
import java.util.EnumMap; import java.util.EnumMap;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
@ -19,35 +20,36 @@ import world.bentobox.bentobox.database.objects.Table;
@Table(name = "IslandBlockCount") @Table(name = "IslandBlockCount")
public class IslandBlockCount implements DataObject { public class IslandBlockCount implements DataObject {
@Expose
private String uniqueId;
@Expose
private String gameMode;
@Expose @Expose
private Map<Material, Integer> blockCounts = new EnumMap<>(Material.class); private Map<Material, Integer> blockCounts = new EnumMap<>(Material.class);
private boolean changed;
/** /**
* Permission based limits * Permission based limits
*/ */
@Expose @Expose
private Map<Material, Integer> blockLimits = new EnumMap<>(Material.class); private Map<Material, Integer> blockLimits = new EnumMap<>(Material.class);
@Expose @Expose
private Map<EntityType, Integer> entityLimits = new EnumMap<>(EntityType.class); private Map<Material, Integer> blockLimitsOffset = new EnumMap<>(Material.class);
private boolean changed;
@Expose @Expose
private Map<String, Integer> entityGroupLimits = new HashMap<>(); private Map<String, Integer> entityGroupLimits = new HashMap<>();
@Expose @Expose
private Map<Material, Integer> blockLimitsOffset = new EnumMap<>(Material.class); private Map<String, Integer> entityGroupLimitsOffset = new HashMap<>();
@Expose
private Map<EntityType, Integer> entityLimits = new EnumMap<>(EntityType.class);
@Expose @Expose
private Map<EntityType, Integer> entityLimitsOffset = new EnumMap<>(EntityType.class); private Map<EntityType, Integer> entityLimitsOffset = new EnumMap<>(EntityType.class);
@Expose @Expose
private Map<String, Integer> entityGroupLimitsOffset = new HashMap<>(); private String gameMode;
@Expose
private String uniqueId;
/** /**
* Create an island block count object * Create an island block count object
*
* @param islandId - unique Island ID string * @param islandId - unique Island ID string
* @param gameMode - Game mode name from gm.getDescription().getName() * @param gameMode - Game mode name from gm.getDescription().getName()
*/ */
@ -57,23 +59,42 @@ public class IslandBlockCount implements DataObject {
setChanged(); setChanged();
} }
/* (non-Javadoc) /**
* @see world.bentobox.bentobox.database.objects.DataObject#getUniqueId() * Add a material to the count
*
* @param material - material
*/ */
@Override public void add(Material material) {
public String getUniqueId() { getBlockCounts().merge(material, 1, Integer::sum);
return uniqueId; setChanged();
} }
/* (non-Javadoc) /**
* @see world.bentobox.bentobox.database.objects.DataObject#setUniqueId(java.lang.String) * Clear all island-specific entity group limits
*/ */
@Override public void clearEntityGroupLimits() {
public void setUniqueId(String uniqueId) { entityGroupLimits.clear();
this.uniqueId = uniqueId;
setChanged(); setChanged();
} }
/**
* Clear all island-specific entity type limits
*/
public void clearEntityLimits() {
entityLimits.clear();
setChanged();
}
/**
* Get the block count for this material for this island
*
* @param m - material
* @return count
*/
public Integer getBlockCount(Material m) {
return getBlockCounts().getOrDefault(m, 0);
}
/** /**
* @return the blockCount * @return the blockCount
*/ */
@ -84,92 +105,19 @@ public class IslandBlockCount implements DataObject {
return blockCounts; return blockCounts;
} }
/**
* @param blockCounts the blockCount to set
*/
public void setBlockCounts(Map<Material, Integer> blockCounts) {
this.blockCounts = blockCounts;
setChanged();
}
/**
* Get the block count for this material for this island
* @param m - material
* @return count
*/
public Integer getBlockCount(Material m) {
return blockCounts.getOrDefault(m, 0);
}
/**
* Add a material to the count
* @param material - material
*/
public void add(Material material) {
blockCounts.merge(material, 1, Integer::sum);
setChanged();
}
/**
* Remove a material from the count
* @param material - material
*/
public void remove(Material material) {
blockCounts.put(material, blockCounts.getOrDefault(material, 0) - 1);
blockCounts.values().removeIf(v -> v <= 0);
setChanged();
}
/**
* Check if this material is at or over a limit
* @param material - block material
* @param limit - limit to check
* @return true if count is >= limit
*/
public boolean isAtLimit(Material material, int limit) {
return blockCounts.getOrDefault(material, 0) >= limit + this.getBlockLimitOffset(material);
}
/**
* Check if no more of this material can be added to this island
* @param m - material
* @return true if no more material can be added
*/
public boolean isAtLimit(Material m) {
// Check island limits first
return blockLimits.containsKey(m) && blockCounts.getOrDefault(m, 0) >= getBlockLimit(m) + this.getBlockLimitOffset(m);
}
public boolean isBlockLimited(Material m) {
return blockLimits.containsKey(m);
}
/**
* @return the blockLimits
*/
public Map<Material, Integer> getBlockLimits() {
return blockLimits;
}
/**
* @param blockLimits the blockLimits to set
*/
public void setBlockLimits(Map<Material, Integer> blockLimits) {
this.blockLimits = blockLimits;
setChanged();
}
/** /**
* Get the block limit for this material for this island * Get the block limit for this material for this island
*
* @param m - material * @param m - material
* @return limit or -1 for unlimited * @return limit or -1 for unlimited
*/ */
public int getBlockLimit(Material m) { public int getBlockLimit(Material m) {
return blockLimits.getOrDefault(m, -1); return getBlockLimits().getOrDefault(m, -1);
} }
/** /**
* Get the block offset for this material for this island * Get the block offset for this material for this island
*
* @param m - material * @param m - material
* @return offset * @return offset
*/ */
@ -178,155 +126,10 @@ public class IslandBlockCount implements DataObject {
} }
/** /**
* Set the block limit for this material for this island * @return the blockLimits
* @param m - material
* @param limit - maximum number allowed
*/ */
public void setBlockLimit(Material m, int limit) { public Map<Material, Integer> getBlockLimits() {
blockLimits.put(m, limit); return Objects.requireNonNullElse(blockLimits, new EnumMap<>(Material.class));
setChanged();
}
/**
* @return the gameMode
*/
public String getGameMode() {
return gameMode;
}
public boolean isGameMode(String gameMode) {
return this.gameMode.equals(gameMode);
}
/**
* @param gameMode the gameMode to set
*/
public void setGameMode(String gameMode) {
this.gameMode = gameMode;
setChanged();
}
/**
* @return the entityLimits
*/
public Map<EntityType, Integer> getEntityLimits() {
return entityLimits;
}
/**
* @param entityLimits the entityLimits to set
*/
public void setEntityLimits(Map<EntityType, Integer> entityLimits) {
this.entityLimits = entityLimits;
setChanged();
}
/**
* Set an island-specific entity type limit
* @param t - entity type
* @param limit - limit
*/
public void setEntityLimit(EntityType t, int limit) {
entityLimits.put(t, limit);
setChanged();
}
/**
* Get the limit for an entity type
* @param t - entity type
* @return limit or -1 for unlimited
*/
public int getEntityLimit(EntityType t) {
return entityLimits.getOrDefault(t, -1);
}
/**
* Get the limit offset for an entity type
* @param t - entity type
* @return offset
*/
public int getEntityLimitOffset(EntityType t) {
return getEntityLimitsOffset().getOrDefault(t, 0);
}
/**
* Clear all island-specific entity type limits
*/
public void clearEntityLimits() {
entityLimits.clear();
setChanged();
}
/**
* @return the entityGroupLimits
*/
public Map<String, Integer> getEntityGroupLimits() {
return entityGroupLimits;
}
/**
* @param entityGroupLimits the entityGroupLimits to set
*/
public void setEntityGroupLimits(Map<String, Integer> entityGroupLimits) {
this.entityGroupLimits = entityGroupLimits;
setChanged();
}
/**
* Set an island-specific entity group limit
* @param name - entity group
* @param limit - limit
*/
public void setEntityGroupLimit(String name, int limit) {
entityGroupLimits.put(name, limit);
setChanged();
}
/**
* Get the limit for an entity group
* @param name - entity group
* @return limit or -1 for unlimited
*/
public int getEntityGroupLimit(String name) {
return entityGroupLimits.getOrDefault(name, -1);
}
/**
* Get the offset for an entity group
* @param name - entity group
* @return offset
*/
public int getEntityGroupLimitOffset(String name) {
return getEntityGroupLimitsOffset().getOrDefault(name, 0);
}
/**
* Clear all island-specific entity group limits
*/
public void clearEntityGroupLimits() {
entityGroupLimits.clear();
setChanged();
}
/**
* @return the changed
*/
public boolean isChanged() {
return changed;
}
/**
* @param changed the changed to set
*/
public void setChanged(boolean changed) {
this.changed = changed;
}
/**
* Mark changed
*/
public void setChanged() {
this.changed = true;
} }
/** /**
@ -340,31 +143,30 @@ public class IslandBlockCount implements DataObject {
} }
/** /**
* Set an offset to a block limit. This will increase/decrease the value of the limit. * Get the limit for an entity group
* @param m material *
* @param blockLimitsOffset the blockLimitsOffset to set * @param name - entity group
* @return limit or -1 for unlimited
*/ */
public void setBlockLimitsOffset(Material m, Integer blockLimitsOffset) { public int getEntityGroupLimit(String name) {
getBlockLimitsOffset().put(m, blockLimitsOffset); return getEntityGroupLimits().getOrDefault(name, -1);
} }
/** /**
* @return the entityLimitsOffset * Get the offset for an entity group
*
* @param name - entity group
* @return offset
*/ */
public Map<EntityType, Integer> getEntityLimitsOffset() { public int getEntityGroupLimitOffset(String name) {
if (entityLimitsOffset == null) { return getEntityGroupLimitsOffset().getOrDefault(name, 0);
entityLimitsOffset = new EnumMap<>(EntityType.class);
}
return entityLimitsOffset;
} }
/** /**
* Set an offset to an entity limit. This will increase/decrease the value of the limit. * @return the entityGroupLimits
* @param t Entity Type
* @param entityLimitsOffset the entityLimitsOffset to set
*/ */
public void setEntityLimitsOffset(EntityType t, Integer entityLimitsOffset) { public Map<String, Integer> getEntityGroupLimits() {
this.getEntityLimitsOffset().put(t, entityLimitsOffset); return Objects.requireNonNullElse(entityGroupLimits, new HashMap<>());
} }
/** /**
@ -378,11 +180,238 @@ public class IslandBlockCount implements DataObject {
} }
/** /**
* Set an offset to an entity group limit. This will increase/decrease the value of the limit. * Get the limit for an entity type
*
* @param t - entity type
* @return limit or -1 for unlimited
*/
public int getEntityLimit(EntityType t) {
return getEntityLimits().getOrDefault(t, -1);
}
/**
* Get the limit offset for an entity type
*
* @param t - entity type
* @return offset
*/
public int getEntityLimitOffset(EntityType t) {
return getEntityLimitsOffset().getOrDefault(t, 0);
}
/**
* @return the entityLimits
*/
public Map<EntityType, Integer> getEntityLimits() {
return Objects.requireNonNullElse(entityLimits, new EnumMap<>(EntityType.class));
}
/**
* @return the entityLimitsOffset
*/
public Map<EntityType, Integer> getEntityLimitsOffset() {
if (entityLimitsOffset == null) {
entityLimitsOffset = new EnumMap<>(EntityType.class);
}
return entityLimitsOffset;
}
/**
* @return the gameMode
*/
public String getGameMode() {
return gameMode;
}
/*
* (non-Javadoc)
*
* @see world.bentobox.bentobox.database.objects.DataObject#getUniqueId()
*/
@Override
public String getUniqueId() {
return uniqueId;
}
/**
* Check if no more of this material can be added to this island
*
* @param m - material
* @return true if no more material can be added
*/
public boolean isAtLimit(Material m) {
// Check island limits first
return getBlockLimits().containsKey(m)
&& getBlockCounts().getOrDefault(m, 0) >= getBlockLimit(m) + this.getBlockLimitOffset(m);
}
/**
* Check if this material is at or over a limit
*
* @param material - block material
* @param limit - limit to check
* @return true if count is >= limit
*/
public boolean isAtLimit(Material material, int limit) {
return getBlockCounts().getOrDefault(material, 0) >= limit + this.getBlockLimitOffset(material);
}
public boolean isBlockLimited(Material m) {
return getBlockLimits().containsKey(m);
}
/**
* @return the changed
*/
public boolean isChanged() {
return changed;
}
public boolean isGameMode(String gameMode) {
return getGameMode().equals(gameMode);
}
/**
* Remove a material from the count
*
* @param material - material
*/
public void remove(Material material) {
getBlockCounts().put(material, getBlockCounts().getOrDefault(material, 0) - 1);
getBlockCounts().values().removeIf(v -> v <= 0);
setChanged();
}
/**
* @param blockCounts the blockCount to set
*/
public void setBlockCounts(Map<Material, Integer> blockCounts) {
this.blockCounts = blockCounts;
setChanged();
}
/**
* Set the block limit for this material for this island
*
* @param m - material
* @param limit - maximum number allowed
*/
public void setBlockLimit(Material m, int limit) {
getBlockLimits().put(m, limit);
setChanged();
}
/**
* @param blockLimits the blockLimits to set
*/
public void setBlockLimits(Map<Material, Integer> blockLimits) {
this.blockLimits = blockLimits;
setChanged();
}
/**
* Set an offset to a block limit. This will increase/decrease the value of the
* limit.
*
* @param m material
* @param blockLimitsOffset the blockLimitsOffset to set
*/
public void setBlockLimitsOffset(Material m, Integer blockLimitsOffset) {
getBlockLimitsOffset().put(m, blockLimitsOffset);
}
/**
* Mark changed
*/
public void setChanged() {
this.changed = true;
}
/**
* @param changed the changed to set
*/
public void setChanged(boolean changed) {
this.changed = changed;
}
/**
* Set an island-specific entity group limit
*
* @param name - entity group
* @param limit - limit
*/
public void setEntityGroupLimit(String name, int limit) {
getEntityGroupLimits().put(name, limit);
setChanged();
}
/**
* @param entityGroupLimits the entityGroupLimits to set
*/
public void setEntityGroupLimits(Map<String, Integer> entityGroupLimits) {
this.entityGroupLimits = entityGroupLimits;
setChanged();
}
/**
* Set an offset to an entity group limit. This will increase/decrease the value
* of the limit.
*
* @param name group name * @param name group name
* @param entityGroupLimitsOffset the entityGroupLimitsOffset to set * @param entityGroupLimitsOffset the entityGroupLimitsOffset to set
*/ */
public void setEntityGroupLimitsOffset(String name, Integer entityGroupLimitsOffset) { public void setEntityGroupLimitsOffset(String name, Integer entityGroupLimitsOffset) {
getEntityGroupLimitsOffset().put(name, entityGroupLimitsOffset); getEntityGroupLimitsOffset().put(name, entityGroupLimitsOffset);
} }
/**
* Set an island-specific entity type limit
*
* @param t - entity type
* @param limit - limit
*/
public void setEntityLimit(EntityType t, int limit) {
getEntityLimits().put(t, limit);
setChanged();
}
/**
* @param entityLimits the entityLimits to set
*/
public void setEntityLimits(Map<EntityType, Integer> entityLimits) {
this.entityLimits = entityLimits;
setChanged();
}
/**
* Set an offset to an entity limit. This will increase/decrease the value of
* the limit.
*
* @param type Entity Type
* @param entityLimitsOffset the entityLimitsOffset to set
*/
public void setEntityLimitsOffset(EntityType type, Integer entityLimitsOffset) {
this.getEntityLimitsOffset().put(type, entityLimitsOffset);
}
/**
* @param gameMode the gameMode to set
*/
public void setGameMode(String gameMode) {
this.gameMode = gameMode;
setChanged();
}
/*
* (non-Javadoc)
*
* @see
* world.bentobox.bentobox.database.objects.DataObject#setUniqueId(java.lang.
* String)
*/
@Override
public void setUniqueId(String uniqueId) {
this.uniqueId = uniqueId;
setChanged();
}
} }

View File

@ -1,7 +1,7 @@
name: Limits name: Limits
main: world.bentobox.limits.Limits main: world.bentobox.limits.Limits
version: ${version}${build.number} version: ${version}${build.number}
api-version: 1.16.5 api-version: 2.0.0
authors: tastybento authors: tastybento

View File

@ -1,7 +1,5 @@
package bentobox.addon.limits.listeners; package bentobox.addon.limits.listeners;
import java.util.*;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
@ -11,6 +9,14 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
@ -45,7 +51,7 @@ import world.bentobox.limits.objects.IslandBlockCount;
* *
*/ */
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
@PrepareForTest( {Bukkit.class} ) @PrepareForTest({ Bukkit.class })
public class JoinListenerTest { public class JoinListenerTest {
@Mock @Mock
@ -80,11 +86,12 @@ public class JoinListenerTest {
when(addon.getGameModePermPrefix(any())).thenReturn("bskyblock."); when(addon.getGameModePermPrefix(any())).thenReturn("bskyblock.");
when(addon.getSettings()).thenReturn(settings); when(addon.getSettings()).thenReturn(settings);
// Settings // Settings
when(settings.getGroupLimitDefinitions()).thenReturn(new ArrayList<>(List.of(new Settings.EntityGroup("friendly", new HashSet<>(), -1)))); when(settings.getGroupLimitDefinitions())
.thenReturn(new ArrayList<>(List.of(new Settings.EntityGroup("friendly", new HashSet<>(), -1))));
// Island Manager // Island Manager
when(im.hasIsland(any(), any(UUID.class))).thenReturn(true);
when(island.getUniqueId()).thenReturn("unique_id"); when(island.getUniqueId()).thenReturn("unique_id");
when(im.getIsland(any(), any(UUID.class))).thenReturn(island); when(im.getIsland(any(), any(UUID.class))).thenReturn(island);
when(im.getIslands(any(), any(UUID.class))).thenReturn(Set.of(island));
// Default is that player has island // Default is that player has island
when(addon.getIslands()).thenReturn(im); when(addon.getIslands()).thenReturn(im);
// Player // Player
@ -114,7 +121,8 @@ public class JoinListenerTest {
} }
/** /**
* Test method for {@link world.bentobox.limits.listeners.JoinListener#onNewIsland(world.bentobox.bentobox.api.events.island.IslandEvent)}. * Test method for
* {@link world.bentobox.limits.listeners.JoinListener#onNewIsland(world.bentobox.bentobox.api.events.island.IslandEvent)}.
*/ */
@Test @Test
public void testOnNewIslandWrongReason() { public void testOnNewIslandWrongReason() {
@ -124,7 +132,8 @@ public class JoinListenerTest {
} }
/** /**
* Test method for {@link world.bentobox.limits.listeners.JoinListener#onNewIsland(world.bentobox.bentobox.api.events.island.IslandEvent)}. * Test method for
* {@link world.bentobox.limits.listeners.JoinListener#onNewIsland(world.bentobox.bentobox.api.events.island.IslandEvent)}.
*/ */
@Test @Test
public void testOnNewIslandRegistered() { public void testOnNewIslandRegistered() {
@ -134,7 +143,8 @@ public class JoinListenerTest {
} }
/** /**
* Test method for {@link world.bentobox.limits.listeners.JoinListener#onNewIsland(world.bentobox.bentobox.api.events.island.IslandEvent)}. * Test method for
* {@link world.bentobox.limits.listeners.JoinListener#onNewIsland(world.bentobox.bentobox.api.events.island.IslandEvent)}.
*/ */
@Test @Test
public void testOnNewIslandResetted() { public void testOnNewIslandResetted() {
@ -185,7 +195,8 @@ public class JoinListenerTest {
} }
/** /**
* Test method for {@link world.bentobox.limits.listeners.JoinListener#onOwnerChange(world.bentobox.bentobox.api.events.team.TeamEvent.TeamSetownerEvent)}. * Test method for
* {@link world.bentobox.limits.listeners.JoinListener#onOwnerChange(world.bentobox.bentobox.api.events.team.TeamEvent.TeamSetownerEvent)}.
*/ */
@Test @Test
public void testOnOwnerChange() { public void testOnOwnerChange() {
@ -198,7 +209,8 @@ public class JoinListenerTest {
} }
/** /**
* Test method for {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}. * Test method for
* {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}.
*/ */
@Test @Test
public void testOnPlayerJoin() { public void testOnPlayerJoin() {
@ -209,7 +221,8 @@ public class JoinListenerTest {
} }
/** /**
* Test method for {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}. * Test method for
* {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}.
*/ */
@Test @Test
public void testOnPlayerJoinIBCNull() { public void testOnPlayerJoinIBCNull() {
@ -220,9 +233,9 @@ public class JoinListenerTest {
verify(bll, never()).setIsland("unique_id", ibc); verify(bll, never()).setIsland("unique_id", ibc);
} }
/** /**
* Test method for {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}. * Test method for
* {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}.
*/ */
@Test @Test
public void testOnPlayerJoinWithPermNotLimits() { public void testOnPlayerJoinWithPermNotLimits() {
@ -238,7 +251,8 @@ public class JoinListenerTest {
} }
/** /**
* Test method for {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}. * Test method for
* {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}.
*/ */
@Test @Test
public void testOnPlayerJoinWithPermLimitsWrongSize() { public void testOnPlayerJoinWithPermLimitsWrongSize() {
@ -250,11 +264,13 @@ public class JoinListenerTest {
when(player.getEffectivePermissions()).thenReturn(perms); when(player.getEffectivePermissions()).thenReturn(perms);
PlayerJoinEvent e = new PlayerJoinEvent(player, "welcome"); PlayerJoinEvent e = new PlayerJoinEvent(player, "welcome");
jl.onPlayerJoin(e); jl.onPlayerJoin(e);
verify(addon).logError("Player tastybento has permission: 'bskyblock.island.limit.my.perm.for.game' but format must be 'bskyblock.island.limit.MATERIAL.NUMBER', 'bskyblock.island.limit.ENTITY-TYPE.NUMBER', or 'bskyblock.island.limit.ENTITY-GROUP.NUMBER' Ignoring..."); verify(addon).logError(
"Player tastybento has permission: 'bskyblock.island.limit.my.perm.for.game' but format must be 'bskyblock.island.limit.MATERIAL.NUMBER', 'bskyblock.island.limit.ENTITY-TYPE.NUMBER', or 'bskyblock.island.limit.ENTITY-GROUP.NUMBER' Ignoring...");
} }
/** /**
* Test method for {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}. * Test method for
* {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}.
*/ */
@Test @Test
public void testOnPlayerJoinWithPermLimitsInvalidMaterial() { public void testOnPlayerJoinWithPermLimitsInvalidMaterial() {
@ -266,11 +282,13 @@ public class JoinListenerTest {
when(player.getEffectivePermissions()).thenReturn(perms); when(player.getEffectivePermissions()).thenReturn(perms);
PlayerJoinEvent e = new PlayerJoinEvent(player, "welcome"); PlayerJoinEvent e = new PlayerJoinEvent(player, "welcome");
jl.onPlayerJoin(e); jl.onPlayerJoin(e);
verify(addon).logError("Player tastybento has permission: 'bskyblock.island.limit.mumbo.34' but MUMBO is not a valid material or entity type/group. Ignoring..."); verify(addon).logError(
"Player tastybento has permission: 'bskyblock.island.limit.mumbo.34' but MUMBO is not a valid material or entity type/group. Ignoring...");
} }
/** /**
* Test method for {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}. * Test method for
* {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}.
*/ */
@Test @Test
public void testOnPlayerJoinWithPermLimitsWildcard() { public void testOnPlayerJoinWithPermLimitsWildcard() {
@ -282,11 +300,13 @@ public class JoinListenerTest {
when(player.getEffectivePermissions()).thenReturn(perms); when(player.getEffectivePermissions()).thenReturn(perms);
PlayerJoinEvent e = new PlayerJoinEvent(player, "welcome"); PlayerJoinEvent e = new PlayerJoinEvent(player, "welcome");
jl.onPlayerJoin(e); jl.onPlayerJoin(e);
verify(addon).logError("Player tastybento has permission: 'bskyblock.island.limit.*' but wildcards are not allowed. Ignoring..."); verify(addon).logError(
"Player tastybento has permission: 'bskyblock.island.limit.*' but wildcards are not allowed. Ignoring...");
} }
/** /**
* Test method for {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}. * Test method for
* {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}.
*/ */
@Test @Test
public void testOnPlayerJoinWithPermLimitsNotNumber() { public void testOnPlayerJoinWithPermLimitsNotNumber() {
@ -298,11 +318,13 @@ public class JoinListenerTest {
when(player.getEffectivePermissions()).thenReturn(perms); when(player.getEffectivePermissions()).thenReturn(perms);
PlayerJoinEvent e = new PlayerJoinEvent(player, "welcome"); PlayerJoinEvent e = new PlayerJoinEvent(player, "welcome");
jl.onPlayerJoin(e); jl.onPlayerJoin(e);
verify(addon).logError("Player tastybento has permission: 'bskyblock.island.limit.STONE.abc' but the last part MUST be an integer! Ignoring..."); verify(addon).logError(
"Player tastybento has permission: 'bskyblock.island.limit.STONE.abc' but the last part MUST be an integer! Ignoring...");
} }
/** /**
* Test method for {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}. * Test method for
* {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}.
*/ */
@Test @Test
public void testOnPlayerJoinWithPermLimitsSuccess() { public void testOnPlayerJoinWithPermLimitsSuccess() {
@ -319,7 +341,8 @@ public class JoinListenerTest {
} }
/** /**
* Test method for {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}. * Test method for
* {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}.
*/ */
@Test @Test
public void testOnPlayerJoinWithPermLimitsSuccessEntity() { public void testOnPlayerJoinWithPermLimitsSuccessEntity() {
@ -336,7 +359,8 @@ public class JoinListenerTest {
} }
/** /**
* Test method for {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}. * Test method for
* {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}.
*/ */
@Test @Test
public void testOnPlayerJoinWithPermLimitsSuccessEntityGroup() { public void testOnPlayerJoinWithPermLimitsSuccessEntityGroup() {
@ -353,7 +377,8 @@ public class JoinListenerTest {
} }
/** /**
* Test method for {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}. * Test method for
* {@link world.bentobox.limits.listeners.JoinListener#onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent)}.
*/ */
@Test @Test
public void testOnPlayerJoinWithPermLimitsMultiPerms() { public void testOnPlayerJoinWithPermLimitsMultiPerms() {
@ -363,7 +388,7 @@ public class JoinListenerTest {
when(permAtt.getValue()).thenReturn(true); when(permAtt.getValue()).thenReturn(true);
perms.add(permAtt); perms.add(permAtt);
PermissionAttachmentInfo permAtt2 = mock(PermissionAttachmentInfo.class); PermissionAttachmentInfo permAtt2 = mock(PermissionAttachmentInfo.class);
when(permAtt2.getPermission()).thenReturn("bskyblock.island.limit.grass.14"); when(permAtt2.getPermission()).thenReturn("bskyblock.island.limit.short_grass.14");
when(permAtt2.getValue()).thenReturn(true); when(permAtt2.getValue()).thenReturn(true);
perms.add(permAtt2); perms.add(permAtt2);
PermissionAttachmentInfo permAtt3 = mock(PermissionAttachmentInfo.class); PermissionAttachmentInfo permAtt3 = mock(PermissionAttachmentInfo.class);
@ -388,7 +413,7 @@ public class JoinListenerTest {
jl.onPlayerJoin(e); jl.onPlayerJoin(e);
verify(addon, never()).logError(anyString()); verify(addon, never()).logError(anyString());
verify(ibc).setBlockLimit(eq(Material.STONE), eq(24)); verify(ibc).setBlockLimit(eq(Material.STONE), eq(24));
verify(ibc).setBlockLimit(eq(Material.GRASS), eq(14)); verify(ibc).setBlockLimit(eq(Material.SHORT_GRASS), eq(14));
verify(ibc).setBlockLimit(eq(Material.DIRT), eq(34)); verify(ibc).setBlockLimit(eq(Material.DIRT), eq(34));
verify(ibc).setEntityLimit(eq(EntityType.CHICKEN), eq(34)); verify(ibc).setEntityLimit(eq(EntityType.CHICKEN), eq(34));
verify(ibc).setEntityLimit(eq(EntityType.CAVE_SPIDER), eq(4)); verify(ibc).setEntityLimit(eq(EntityType.CAVE_SPIDER), eq(4));
@ -455,7 +480,8 @@ public class JoinListenerTest {
} }
/** /**
* Test method for {@link world.bentobox.limits.listeners.JoinListener#onUnregisterIsland(world.bentobox.bentobox.api.events.island.IslandEvent)}. * Test method for
* {@link world.bentobox.limits.listeners.JoinListener#onUnregisterIsland(world.bentobox.bentobox.api.events.island.IslandEvent)}.
*/ */
@Test @Test
public void testOnUnregisterIslandNotUnregistered() { public void testOnUnregisterIslandNotUnregistered() {
@ -465,7 +491,8 @@ public class JoinListenerTest {
} }
/** /**
* Test method for {@link world.bentobox.limits.listeners.JoinListener#onUnregisterIsland(world.bentobox.bentobox.api.events.island.IslandEvent)}. * Test method for
* {@link world.bentobox.limits.listeners.JoinListener#onUnregisterIsland(world.bentobox.bentobox.api.events.island.IslandEvent)}.
*/ */
@Test @Test
public void testOnUnregisterIslandNotInWorld() { public void testOnUnregisterIslandNotInWorld() {
@ -476,7 +503,8 @@ public class JoinListenerTest {
} }
/** /**
* Test method for {@link world.bentobox.limits.listeners.JoinListener#onUnregisterIsland(world.bentobox.bentobox.api.events.island.IslandEvent)}. * Test method for
* {@link world.bentobox.limits.listeners.JoinListener#onUnregisterIsland(world.bentobox.bentobox.api.events.island.IslandEvent)}.
*/ */
@Test @Test
public void testOnUnregisterIslandInWorld() { public void testOnUnregisterIslandInWorld() {
@ -510,6 +538,4 @@ public class JoinListenerTest {
} }
} }