From ff78bf30f6a9d7c6bbab4b66ce05808625bb12d4 Mon Sep 17 00:00:00 2001 From: CraftBukkit/Spigot Date: Mon, 12 Jun 2023 19:41:02 +1000 Subject: [PATCH] #1182: Consolidate Preconditions use and minor cleanup By: Doc --- paper-server/README.md | 26 +- .../org/bukkit/craftbukkit/CraftEffect.java | 6 +- .../bukkit/craftbukkit/CraftIpBanList.java | 10 +- .../craftbukkit/CraftProfileBanList.java | 10 +- .../craftbukkit/CraftRegionAccessor.java | 12 +- .../org/bukkit/craftbukkit/CraftServer.java | 143 +++++----- .../bukkit/craftbukkit/CraftStatistic.java | 70 ++--- .../org/bukkit/craftbukkit/CraftWorld.java | 128 +++++---- .../bukkit/craftbukkit/block/CraftBlock.java | 16 +- .../craftbukkit/block/CraftBlockState.java | 16 +- .../block/CraftStructureBlock.java | 26 +- .../command/VanillaCommandWrapper.java | 8 +- .../entity/CraftAbstractHorse.java | 9 +- .../entity/CraftAreaEffectCloud.java | 10 +- .../bukkit/craftbukkit/entity/CraftArrow.java | 10 +- .../craftbukkit/entity/CraftEntity.java | 17 +- .../craftbukkit/entity/CraftFireball.java | 4 +- .../craftbukkit/entity/CraftFishHook.java | 24 +- .../bukkit/craftbukkit/entity/CraftFox.java | 8 +- .../bukkit/craftbukkit/entity/CraftHorse.java | 9 +- .../craftbukkit/entity/CraftHumanEntity.java | 4 +- .../craftbukkit/entity/CraftItemFrame.java | 5 +- .../craftbukkit/entity/CraftLivingEntity.java | 13 +- .../craftbukkit/entity/CraftPlayer.java | 254 +++++++----------- .../craftbukkit/entity/CraftThrownPotion.java | 9 +- .../craftbukkit/entity/CraftTippedArrow.java | 4 +- .../craftbukkit/entity/CraftVillager.java | 9 +- .../entity/CraftVillagerZombie.java | 8 +- .../craftbukkit/event/CraftEventFactory.java | 6 +- .../craftbukkit/generator/CraftChunkData.java | 5 +- .../generator/CraftLimitedRegion.java | 4 +- .../help/CommandAliasHelpTopic.java | 6 +- .../craftbukkit/help/SimpleHelpMap.java | 5 +- .../craftbukkit/inventory/CraftInventory.java | 30 +-- .../inventory/CraftInventoryCrafting.java | 9 +- .../inventory/CraftInventoryCustom.java | 4 +- .../inventory/CraftInventoryDoubleChest.java | 5 +- .../inventory/CraftInventoryPlayer.java | 5 +- .../inventory/CraftItemFactory.java | 33 +-- .../craftbukkit/inventory/CraftItemStack.java | 8 +- .../inventory/CraftMerchantCustom.java | 5 +- .../inventory/CraftMetaBanner.java | 5 +- .../inventory/CraftMetaBlockState.java | 6 +- .../craftbukkit/inventory/CraftMetaBook.java | 11 +- .../inventory/CraftMetaFirework.java | 32 +-- .../craftbukkit/inventory/CraftMetaItem.java | 15 +- .../inventory/CraftMetaPotion.java | 27 +- .../inventory/CraftMetaSuspiciousStew.java | 29 +- .../craftbukkit/inventory/CraftRecipe.java | 5 +- .../inventory/InventoryIterator.java | 5 +- .../craftbukkit/inventory/RecipeIterator.java | 6 +- .../tags/DeprecatedContainerTagType.java | 8 +- .../craftbukkit/legacy/CraftLegacy.java | 10 +- .../craftbukkit/map/CraftMapCanvas.java | 19 +- .../bukkit/craftbukkit/map/CraftMapView.java | 15 +- .../metadata/BlockMetadataStore.java | 29 +- .../CraftPersistentDataContainer.java | 18 +- .../CraftPersistentDataTypeRegistry.java | 17 +- .../profile/CraftPlayerProfile.java | 4 +- .../CraftBlockProjectileSource.java | 6 +- .../craftbukkit/scheduler/CraftScheduler.java | 11 +- .../scoreboard/CraftObjective.java | 38 ++- .../scoreboard/CraftScoreboard.java | 69 ++--- .../scoreboard/CraftScoreboardManager.java | 4 +- .../craftbukkit/scoreboard/CraftTeam.java | 75 +++--- .../craftbukkit/structure/CraftStructure.java | 28 +- .../structure/CraftStructureManager.java | 34 +-- .../craftbukkit/util/CraftMagicNumbers.java | 4 +- .../craftbukkit/util/LazyPlayerSet.java | 5 +- .../bukkit/craftbukkit/util/UnsafeList.java | 5 +- .../org/bukkit/craftbukkit/util/Waitable.java | 5 +- .../craftbukkit/util/WeakCollection.java | 12 +- 72 files changed, 695 insertions(+), 855 deletions(-) diff --git a/paper-server/README.md b/paper-server/README.md index 64160a75ec..3db2c7cfd1 100644 --- a/paper-server/README.md +++ b/paper-server/README.md @@ -152,18 +152,32 @@ if (false && !this.world.isClientSide && !this.isDead && (d0*d0) + d1 + (d2*d2) this.h(); } ``` - -* When adding a validation check, this applies everywhere not just in Minecraft classes, see if the Validate package has a better, more concise method you can use instead. - * The Preconditions package works just as well. Either are acceptable; though these are, by no means, the only accepted validation strategies. +* For checks related to API where an exception needs to be thrown in a specific case we recommend use the package `Preconditions` + * For checking arguments we recommend using `Preconditions#checkArgument` where a failing check should throw a `IllegalArgumentException` + * We recommend using this to ensure the behaviour of `@NotNull` in the Bukkit API + * For checking arguments we recommend using `Preconditions#checkState` where a failing check should throw a `IllegalStateException` __For example, you should use:__ ```java -Validate.notNull(sender, "Sender cannot be null"); +private Object messenger; + +public void sendMessage(Sender sender, String message) { + Preconditions.checkArgument(sender != null, "sender cannot be null"); + Preconditions.checkState(this.messenger != null, "The messenger instance cannot be used") +} ``` __Instead of:__ ```java -if (sender == null) { - throw new IllegalArgumentException("Sender cannot be null"); +private Object messenger; + +public void sendMessage(Sender sender, String message) { + if (sender == null) { + throw new IllegalArgumentException("Sender cannot be null"); + } + + if (this.messenger == null) { + throw new IllegalStateException("The messenger instance cannot be used"); + } } ``` diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/CraftEffect.java b/paper-server/src/main/java/org/bukkit/craftbukkit/CraftEffect.java index da975e6360..5a5a8945c7 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/CraftEffect.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/CraftEffect.java @@ -1,8 +1,8 @@ package org.bukkit.craftbukkit; +import com.google.common.base.Preconditions; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; -import org.apache.commons.lang.Validate; import org.bukkit.Axis; import org.bukkit.Color; import org.bukkit.Effect; @@ -25,7 +25,7 @@ public class CraftEffect { datavalue = ((Color) data).asRGB(); break; case RECORD_PLAY: - Validate.isTrue(data == Material.AIR || ((Material) data).isRecord(), "Invalid record type!"); + Preconditions.checkArgument(data == Material.AIR || ((Material) data).isRecord(), "Invalid record type for Material %s!", data); datavalue = Item.getId(CraftMagicNumbers.getItem((Material) data)); break; case SMOKE: @@ -59,7 +59,7 @@ public class CraftEffect { } break; case STEP_SOUND: - Validate.isTrue(((Material) data).isBlock(), "Material is not a block!"); + Preconditions.checkArgument(((Material) data).isBlock(), "Material %s is not a block!", data); datavalue = Block.getId(CraftMagicNumbers.getBlock((Material) data).defaultBlockState()); break; case COMPOSTER_FILL_ATTEMPT: diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/CraftIpBanList.java b/paper-server/src/main/java/org/bukkit/craftbukkit/CraftIpBanList.java index c9c43fb9a7..d66e3c0caf 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/CraftIpBanList.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/CraftIpBanList.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit; +import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import java.io.IOException; import java.net.InetSocketAddress; @@ -9,7 +10,6 @@ import java.util.logging.Level; import net.minecraft.server.players.IpBanEntry; import net.minecraft.server.players.IpBanList; import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.Validate; import org.bukkit.Bukkit; public class CraftIpBanList implements org.bukkit.BanList { @@ -21,7 +21,7 @@ public class CraftIpBanList implements org.bukkit.BanList { @Override public org.bukkit.BanEntry getBanEntry(String target) { - Validate.notNull(target, "Target cannot be null"); + Preconditions.checkArgument(target != null, "Target cannot be null"); IpBanEntry entry = (IpBanEntry) list.get(target); if (entry == null) { @@ -33,7 +33,7 @@ public class CraftIpBanList implements org.bukkit.BanList { @Override public org.bukkit.BanEntry addBan(String target, String reason, Date expires, String source) { - Validate.notNull(target, "Ban target cannot be null"); + Preconditions.checkArgument(target != null, "Ban target cannot be null"); IpBanEntry entry = new IpBanEntry(target, new Date(), StringUtils.isBlank(source) ? null : source, expires, @@ -62,14 +62,14 @@ public class CraftIpBanList implements org.bukkit.BanList { @Override public boolean isBanned(String target) { - Validate.notNull(target, "Target cannot be null"); + Preconditions.checkArgument(target != null, "Target cannot be null"); return list.isBanned(InetSocketAddress.createUnresolved(target, 0)); } @Override public void pardon(String target) { - Validate.notNull(target, "Target cannot be null"); + Preconditions.checkArgument(target != null, "Target cannot be null"); list.remove(target); } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/CraftProfileBanList.java b/paper-server/src/main/java/org/bukkit/craftbukkit/CraftProfileBanList.java index 631281badc..8b88e0eb21 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/CraftProfileBanList.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/CraftProfileBanList.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit; +import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.mojang.authlib.GameProfile; import java.io.IOException; @@ -12,7 +13,6 @@ import net.minecraft.server.players.GameProfileBanEntry; import net.minecraft.server.players.GameProfileBanList; import net.minecraft.server.players.JsonListEntry; import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.Validate; import org.bukkit.Bukkit; public class CraftProfileBanList implements org.bukkit.BanList { @@ -24,7 +24,7 @@ public class CraftProfileBanList implements org.bukkit.BanList { @Override public org.bukkit.BanEntry getBanEntry(String target) { - Validate.notNull(target, "Target cannot be null"); + Preconditions.checkArgument(target != null, "Target cannot be null"); GameProfile profile = getProfile(target); if (profile == null) { @@ -41,7 +41,7 @@ public class CraftProfileBanList implements org.bukkit.BanList { @Override public org.bukkit.BanEntry addBan(String target, String reason, Date expires, String source) { - Validate.notNull(target, "Ban target cannot be null"); + Preconditions.checkArgument(target != null, "Ban target cannot be null"); GameProfile profile = getProfile(target); if (profile == null) { @@ -77,7 +77,7 @@ public class CraftProfileBanList implements org.bukkit.BanList { @Override public boolean isBanned(String target) { - Validate.notNull(target, "Target cannot be null"); + Preconditions.checkArgument(target != null, "Target cannot be null"); GameProfile profile = getProfile(target); if (profile == null) { @@ -89,7 +89,7 @@ public class CraftProfileBanList implements org.bukkit.BanList { @Override public void pardon(String target) { - Validate.notNull(target, "Target cannot be null"); + Preconditions.checkArgument(target != null, "Target cannot be null"); GameProfile profile = getProfile(target); list.remove(profile); diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/CraftRegionAccessor.java b/paper-server/src/main/java/org/bukkit/craftbukkit/CraftRegionAccessor.java index 94ab6418ad..e97c287a2e 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/CraftRegionAccessor.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/CraftRegionAccessor.java @@ -585,9 +585,8 @@ public abstract class CraftRegionAccessor implements RegionAccessor { @SuppressWarnings("unchecked") public net.minecraft.world.entity.Entity createEntity(Location location, Class clazz, boolean randomizeData) throws IllegalArgumentException { - if (location == null || clazz == null) { - throw new IllegalArgumentException("Location or entity class cannot be null"); - } + Preconditions.checkArgument(location != null, "Location cannot be null"); + Preconditions.checkArgument(clazz != null, "Entity class cannot be null"); net.minecraft.world.entity.Entity entity = null; net.minecraft.world.level.World world = getHandle().getMinecraftWorld(); @@ -798,11 +797,8 @@ public abstract class CraftRegionAccessor implements RegionAccessor { entity = EntityTypes.WITHER.create(world); } else if (ComplexLivingEntity.class.isAssignableFrom(clazz)) { if (EnderDragon.class.isAssignableFrom(clazz)) { - if (isNormalWorld()) { - entity = EntityTypes.ENDER_DRAGON.create(getHandle().getMinecraftWorld()); - } else { - throw new IllegalArgumentException("Cannot spawn entity " + clazz.getName() + " during world generation"); - } + Preconditions.checkArgument(this.isNormalWorld(), "Cannot spawn entity %s during world generation", clazz.getName()); + entity = EntityTypes.ENDER_DRAGON.create(getHandle().getMinecraftWorld()); } } else if (Ambient.class.isAssignableFrom(clazz)) { if (Bat.class.isAssignableFrom(clazz)) { diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/CraftServer.java b/paper-server/src/main/java/org/bukkit/craftbukkit/CraftServer.java index 8f12fd497b..a4f291994b 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/CraftServer.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/CraftServer.java @@ -117,7 +117,6 @@ import net.minecraft.world.level.storage.WorldNBTStorage; import net.minecraft.world.level.storage.loot.LootDataManager; import net.minecraft.world.level.validation.ContentValidationException; import net.minecraft.world.phys.Vec3D; -import org.apache.commons.lang.Validate; import org.bukkit.BanList; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -553,7 +552,7 @@ public final class CraftServer implements Server { @Override @Deprecated public Player getPlayer(final String name) { - Validate.notNull(name, "Name cannot be null"); + Preconditions.checkArgument(name != null, "name cannot be null"); Player found = getPlayerExact(name); // Try for an exact match first. @@ -579,7 +578,7 @@ public final class CraftServer implements Server { @Override @Deprecated public Player getPlayerExact(String name) { - Validate.notNull(name, "Name cannot be null"); + Preconditions.checkArgument(name != null, "name cannot be null"); EntityPlayer player = playerList.getPlayerByName(name); return (player != null) ? player.getBukkitEntity() : null; @@ -587,8 +586,9 @@ public final class CraftServer implements Server { @Override public Player getPlayer(UUID id) { - EntityPlayer player = playerList.getPlayer(id); + Preconditions.checkArgument(id != null, "UUID id cannot be null"); + EntityPlayer player = playerList.getPlayer(id); if (player != null) { return player.getBukkitEntity(); } @@ -604,9 +604,9 @@ public final class CraftServer implements Server { @Override @Deprecated public List matchPlayer(String partialName) { - Validate.notNull(partialName, "PartialName cannot be null"); + Preconditions.checkArgument(partialName != null, "partialName cannot be null"); - List matchedPlayers = new ArrayList(); + List matchedPlayers = new ArrayList<>(); for (Player iterPlayer : this.getOnlinePlayers()) { String iterPlayerName = iterPlayer.getName(); @@ -792,8 +792,8 @@ public final class CraftServer implements Server { @Override public int getTicksPerSpawns(SpawnCategory spawnCategory) { - Validate.notNull(spawnCategory, "SpawnCategory cannot be null"); - Validate.isTrue(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory." + spawnCategory + " are not supported."); + Preconditions.checkArgument(spawnCategory != null, "SpawnCategory cannot be null"); + Preconditions.checkArgument(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory.%s are not supported", spawnCategory); return this.configuration.getInt(CraftSpawnCategory.getConfigNameTicksPerSpawn(spawnCategory)); } @@ -844,8 +844,8 @@ public final class CraftServer implements Server { @Override public boolean dispatchCommand(CommandSender sender, String commandLine) { - Validate.notNull(sender, "Sender cannot be null"); - Validate.notNull(commandLine, "CommandLine cannot be null"); + Preconditions.checkArgument(sender != null, "sender cannot be null"); + Preconditions.checkArgument(commandLine != null, "commandLine cannot be null"); if (commandMap.dispatch(sender, commandLine)) { return true; @@ -1027,7 +1027,7 @@ public final class CraftServer implements Server { @Override public World createWorld(WorldCreator creator) { Preconditions.checkState(console.getAllLevels().iterator().hasNext(), "Cannot create additional worlds on STARTUP"); - Validate.notNull(creator, "Creator may not be null"); + Preconditions.checkArgument(creator != null, "WorldCreator cannot be null"); String name = creator.name(); ChunkGenerator generator = creator.generator(); @@ -1039,8 +1039,8 @@ public final class CraftServer implements Server { return world; } - if ((folder.exists()) && (!folder.isDirectory())) { - throw new IllegalArgumentException("File exists with the name '" + name + "' and isn't a folder"); + if (folder.exists()) { + Preconditions.checkArgument(folder.isDirectory(), "File (%s) exists and isn't a folder", name); } if (generator == null) { @@ -1063,7 +1063,7 @@ public final class CraftServer implements Server { actualDimension = WorldDimension.END; break; default: - throw new IllegalArgumentException("Illegal dimension"); + throw new IllegalArgumentException("Illegal dimension (" + creator.environment() + ")"); } Convertable.ConversionSession worldSession; @@ -1105,9 +1105,7 @@ public final class CraftServer implements Server { worlddata.setModdedInfo(console.getServerModName(), console.getModdedStatus().shouldReportAsModified()); if (console.options.has("forceUpgrade")) { - net.minecraft.server.Main.forceUpgrade(worldSession, DataConverterRegistry.getDataFixer(), console.options.has("eraseCache"), () -> { - return true; - }, iregistry); + net.minecraft.server.Main.forceUpgrade(worldSession, DataConverterRegistry.getDataFixer(), console.options.has("eraseCache"), () -> true, iregistry); } long j = BiomeManager.obfuscateSeed(creator.seed()); @@ -1203,7 +1201,8 @@ public final class CraftServer implements Server { @Override public World getWorld(String name) { - Validate.notNull(name, "Name cannot be null"); + Preconditions.checkArgument(name != null, "name cannot be null"); + Preconditions.checkArgument(!name.isBlank(), "name cannot be empty"); return worlds.get(name.toLowerCase(java.util.Locale.ENGLISH)); } @@ -1294,7 +1293,7 @@ public final class CraftServer implements Server { @Override public List getRecipesFor(ItemStack result) { - Validate.notNull(result, "Result cannot be null"); + Preconditions.checkArgument(result != null, "ItemStack cannot be null"); List results = new ArrayList(); Iterator iter = recipeIterator(); @@ -1313,7 +1312,7 @@ public final class CraftServer implements Server { @Override public Recipe getRecipe(NamespacedKey recipeKey) { - Preconditions.checkArgument(recipeKey != null, "recipeKey == null"); + Preconditions.checkArgument(recipeKey != null, "NamespacedKey recipeKey cannot be null"); return getServer().getRecipeManager().byKey(CraftNamespacedKey.toMinecraft(recipeKey)).map(IRecipe::toBukkitRecipe).orElse(null); } @@ -1344,8 +1343,8 @@ public final class CraftServer implements Server { @Override public ItemStack craftItem(ItemStack[] craftingMatrix, World world, Player player) { - Preconditions.checkArgument(world != null, "world must not be null"); - Preconditions.checkArgument(player != null, "player must not be null"); + Preconditions.checkArgument(world != null, "world cannot be null"); + Preconditions.checkArgument(player != null, "player cannot be null"); CraftWorld craftWorld = (CraftWorld) world; CraftPlayer craftPlayer = (CraftPlayer) player; @@ -1575,7 +1574,7 @@ public final class CraftServer implements Server { @Override public CraftMapView createMap(World world) { - Validate.notNull(world, "World cannot be null"); + Preconditions.checkArgument(world != null, "World cannot be null"); net.minecraft.world.level.World minecraftWorld = ((CraftWorld) world).getHandle(); // creates a new map at world spawn with the scale of 3, with out tracking position and unlimited tracking @@ -1590,9 +1589,9 @@ public final class CraftServer implements Server { @Override public ItemStack createExplorerMap(World world, Location location, StructureType structureType, int radius, boolean findUnexplored) { - Validate.notNull(world, "World cannot be null"); - Validate.notNull(structureType, "StructureType cannot be null"); - Validate.notNull(structureType.getMapIcon(), "Cannot create explorer maps for StructureType " + structureType.getName()); + Preconditions.checkArgument(world != null, "World cannot be null"); + Preconditions.checkArgument(structureType != null, "StructureType cannot be null"); + Preconditions.checkArgument(structureType.getMapIcon() != null, "Cannot create explorer maps for StructureType %s", structureType.getName()); WorldServer worldServer = ((CraftWorld) world).getHandle(); Location structureLocation = world.locateNearestStructure(location, structureType, radius, findUnexplored); @@ -1640,8 +1639,8 @@ public final class CraftServer implements Server { @Override @Deprecated public OfflinePlayer getOfflinePlayer(String name) { - Validate.notNull(name, "Name cannot be null"); - Validate.notEmpty(name, "Name cannot be empty"); + Preconditions.checkArgument(name != null, "name cannot be null"); + Preconditions.checkArgument(!name.isBlank(), "name cannot be empty"); OfflinePlayer result = getPlayerExact(name); if (result == null) { @@ -1663,7 +1662,7 @@ public final class CraftServer implements Server { @Override public OfflinePlayer getOfflinePlayer(UUID id) { - Validate.notNull(id, "UUID cannot be null"); + Preconditions.checkArgument(id != null, "UUID id cannot be null"); OfflinePlayer result = getPlayer(id); if (result == null) { @@ -1708,14 +1707,16 @@ public final class CraftServer implements Server { @Override public void banIP(String address) { - Validate.notNull(address, "Address cannot be null."); + Preconditions.checkArgument(address != null, "address cannot be null"); + Preconditions.checkArgument(!address.isBlank(), "address cannot be empty"); this.getBanList(org.bukkit.BanList.Type.IP).addBan(address, null, null, null); } @Override public void unbanIP(String address) { - Validate.notNull(address, "Address cannot be null."); + Preconditions.checkArgument(address != null, "address cannot be null"); + Preconditions.checkArgument(!address.isBlank(), "address cannot be empty"); this.getBanList(org.bukkit.BanList.Type.IP).pardon(address); } @@ -1733,7 +1734,7 @@ public final class CraftServer implements Server { @Override public BanList getBanList(BanList.Type type) { - Validate.notNull(type, "Type cannot be null"); + Preconditions.checkArgument(type != null, "BanList.Type cannot be null"); switch (type) { case IP: @@ -1794,7 +1795,7 @@ public final class CraftServer implements Server { @Override public void setDefaultGameMode(GameMode mode) { - Validate.notNull(mode, "Mode cannot be null"); + Preconditions.checkArgument(mode != null, "GameMode cannot be null"); for (World world : getWorlds()) { ((CraftWorld) world).getHandle().serverLevelData.setGameType(EnumGamemode.byId(mode.getValue())); @@ -1869,25 +1870,28 @@ public final class CraftServer implements Server { @Override public Inventory createInventory(InventoryHolder owner, InventoryType type) { - Validate.isTrue(type.isCreatable(), "Cannot open an inventory of type ", type); + Preconditions.checkArgument(type != null, "InventoryType cannot be null"); + Preconditions.checkArgument(type.isCreatable(), "InventoryType.%s cannot be used to create a inventory", type); return CraftInventoryCreator.INSTANCE.createInventory(owner, type); } @Override public Inventory createInventory(InventoryHolder owner, InventoryType type, String title) { - Validate.isTrue(type.isCreatable(), "Cannot open an inventory of type ", type); + Preconditions.checkArgument(type != null, "InventoryType cannot be null"); + Preconditions.checkArgument(type.isCreatable(), "InventoryType.%s cannot be used to create a inventory", type); + Preconditions.checkArgument(title != null, "title cannot be null"); return CraftInventoryCreator.INSTANCE.createInventory(owner, type, title); } @Override public Inventory createInventory(InventoryHolder owner, int size) throws IllegalArgumentException { - Validate.isTrue(9 <= size && size <= 54 && size % 9 == 0, "Size for custom inventory must be a multiple of 9 between 9 and 54 slots (got " + size + ")"); + Preconditions.checkArgument(9 <= size && size <= 54 && size % 9 == 0, "Size for custom inventory must be a multiple of 9 between 9 and 54 slots (got %s)", size); return CraftInventoryCreator.INSTANCE.createInventory(owner, size); } @Override public Inventory createInventory(InventoryHolder owner, int size, String title) throws IllegalArgumentException { - Validate.isTrue(9 <= size && size <= 54 && size % 9 == 0, "Size for custom inventory must be a multiple of 9 between 9 and 54 slots (got " + size + ")"); + Preconditions.checkArgument(9 <= size && size <= 54 && size % 9 == 0, "Size for custom inventory must be a multiple of 9 between 9 and 54 slots (got %s)", size); return CraftInventoryCreator.INSTANCE.createInventory(owner, size, title); } @@ -2063,10 +2067,8 @@ public final class CraftServer implements Server { @Override public CraftIconCache loadServerIcon(File file) throws Exception { - Validate.notNull(file, "File cannot be null"); - if (!file.isFile()) { - throw new IllegalArgumentException(file + " is not a file"); - } + Preconditions.checkArgument(file != null, "File cannot be null"); + Preconditions.checkArgument(file.isFile(), "File (%s) is not a valid file", file); return loadServerIcon0(file); } @@ -2076,13 +2078,13 @@ public final class CraftServer implements Server { @Override public CraftIconCache loadServerIcon(BufferedImage image) throws Exception { - Validate.notNull(image, "Image cannot be null"); + Preconditions.checkArgument(image != null, "BufferedImage image cannot be null"); return loadServerIcon0(image); } static CraftIconCache loadServerIcon0(BufferedImage image) throws Exception { - Validate.isTrue(image.getWidth() == 64, "Must be 64 pixels wide"); - Validate.isTrue(image.getHeight() == 64, "Must be 64 pixels high"); + Preconditions.checkArgument(image.getWidth() == 64, "BufferedImage must be 64 pixels wide (%s)", image.getWidth()); + Preconditions.checkArgument(image.getHeight() == 64, "BufferedImage must be 64 pixels high (%s)", image.getHeight()); ByteArrayOutputStream bytebuf = new ByteArrayOutputStream(); ImageIO.write(image, "PNG", bytebuf); @@ -2102,7 +2104,7 @@ public final class CraftServer implements Server { @Override public ChunkGenerator.ChunkData createChunkData(World world) { - Validate.notNull(world, "World cannot be null"); + Preconditions.checkArgument(world != null, "World cannot be null"); WorldServer handle = ((CraftWorld) world).getHandle(); return new OldCraftChunkData(world.getMinHeight(), world.getMaxHeight(), handle.registryAccess().registryOrThrow(Registries.BIOME)); } @@ -2114,13 +2116,18 @@ public final class CraftServer implements Server { @Override public KeyedBossBar createBossBar(NamespacedKey key, String title, BarColor barColor, BarStyle barStyle, BarFlag... barFlags) { - Preconditions.checkArgument(key != null, "key"); + Preconditions.checkArgument(key != null, "NamespacedKey key cannot be null"); + Preconditions.checkArgument(barColor != null, "BarColor key cannot be null"); + Preconditions.checkArgument(barStyle != null, "BarStyle key cannot be null"); BossBattleCustom bossBattleCustom = getServer().getCustomBossEvents().create(CraftNamespacedKey.toMinecraft(key), CraftChatMessage.fromString(title, true)[0]); CraftKeyedBossbar craftKeyedBossbar = new CraftKeyedBossbar(bossBattleCustom); craftKeyedBossbar.setColor(barColor); craftKeyedBossbar.setStyle(barStyle); for (BarFlag flag : barFlags) { + if (flag == null) { + continue; + } craftKeyedBossbar.addFlag(flag); } @@ -2161,7 +2168,7 @@ public final class CraftServer implements Server { @Override public Entity getEntity(UUID uuid) { - Validate.notNull(uuid, "UUID cannot be null"); + Preconditions.checkArgument(uuid != null, "UUID id cannot be null"); for (WorldServer world : getServer().getAllLevels()) { net.minecraft.world.entity.Entity entity = world.getEntity(uuid); @@ -2175,7 +2182,7 @@ public final class CraftServer implements Server { @Override public org.bukkit.advancement.Advancement getAdvancement(NamespacedKey key) { - Preconditions.checkArgument(key != null, "key"); + Preconditions.checkArgument(key != null, "NamespacedKey key cannot be null"); Advancement advancement = console.getAdvancements().getAdvancement(CraftNamespacedKey.toMinecraft(key)); return (advancement == null) ? null : advancement.bukkit; @@ -2193,7 +2200,7 @@ public final class CraftServer implements Server { @Override public BlockData createBlockData(org.bukkit.Material material) { - Validate.isTrue(material != null, "Must provide material"); + Preconditions.checkArgument(material != null, "Material cannot be null"); return createBlockData(material, (String) null); } @@ -2211,14 +2218,14 @@ public final class CraftServer implements Server { @Override public BlockData createBlockData(String data) throws IllegalArgumentException { - Validate.isTrue(data != null, "Must provide data"); + Preconditions.checkArgument(data != null, "data cannot be null"); return createBlockData(null, data); } @Override public BlockData createBlockData(org.bukkit.Material material, String data) { - Validate.isTrue(material != null || data != null, "Must provide one of material or data"); + Preconditions.checkArgument(material != null, "Material cannot be null"); return CraftBlockData.newData(material, data); } @@ -2226,35 +2233,35 @@ public final class CraftServer implements Server { @Override @SuppressWarnings("unchecked") public org.bukkit.Tag getTag(String registry, NamespacedKey tag, Class clazz) { - Validate.notNull(registry, "registry cannot be null"); - Validate.notNull(tag, "NamespacedKey cannot be null"); - Validate.notNull(clazz, "Class cannot be null"); + Preconditions.checkArgument(registry != null, "registry cannot be null"); + Preconditions.checkArgument(tag != null, "NamespacedKey tag cannot be null"); + Preconditions.checkArgument(clazz != null, "Class clazz cannot be null"); MinecraftKey key = CraftNamespacedKey.toMinecraft(tag); switch (registry) { case org.bukkit.Tag.REGISTRY_BLOCKS -> { - Preconditions.checkArgument(clazz == org.bukkit.Material.class, "Block namespace must have material type"); + Preconditions.checkArgument(clazz == org.bukkit.Material.class, "Block namespace (%s) must have material type", clazz.getName()); TagKey blockTagKey = TagKey.create(Registries.BLOCK, key); if (BuiltInRegistries.BLOCK.getTag(blockTagKey).isPresent()) { return (org.bukkit.Tag) new CraftBlockTag(BuiltInRegistries.BLOCK, blockTagKey); } } case org.bukkit.Tag.REGISTRY_ITEMS -> { - Preconditions.checkArgument(clazz == org.bukkit.Material.class, "Item namespace must have material type"); + Preconditions.checkArgument(clazz == org.bukkit.Material.class, "Item namespace (%s) must have material type", clazz.getName()); TagKey itemTagKey = TagKey.create(Registries.ITEM, key); if (BuiltInRegistries.ITEM.getTag(itemTagKey).isPresent()) { return (org.bukkit.Tag) new CraftItemTag(BuiltInRegistries.ITEM, itemTagKey); } } case org.bukkit.Tag.REGISTRY_FLUIDS -> { - Preconditions.checkArgument(clazz == org.bukkit.Fluid.class, "Fluid namespace must have fluid type"); + Preconditions.checkArgument(clazz == org.bukkit.Fluid.class, "Fluid namespace (%s) must have fluid type", clazz.getName()); TagKey fluidTagKey = TagKey.create(Registries.FLUID, key); if (BuiltInRegistries.FLUID.getTag(fluidTagKey).isPresent()) { return (org.bukkit.Tag) new CraftFluidTag(BuiltInRegistries.FLUID, fluidTagKey); } } case org.bukkit.Tag.REGISTRY_ENTITY_TYPES -> { - Preconditions.checkArgument(clazz == org.bukkit.entity.EntityType.class, "Entity type namespace must have entity type"); + Preconditions.checkArgument(clazz == org.bukkit.entity.EntityType.class, "Entity type namespace (%s) must have entity type", clazz.getName()); TagKey> entityTagKey = TagKey.create(Registries.ENTITY_TYPE, key); if (BuiltInRegistries.ENTITY_TYPE.getTag(entityTagKey).isPresent()) { return (org.bukkit.Tag) new CraftEntityTag(BuiltInRegistries.ENTITY_TYPE, entityTagKey); @@ -2269,26 +2276,26 @@ public final class CraftServer implements Server { @Override @SuppressWarnings("unchecked") public Iterable> getTags(String registry, Class clazz) { - Validate.notNull(registry, "registry cannot be null"); - Validate.notNull(clazz, "Class cannot be null"); + Preconditions.checkArgument(registry != null, "registry cannot be null"); + Preconditions.checkArgument(clazz != null, "Class clazz cannot be null"); switch (registry) { case org.bukkit.Tag.REGISTRY_BLOCKS -> { - Preconditions.checkArgument(clazz == org.bukkit.Material.class, "Block namespace must have material type"); + Preconditions.checkArgument(clazz == org.bukkit.Material.class, "Block namespace (%s) must have material type", clazz.getName()); IRegistry blockTags = BuiltInRegistries.BLOCK; return blockTags.getTags().map(pair -> (org.bukkit.Tag) new CraftBlockTag(blockTags, pair.getFirst())).collect(ImmutableList.toImmutableList()); } case org.bukkit.Tag.REGISTRY_ITEMS -> { - Preconditions.checkArgument(clazz == org.bukkit.Material.class, "Item namespace must have material type"); + Preconditions.checkArgument(clazz == org.bukkit.Material.class, "Item namespace (%s) must have material type", clazz.getName()); IRegistry itemTags = BuiltInRegistries.ITEM; return itemTags.getTags().map(pair -> (org.bukkit.Tag) new CraftItemTag(itemTags, pair.getFirst())).collect(ImmutableList.toImmutableList()); } case org.bukkit.Tag.REGISTRY_FLUIDS -> { - Preconditions.checkArgument(clazz == org.bukkit.Material.class, "Fluid namespace must have fluid type"); + Preconditions.checkArgument(clazz == org.bukkit.Material.class, "Fluid namespace (%s) must have fluid type", clazz.getName()); IRegistry fluidTags = BuiltInRegistries.FLUID; return fluidTags.getTags().map(pair -> (org.bukkit.Tag) new CraftFluidTag(fluidTags, pair.getFirst())).collect(ImmutableList.toImmutableList()); } case org.bukkit.Tag.REGISTRY_ENTITY_TYPES -> { - Preconditions.checkArgument(clazz == org.bukkit.entity.EntityType.class, "Entity type namespace must have entity type"); + Preconditions.checkArgument(clazz == org.bukkit.entity.EntityType.class, "Entity type namespace (%s) must have entity type", clazz.getName()); IRegistry> entityTags = BuiltInRegistries.ENTITY_TYPE; return entityTags.getTags().map(pair -> (org.bukkit.Tag) new CraftEntityTag(entityTags, pair.getFirst())).collect(ImmutableList.toImmutableList()); } @@ -2298,7 +2305,7 @@ public final class CraftServer implements Server { @Override public LootTable getLootTable(NamespacedKey key) { - Validate.notNull(key, "NamespacedKey cannot be null"); + Preconditions.checkArgument(key != null, "NamespacedKey key cannot be null"); LootDataManager registry = getServer().getLootData(); return new CraftLootTable(key, registry.getLootTable(CraftNamespacedKey.toMinecraft(key))); @@ -2306,8 +2313,8 @@ public final class CraftServer implements Server { @Override public List selectEntities(CommandSender sender, String selector) { - Preconditions.checkArgument(selector != null, "Selector cannot be null"); - Preconditions.checkArgument(sender != null, "Sender cannot be null"); + Preconditions.checkArgument(selector != null, "selector cannot be null"); + Preconditions.checkArgument(sender != null, "CommandSender sender cannot be null"); ArgumentEntity arg = ArgumentEntity.entities(); List nms; @@ -2315,7 +2322,7 @@ public final class CraftServer implements Server { try { StringReader reader = new StringReader(selector); nms = arg.parse(reader, true).findEntities(VanillaCommandWrapper.getListener(sender)); - Preconditions.checkArgument(!reader.canRead(), "Spurious trailing data in selector: " + selector); + Preconditions.checkArgument(!reader.canRead(), "Spurious trailing data in selector: %s", selector); } catch (CommandSyntaxException ex) { throw new IllegalArgumentException("Could not parse selector: " + selector, ex); } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/CraftStatistic.java b/paper-server/src/main/java/org/bukkit/craftbukkit/CraftStatistic.java index f409a3f278..f3ed30a722 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/CraftStatistic.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/CraftStatistic.java @@ -11,7 +11,6 @@ import net.minecraft.stats.StatisticList; import net.minecraft.world.entity.EntityTypes; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; -import org.apache.commons.lang.Validate; import org.bukkit.Material; import org.bukkit.Statistic; import org.bukkit.Statistic.Type; @@ -123,6 +122,7 @@ public enum CraftStatistic { } public static org.bukkit.Statistic getBukkitStatistic(net.minecraft.stats.Statistic statistic) { + Preconditions.checkArgument(statistic != null, "NMS Statistic cannot be null"); IRegistry statRegistry = statistic.getType().getRegistry(); MinecraftKey nmsKey = BuiltInRegistries.STAT_TYPE.getKey(statistic.getType()); @@ -169,6 +169,7 @@ public enum CraftStatistic { } public static net.minecraft.stats.Statistic getEntityStatistic(org.bukkit.Statistic stat, EntityType entity) { + Preconditions.checkArgument(entity != null, "EntityType cannot be null"); if (entity.getName() != null) { EntityTypes nmsEntity = BuiltInRegistries.ENTITY_TYPE.get(new MinecraftKey(entity.getName())); @@ -183,16 +184,17 @@ public enum CraftStatistic { } public static EntityType getEntityTypeFromStatistic(net.minecraft.stats.Statistic> statistic) { + Preconditions.checkArgument(statistic != null, "NMS Statistic cannot be null"); MinecraftKey name = EntityTypes.getKey(statistic.getValue()); return EntityType.fromName(name.getPath()); } public static Material getMaterialFromStatistic(net.minecraft.stats.Statistic statistic) { - if (statistic.getValue() instanceof Item) { - return CraftMagicNumbers.getMaterial((Item) statistic.getValue()); + if (statistic.getValue() instanceof Item statisticItemValue) { + return CraftMagicNumbers.getMaterial(statisticItemValue); } - if (statistic.getValue() instanceof Block) { - return CraftMagicNumbers.getMaterial((Block) statistic.getValue()); + if (statistic.getValue() instanceof Block statisticBlockValue) { + return CraftMagicNumbers.getMaterial(statisticBlockValue); } return null; } @@ -206,25 +208,25 @@ public enum CraftStatistic { } public static int getStatistic(ServerStatisticManager manager, Statistic statistic) { - Validate.notNull(statistic, "Statistic cannot be null"); - Validate.isTrue(statistic.getType() == Type.UNTYPED, "Must supply additional paramater for this statistic"); + Preconditions.checkArgument(statistic != null, "Statistic cannot be null"); + Preconditions.checkArgument(statistic.getType() == Type.UNTYPED, "Must supply additional parameter for this statistic"); return manager.getValue(CraftStatistic.getNMSStatistic(statistic)); } public static void incrementStatistic(ServerStatisticManager manager, Statistic statistic, int amount) { - Validate.isTrue(amount > 0, "Amount must be greater than 0"); + Preconditions.checkArgument(amount > 0, "Amount must be greater than 0"); setStatistic(manager, statistic, getStatistic(manager, statistic) + amount); } public static void decrementStatistic(ServerStatisticManager manager, Statistic statistic, int amount) { - Validate.isTrue(amount > 0, "Amount must be greater than 0"); + Preconditions.checkArgument(amount > 0, "Amount must be greater than 0"); setStatistic(manager, statistic, getStatistic(manager, statistic) - amount); } public static void setStatistic(ServerStatisticManager manager, Statistic statistic, int newValue) { - Validate.notNull(statistic, "Statistic cannot be null"); - Validate.isTrue(statistic.getType() == Type.UNTYPED, "Must supply additional paramater for this statistic"); - Validate.isTrue(newValue >= 0, "Value must be greater than or equal to 0"); + Preconditions.checkArgument(statistic != null, "Statistic cannot be null"); + Preconditions.checkArgument(statistic.getType() == Type.UNTYPED, "Must supply additional parameter for this statistic"); + Preconditions.checkArgument(newValue >= 0, "Value must be greater than or equal to 0"); net.minecraft.stats.Statistic nmsStatistic = CraftStatistic.getNMSStatistic(statistic); manager.setValue(null, nmsStatistic, newValue);; } @@ -238,31 +240,31 @@ public enum CraftStatistic { } public static int getStatistic(ServerStatisticManager manager, Statistic statistic, Material material) { - Validate.notNull(statistic, "Statistic cannot be null"); - Validate.notNull(material, "Material cannot be null"); - Validate.isTrue(statistic.getType() == Type.BLOCK || statistic.getType() == Type.ITEM, "This statistic does not take a Material parameter"); + Preconditions.checkArgument(statistic != null, "Statistic cannot be null"); + Preconditions.checkArgument(material != null, "Material cannot be null"); + Preconditions.checkArgument(statistic.getType() == Type.BLOCK || statistic.getType() == Type.ITEM, "This statistic does not take a Material parameter"); net.minecraft.stats.Statistic nmsStatistic = CraftStatistic.getMaterialStatistic(statistic, material); - Validate.notNull(nmsStatistic, "The supplied Material does not have a corresponding statistic"); + Preconditions.checkArgument(nmsStatistic != null, "The supplied Material %s does not have a corresponding statistic", material); return manager.getValue(nmsStatistic); } public static void incrementStatistic(ServerStatisticManager manager, Statistic statistic, Material material, int amount) { - Validate.isTrue(amount > 0, "Amount must be greater than 0"); + Preconditions.checkArgument(amount > 0, "Amount must be greater than 0"); setStatistic(manager, statistic, material, getStatistic(manager, statistic, material) + amount); } public static void decrementStatistic(ServerStatisticManager manager, Statistic statistic, Material material, int amount) { - Validate.isTrue(amount > 0, "Amount must be greater than 0"); + Preconditions.checkArgument(amount > 0, "Amount must be greater than 0"); setStatistic(manager, statistic, material, getStatistic(manager, statistic, material) - amount); } public static void setStatistic(ServerStatisticManager manager, Statistic statistic, Material material, int newValue) { - Validate.notNull(statistic, "Statistic cannot be null"); - Validate.notNull(material, "Material cannot be null"); - Validate.isTrue(newValue >= 0, "Value must be greater than or equal to 0"); - Validate.isTrue(statistic.getType() == Type.BLOCK || statistic.getType() == Type.ITEM, "This statistic does not take a Material parameter"); + Preconditions.checkArgument(statistic != null, "Statistic cannot be null"); + Preconditions.checkArgument(material != null, "Material cannot be null"); + Preconditions.checkArgument(newValue >= 0, "Value must be greater than or equal to 0"); + Preconditions.checkArgument(statistic.getType() == Type.BLOCK || statistic.getType() == Type.ITEM, "This statistic does not take a Material parameter"); net.minecraft.stats.Statistic nmsStatistic = CraftStatistic.getMaterialStatistic(statistic, material); - Validate.notNull(nmsStatistic, "The supplied Material does not have a corresponding statistic"); + Preconditions.checkArgument(nmsStatistic != null, "The supplied Material %s does not have a corresponding statistic", material); manager.setValue(null, nmsStatistic, newValue); } @@ -275,31 +277,31 @@ public enum CraftStatistic { } public static int getStatistic(ServerStatisticManager manager, Statistic statistic, EntityType entityType) { - Validate.notNull(statistic, "Statistic cannot be null"); - Validate.notNull(entityType, "EntityType cannot be null"); - Validate.isTrue(statistic.getType() == Type.ENTITY, "This statistic does not take an EntityType parameter"); + Preconditions.checkArgument(statistic != null, "Statistic cannot be null"); + Preconditions.checkArgument(entityType != null, "EntityType cannot be null"); + Preconditions.checkArgument(statistic.getType() == Type.ENTITY, "This statistic does not take an EntityType parameter"); net.minecraft.stats.Statistic nmsStatistic = CraftStatistic.getEntityStatistic(statistic, entityType); - Validate.notNull(nmsStatistic, "The supplied EntityType does not have a corresponding statistic"); + Preconditions.checkArgument(nmsStatistic != null, "The supplied EntityType %s does not have a corresponding statistic", entityType); return manager.getValue(nmsStatistic); } public static void incrementStatistic(ServerStatisticManager manager, Statistic statistic, EntityType entityType, int amount) { - Validate.isTrue(amount > 0, "Amount must be greater than 0"); + Preconditions.checkArgument(amount > 0, "Amount must be greater than 0"); setStatistic(manager, statistic, entityType, getStatistic(manager, statistic, entityType) + amount); } public static void decrementStatistic(ServerStatisticManager manager, Statistic statistic, EntityType entityType, int amount) { - Validate.isTrue(amount > 0, "Amount must be greater than 0"); + Preconditions.checkArgument(amount > 0, "Amount must be greater than 0"); setStatistic(manager, statistic, entityType, getStatistic(manager, statistic, entityType) - amount); } public static void setStatistic(ServerStatisticManager manager, Statistic statistic, EntityType entityType, int newValue) { - Validate.notNull(statistic, "Statistic cannot be null"); - Validate.notNull(entityType, "EntityType cannot be null"); - Validate.isTrue(newValue >= 0, "Value must be greater than or equal to 0"); - Validate.isTrue(statistic.getType() == Type.ENTITY, "This statistic does not take an EntityType parameter"); + Preconditions.checkArgument(statistic != null, "Statistic cannot be null"); + Preconditions.checkArgument(entityType != null, "EntityType cannot be null"); + Preconditions.checkArgument(newValue >= 0, "Value must be greater than or equal to 0"); + Preconditions.checkArgument(statistic.getType() == Type.ENTITY, "This statistic does not take an EntityType parameter"); net.minecraft.stats.Statistic nmsStatistic = CraftStatistic.getEntityStatistic(statistic, entityType); - Validate.notNull(nmsStatistic, "The supplied EntityType does not have a corresponding statistic"); + Preconditions.checkArgument(nmsStatistic != null, "The supplied EntityType %s does not have a corresponding statistic", entityType); manager.setValue(null, nmsStatistic, newValue); } } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/CraftWorld.java b/paper-server/src/main/java/org/bukkit/craftbukkit/CraftWorld.java index 4daf60ecef..6f724ac7ae 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/CraftWorld.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/CraftWorld.java @@ -67,7 +67,6 @@ import net.minecraft.world.level.storage.SavedFile; import net.minecraft.world.phys.AxisAlignedBB; import net.minecraft.world.phys.MovingObjectPosition; import net.minecraft.world.phys.Vec3D; -import org.apache.commons.lang.Validate; import org.bukkit.BlockChangeDelegate; import org.bukkit.Bukkit; import org.bukkit.Chunk; @@ -486,14 +485,17 @@ public class CraftWorld extends CraftRegionAccessor implements World { @Override public org.bukkit.entity.Item dropItem(Location loc, ItemStack item, Consumer function) { - Validate.notNull(item, "Cannot drop a Null item."); + Preconditions.checkArgument(loc != null, "Location cannot be null"); + Preconditions.checkArgument(item != null, "ItemStack cannot be null"); + EntityItem entity = new EntityItem(world, loc.getX(), loc.getY(), loc.getZ(), CraftItemStack.asNMSCopy(item)); + org.bukkit.entity.Item itemEntity = (org.bukkit.entity.Item) entity.getBukkitEntity(); entity.pickupDelay = 10; if (function != null) { - function.accept((org.bukkit.entity.Item) entity.getBukkitEntity()); + function.accept(itemEntity); } world.addFreshEntity(entity, SpawnReason.CUSTOM); - return (org.bukkit.entity.Item) entity.getBukkitEntity(); + return itemEntity; } @Override @@ -503,13 +505,13 @@ public class CraftWorld extends CraftRegionAccessor implements World { @Override public org.bukkit.entity.Item dropItemNaturally(Location loc, ItemStack item, Consumer function) { + Preconditions.checkArgument(loc != null, "Location cannot be null"); + Preconditions.checkArgument(item != null, "ItemStack cannot be null"); + double xs = (world.random.nextFloat() * 0.5F) + 0.25D; double ys = (world.random.nextFloat() * 0.5F) + 0.25D; double zs = (world.random.nextFloat() * 0.5F) + 0.25D; - loc = loc.clone(); - loc.setX(loc.getX() + xs); - loc.setY(loc.getY() + ys); - loc.setZ(loc.getZ() + zs); + loc = loc.clone().add(xs, ys, zs); return dropItem(loc, item, function); } @@ -520,9 +522,9 @@ public class CraftWorld extends CraftRegionAccessor implements World { @Override public T spawnArrow(Location loc, Vector velocity, float speed, float spread, Class clazz) { - Validate.notNull(loc, "Can not spawn arrow with a null location"); - Validate.notNull(velocity, "Can not spawn arrow with a null velocity"); - Validate.notNull(clazz, "Can not spawn an arrow with no class"); + Preconditions.checkArgument(loc != null, "Location cannot be null"); + Preconditions.checkArgument(velocity != null, "Vector cannot be null"); + Preconditions.checkArgument(clazz != null, "clazz Entity for the arrow cannot be null"); EntityArrow arrow; if (TippedArrow.class.isAssignableFrom(clazz)) { @@ -544,17 +546,20 @@ public class CraftWorld extends CraftRegionAccessor implements World { @Override public LightningStrike strikeLightning(Location loc) { - EntityLightning lightning = EntityTypes.LIGHTNING_BOLT.create(world); - lightning.moveTo(loc.getX(), loc.getY(), loc.getZ()); - world.strikeLightning(lightning, LightningStrikeEvent.Cause.CUSTOM); - return (LightningStrike) lightning.getBukkitEntity(); + return strikeLightning0(loc, false); } @Override public LightningStrike strikeLightningEffect(Location loc) { + return strikeLightning0(loc, true); + } + + private LightningStrike strikeLightning0(Location loc, boolean isVisual) { + Preconditions.checkArgument(loc != null, "Location cannot be null"); + EntityLightning lightning = EntityTypes.LIGHTNING_BOLT.create(world); lightning.moveTo(loc.getX(), loc.getY(), loc.getZ()); - lightning.setVisualOnly(true); + lightning.setVisualOnly(isVisual); world.strikeLightning(lightning, LightningStrikeEvent.Cause.CUSTOM); return (LightningStrike) lightning.getBukkitEntity(); } @@ -822,8 +827,8 @@ public class CraftWorld extends CraftRegionAccessor implements World { @Override public Collection getNearbyEntities(Location location, double x, double y, double z, Predicate filter) { - Validate.notNull(location, "Location is null!"); - Validate.isTrue(this.equals(location.getWorld()), "Location is from different world!"); + Preconditions.checkArgument(location != null, "Location cannot be null"); + Preconditions.checkArgument(this.equals(location.getWorld()), "Location cannot be in a different world"); BoundingBox aabb = BoundingBox.of(location, x, y, z); return this.getNearbyEntities(aabb, filter); @@ -836,7 +841,7 @@ public class CraftWorld extends CraftRegionAccessor implements World { @Override public Collection getNearbyEntities(BoundingBox boundingBox, Predicate filter) { - Validate.notNull(boundingBox, "Bounding box is null!"); + Preconditions.checkArgument(boundingBox != null, "BoundingBox cannot be null"); AxisAlignedBB bb = new AxisAlignedBB(boundingBox.getMinX(), boundingBox.getMinY(), boundingBox.getMinZ(), boundingBox.getMaxX(), boundingBox.getMaxY(), boundingBox.getMaxZ()); List entityList = getHandle().getEntities((net.minecraft.world.entity.Entity) null, bb, Predicates.alwaysTrue()); @@ -869,14 +874,14 @@ public class CraftWorld extends CraftRegionAccessor implements World { @Override public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, double raySize, Predicate filter) { - Validate.notNull(start, "Start location is null!"); - Validate.isTrue(this.equals(start.getWorld()), "Start location is from different world!"); + Preconditions.checkArgument(start != null, "Location start cannot be null"); + Preconditions.checkArgument(this.equals(start.getWorld()), "Location start cannot be in a different world"); start.checkFinite(); - Validate.notNull(direction, "Direction is null!"); + Preconditions.checkArgument(direction != null, "Vector direction cannot be null"); direction.checkFinite(); - Validate.isTrue(direction.lengthSquared() > 0, "Direction's magnitude is 0!"); + Preconditions.checkArgument(direction.lengthSquared() > 0, "Direction's magnitude (%s) need to be greater than 0", direction.lengthSquared()); if (maxDistance < 0.0D) { return null; @@ -921,15 +926,15 @@ public class CraftWorld extends CraftRegionAccessor implements World { @Override public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode, boolean ignorePassableBlocks) { - Validate.notNull(start, "Start location is null!"); - Validate.isTrue(this.equals(start.getWorld()), "Start location is from different world!"); + Preconditions.checkArgument(start != null, "Location start cannot be null"); + Preconditions.checkArgument(this.equals(start.getWorld()), "Location start cannot be in a different world"); start.checkFinite(); - Validate.notNull(direction, "Direction is null!"); + Preconditions.checkArgument(direction != null, "Vector direction cannot be null"); direction.checkFinite(); - Validate.isTrue(direction.lengthSquared() > 0, "Direction's magnitude is 0!"); - Validate.notNull(fluidCollisionMode, "Fluid collision mode is null!"); + Preconditions.checkArgument(direction.lengthSquared() > 0, "Direction's magnitude (%s) need to be greater than 0", direction.lengthSquared()); + Preconditions.checkArgument(fluidCollisionMode != null, "FluidCollisionMode cannot be null"); if (maxDistance < 0.0D) { return null; @@ -1114,10 +1119,11 @@ public class CraftWorld extends CraftRegionAccessor implements World { @Override public void playEffect(Location loc, Effect effect, T data, int radius) { if (data != null) { - Validate.isTrue(effect.getData() != null && effect.getData().isAssignableFrom(data.getClass()), "Wrong kind of data for this effect!"); + Preconditions.checkArgument(effect.getData() != null, "Effect.%s does not have a valid Data", effect); + Preconditions.checkArgument(effect.getData().isAssignableFrom(data.getClass()), "%s data cannot be used for the %s effect", data.getClass().getName(), effect); } else { // Special case: the axis is optional for ELECTRIC_SPARK - Validate.isTrue(effect.getData() == null || effect == Effect.ELECTRIC_SPARK, "Wrong kind of data for this effect!"); + Preconditions.checkArgument(effect.getData() == null || effect == Effect.ELECTRIC_SPARK, "Wrong kind of data for the %s effect", effect); } int datavalue = CraftEffect.getDataValue(effect, data); @@ -1126,9 +1132,9 @@ public class CraftWorld extends CraftRegionAccessor implements World { @Override public void playEffect(Location location, Effect effect, int data, int radius) { - Validate.notNull(location, "Location cannot be null"); - Validate.notNull(effect, "Effect cannot be null"); - Validate.notNull(location.getWorld(), "World cannot be null"); + Preconditions.checkArgument(effect != null, "Effect cannot be null"); + Preconditions.checkArgument(location != null, "Location cannot be null"); + Preconditions.checkArgument(location.getWorld() != null, "World of Location cannot be null"); int packetData = effect.getId(); PacketPlayOutWorldEvent packet = new PacketPlayOutWorldEvent(packetData, CraftLocation.toBlockPosition(location), data, false); int distance; @@ -1147,15 +1153,15 @@ public class CraftWorld extends CraftRegionAccessor implements World { @Override public FallingBlock spawnFallingBlock(Location location, MaterialData data) throws IllegalArgumentException { - Validate.notNull(data, "MaterialData cannot be null"); + Preconditions.checkArgument(data != null, "MaterialData cannot be null"); return spawnFallingBlock(location, data.getItemType(), data.getData()); } @Override public FallingBlock spawnFallingBlock(Location location, org.bukkit.Material material, byte data) throws IllegalArgumentException { - Validate.notNull(location, "Location cannot be null"); - Validate.notNull(material, "Material cannot be null"); - Validate.isTrue(material.isBlock(), "Material must be a block"); + Preconditions.checkArgument(location != null, "Location cannot be null"); + Preconditions.checkArgument(material != null, "Material cannot be null"); + Preconditions.checkArgument(material.isBlock(), "Material.%s must be a block", material); EntityFallingBlock entity = EntityFallingBlock.fall(world, BlockPosition.containing(location.getX(), location.getY(), location.getZ()), CraftMagicNumbers.getBlock(material).defaultBlockState(), SpawnReason.CUSTOM); return (FallingBlock) entity.getBukkitEntity(); @@ -1163,8 +1169,8 @@ public class CraftWorld extends CraftRegionAccessor implements World { @Override public FallingBlock spawnFallingBlock(Location location, BlockData data) throws IllegalArgumentException { - Validate.notNull(location, "Location cannot be null"); - Validate.notNull(data, "BlockData cannot be null"); + Preconditions.checkArgument(location != null, "Location cannot be null"); + Preconditions.checkArgument(data != null, "BlockData cannot be null"); EntityFallingBlock entity = EntityFallingBlock.fall(world, BlockPosition.containing(location.getX(), location.getY(), location.getZ()), ((CraftBlockData) data).getState(), SpawnReason.CUSTOM); return (FallingBlock) entity.getBukkitEntity(); @@ -1406,16 +1412,16 @@ public class CraftWorld extends CraftRegionAccessor implements World { @Override public void setTicksPerSpawns(SpawnCategory spawnCategory, int ticksPerCategorySpawn) { - Validate.notNull(spawnCategory, "SpawnCategory cannot be null"); - Validate.isTrue(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory." + spawnCategory + " are not supported."); + Preconditions.checkArgument(spawnCategory != null, "SpawnCategory cannot be null"); + Preconditions.checkArgument(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory.%s are not supported", spawnCategory); world.ticksPerSpawnCategory.put(spawnCategory, (long) ticksPerCategorySpawn); } @Override public long getTicksPerSpawns(SpawnCategory spawnCategory) { - Validate.notNull(spawnCategory, "SpawnCategory cannot be null"); - Validate.isTrue(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory." + spawnCategory + " are not supported."); + Preconditions.checkArgument(spawnCategory != null, "SpawnCategory cannot be null"); + Preconditions.checkArgument(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory.%s are not supported", spawnCategory); return world.ticksPerSpawnCategory.getLong(spawnCategory); } @@ -1514,8 +1520,8 @@ public class CraftWorld extends CraftRegionAccessor implements World { @Override public int getSpawnLimit(SpawnCategory spawnCategory) { - Validate.notNull(spawnCategory, "SpawnCategory cannot be null"); - Validate.isTrue(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory." + spawnCategory + " are not supported."); + Preconditions.checkArgument(spawnCategory != null, "SpawnCategory cannot be null"); + Preconditions.checkArgument(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory.%s are not supported", spawnCategory); int limit = spawnCategoryLimit.getOrDefault(spawnCategory, -1); if (limit < 0) { @@ -1526,8 +1532,8 @@ public class CraftWorld extends CraftRegionAccessor implements World { @Override public void setSpawnLimit(SpawnCategory spawnCategory, int limit) { - Validate.notNull(spawnCategory, "SpawnCategory cannot be null"); - Validate.isTrue(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory." + spawnCategory + " are not supported."); + Preconditions.checkArgument(spawnCategory != null, "SpawnCategory cannot be null"); + Preconditions.checkArgument(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory.%s are not supported", spawnCategory); spawnCategoryLimit.put(spawnCategory, limit); } @@ -1544,7 +1550,9 @@ public class CraftWorld extends CraftRegionAccessor implements World { @Override public void playSound(Location loc, Sound sound, org.bukkit.SoundCategory category, float volume, float pitch) { - if (loc == null || sound == null || category == null) return; + Preconditions.checkArgument(loc != null, "Location cannot be null"); + Preconditions.checkArgument(sound != null, "Sound cannot be null"); + Preconditions.checkArgument(category != null, "Category cannot be null"); double x = loc.getX(); double y = loc.getY(); @@ -1555,7 +1563,10 @@ public class CraftWorld extends CraftRegionAccessor implements World { @Override public void playSound(Location loc, String sound, org.bukkit.SoundCategory category, float volume, float pitch) { - if (loc == null || sound == null || category == null) return; + Preconditions.checkArgument(loc != null, "Location cannot be null"); + Preconditions.checkArgument(sound != null, "Sound cannot be null"); + Preconditions.checkArgument(!sound.isBlank(), "Sound cannot be empty"); + Preconditions.checkArgument(category != null, "Category cannot be null"); double x = loc.getX(); double y = loc.getY(); @@ -1662,26 +1673,27 @@ public class CraftWorld extends CraftRegionAccessor implements World { @Override public boolean isGameRule(String rule) { - Validate.isTrue(rule != null && !rule.isEmpty(), "Rule cannot be null nor empty"); + Preconditions.checkArgument(rule != null, "String rule cannot be null"); + Preconditions.checkArgument(!rule.isBlank(), "String rule cannot be empty"); return getGameRulesNMS().containsKey(rule); } @Override public T getGameRuleValue(GameRule rule) { - Validate.notNull(rule, "GameRule cannot be null"); + Preconditions.checkArgument(rule != null, "GameRule cannot be null"); return convert(rule, getHandle().getGameRules().getRule(getGameRulesNMS().get(rule.getName()))); } @Override public T getGameRuleDefault(GameRule rule) { - Validate.notNull(rule, "GameRule cannot be null"); + Preconditions.checkArgument(rule != null, "GameRule cannot be null"); return convert(rule, getGameRuleDefinitions().get(rule.getName()).createRule()); } @Override public boolean setGameRule(GameRule rule, T newValue) { - Validate.notNull(rule, "GameRule cannot be null"); - Validate.notNull(newValue, "GameRule value cannot be null"); + Preconditions.checkArgument(rule != null, "GameRule cannot be null"); + Preconditions.checkArgument(newValue != null, "GameRule value cannot be null"); if (!isGameRule(rule.getName())) return false; @@ -1781,8 +1793,8 @@ public class CraftWorld extends CraftRegionAccessor implements World { @Override public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data, boolean force) { - if (data != null && !particle.getDataType().isInstance(data)) { - throw new IllegalArgumentException("data should be " + particle.getDataType() + " got " + data.getClass()); + if (data != null) { + Preconditions.checkArgument(particle.getDataType().isInstance(data), "data (%s) should be %s", data.getClass(), particle.getDataType()); } getHandle().sendParticles( null, // Sender @@ -1878,8 +1890,8 @@ public class CraftWorld extends CraftRegionAccessor implements World { @Override public Raid locateNearestRaid(Location location, int radius) { - Validate.notNull(location, "Location cannot be null"); - Validate.isTrue(radius >= 0, "Radius cannot be negative"); + Preconditions.checkArgument(location != null, "Location cannot be null"); + Preconditions.checkArgument(radius >= 0, "Radius value (%s) cannot be negative", radius); PersistentRaid persistentRaid = world.getRaids(); net.minecraft.world.entity.raid.Raid raid = persistentRaid.getNearbyRaid(CraftLocation.toBlockPosition(location), radius * radius); diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/block/CraftBlock.java b/paper-server/src/main/java/org/bukkit/craftbukkit/block/CraftBlock.java index ef3ede7cf6..c683616d4a 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/block/CraftBlock.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/block/CraftBlock.java @@ -31,7 +31,6 @@ import net.minecraft.world.phys.MovingObjectPosition; import net.minecraft.world.phys.MovingObjectPositionBlock; import net.minecraft.world.phys.Vec3D; import net.minecraft.world.phys.shapes.VoxelShape; -import org.apache.commons.lang.Validate; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.FluidCollisionMode; @@ -392,10 +391,9 @@ public class CraftBlock implements Block { if (o == this) { return true; } - if (!(o instanceof CraftBlock)) { + if (!(o instanceof CraftBlock other)) { return false; } - CraftBlock other = (CraftBlock) o; return this.position.equals(other.position) && this.getWorld().equals(other.getWorld()); } @@ -593,15 +591,15 @@ public class CraftBlock implements Block { @Override public RayTraceResult rayTrace(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode) { - Validate.notNull(start, "Start location is null!"); - Validate.isTrue(this.getWorld().equals(start.getWorld()), "Start location is from different world!"); + Preconditions.checkArgument(start != null, "Location start cannot be null"); + Preconditions.checkArgument(this.getWorld().equals(start.getWorld()), "Location start cannot be a different world"); start.checkFinite(); - Validate.notNull(direction, "Direction is null!"); + Preconditions.checkArgument(direction != null, "Vector direction cannot be null"); direction.checkFinite(); - Validate.isTrue(direction.lengthSquared() > 0, "Direction's magnitude is 0!"); + Preconditions.checkArgument(direction.lengthSquared() > 0, "Direction's magnitude (%s) must be greater than 0", direction.lengthSquared()); - Validate.notNull(fluidCollisionMode, "Fluid collision mode is null!"); + Preconditions.checkArgument(fluidCollisionMode != null, "FluidCollisionMode cannot be null"); if (maxDistance < 0.0D) { return null; } @@ -634,7 +632,7 @@ public class CraftBlock implements Block { @Override public boolean canPlace(BlockData data) { - Preconditions.checkArgument(data != null, "Provided block data is null!"); + Preconditions.checkArgument(data != null, "BlockData cannot be null"); net.minecraft.world.level.block.state.IBlockData iblockdata = ((CraftBlockData) data).getState(); net.minecraft.world.level.World world = this.world.getMinecraftWorld(); diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/block/CraftBlockState.java b/paper-server/src/main/java/org/bukkit/craftbukkit/block/CraftBlockState.java index 5c2236f5e5..19de83433a 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/block/CraftBlockState.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/block/CraftBlockState.java @@ -80,9 +80,7 @@ public class CraftBlockState implements BlockState { } protected final void ensureNoWorldGeneration() { - if (isWorldGeneration()) { - throw new IllegalStateException("This operation is not supported during world generation!"); - } + Preconditions.checkState(!isWorldGeneration(), "This operation is not supported during world generation!"); } @Override @@ -142,12 +140,8 @@ public class CraftBlockState implements BlockState { if ((mat == null) || (mat.getData() == null)) { this.data = CraftMagicNumbers.getBlock(data); } else { - if ((data.getClass() == mat.getData()) || (data.getClass() == MaterialData.class)) { - this.data = CraftMagicNumbers.getBlock(data); - } else { - throw new IllegalArgumentException("Provided data is not of type " - + mat.getData().getName() + ", found " + data.getClass().getName()); - } + Preconditions.checkArgument((data.getClass() == mat.getData()) || (data.getClass() == MaterialData.class), "Provided data is not of type %s, found %s", mat.getData().getName(), data.getClass().getName()); + this.data = CraftMagicNumbers.getBlock(data); } } @@ -322,8 +316,6 @@ public class CraftBlockState implements BlockState { } protected void requirePlaced() { - if (!isPlaced()) { - throw new IllegalStateException("The blockState must be placed to call this method"); - } + Preconditions.checkState(isPlaced(), "The blockState must be placed to call this method"); } } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/block/CraftStructureBlock.java b/paper-server/src/main/java/org/bukkit/craftbukkit/block/CraftStructureBlock.java index 3890089b7a..39488f723d 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/block/CraftStructureBlock.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/block/CraftStructureBlock.java @@ -1,12 +1,10 @@ package org.bukkit.craftbukkit.block; import com.google.common.base.Preconditions; -import net.minecraft.core.BlockPosition; import net.minecraft.world.level.block.EnumBlockMirror; import net.minecraft.world.level.block.EnumBlockRotation; import net.minecraft.world.level.block.entity.TileEntityStructure; import net.minecraft.world.level.block.state.properties.BlockPropertyStructureMode; -import org.apache.commons.lang3.Validate; import org.bukkit.World; import org.bukkit.block.Structure; import org.bukkit.block.structure.Mirror; @@ -32,7 +30,7 @@ public class CraftStructureBlock extends CraftBlockEntityState tabComplete(CommandSender sender, String alias, String[] args, Location location) throws IllegalArgumentException { - Validate.notNull(sender, "Sender cannot be null"); - Validate.notNull(args, "Arguments cannot be null"); - Validate.notNull(alias, "Alias cannot be null"); + Preconditions.checkArgument(sender != null, "Sender cannot be null"); + Preconditions.checkArgument(args != null, "Arguments cannot be null"); + Preconditions.checkArgument(alias != null, "Alias cannot be null"); CommandListenerWrapper icommandlistener = getListener(sender); ParseResults parsed = dispatcher.getDispatcher().parse(toDispatcher(args, getName()), icommandlistener); diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractHorse.java b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractHorse.java index 3c8f3cdf8e..de748e927a 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractHorse.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftAbstractHorse.java @@ -1,9 +1,9 @@ package org.bukkit.craftbukkit.entity; +import com.google.common.base.Preconditions; import java.util.UUID; import net.minecraft.world.entity.ai.attributes.GenericAttributes; import net.minecraft.world.entity.animal.horse.EntityHorseAbstract; -import org.apache.commons.lang.Validate; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.inventory.CraftInventoryAbstractHorse; import org.bukkit.entity.AbstractHorse; @@ -34,8 +34,7 @@ public abstract class CraftAbstractHorse extends CraftAnimals implements Abstrac @Override public void setDomestication(int value) { - Validate.isTrue(value >= 0, "Domestication cannot be less than zero"); - Validate.isTrue(value <= getMaxDomestication(), "Domestication cannot be greater than the max domestication"); + Preconditions.checkArgument(value >= 0 && value <= this.getMaxDomestication(), "Domestication level (%s) need to be between %s and %s (max domestication)", value, 0, this.getMaxDomestication()); getHandle().setTemper(value); } @@ -46,7 +45,7 @@ public abstract class CraftAbstractHorse extends CraftAnimals implements Abstrac @Override public void setMaxDomestication(int value) { - Validate.isTrue(value > 0, "Max domestication cannot be zero or less"); + Preconditions.checkArgument(value > 0, "Max domestication (%s) cannot be zero or less", value); getHandle().maxDomestication = value; } @@ -57,7 +56,7 @@ public abstract class CraftAbstractHorse extends CraftAnimals implements Abstrac @Override public void setJumpStrength(double strength) { - Validate.isTrue(strength >= 0, "Jump strength cannot be less than zero"); + Preconditions.checkArgument(strength >= 0, "Jump strength (%s) cannot be less than zero", strength); getHandle().getAttribute(GenericAttributes.JUMP_STRENGTH).setBaseValue(strength); } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftAreaEffectCloud.java b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftAreaEffectCloud.java index 1a5e537669..598c070a28 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftAreaEffectCloud.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftAreaEffectCloud.java @@ -1,12 +1,12 @@ package org.bukkit.craftbukkit.entity; +import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import java.util.List; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffectList; import net.minecraft.world.entity.EntityAreaEffectCloud; import net.minecraft.world.entity.EntityLiving; -import org.apache.commons.lang.Validate; import org.bukkit.Color; import org.bukkit.Particle; import org.bukkit.craftbukkit.CraftParticle; @@ -205,7 +205,7 @@ public class CraftAreaEffectCloud extends CraftEntity implements AreaEffectCloud @Override public void setBasePotionData(PotionData data) { - Validate.notNull(data, "PotionData cannot be null"); + Preconditions.checkArgument(data != null, "PotionData cannot be null"); getHandle().setPotionType(CraftPotionUtil.fromBukkit(data)); } @@ -222,10 +222,10 @@ public class CraftAreaEffectCloud extends CraftEntity implements AreaEffectCloud @Override public void setSource(ProjectileSource shooter) { - if (shooter instanceof CraftLivingEntity) { - getHandle().setOwner((EntityLiving) ((CraftLivingEntity) shooter).getHandle()); + if (shooter instanceof CraftLivingEntity craftLivingEntity) { + getHandle().setOwner(craftLivingEntity.getHandle()); } else { - getHandle().setOwner((EntityLiving) null); + getHandle().setOwner(null); } } } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftArrow.java b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftArrow.java index 139d902cbc..dc0dd14b36 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftArrow.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftArrow.java @@ -3,11 +3,9 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; import net.minecraft.core.BlockPosition; import net.minecraft.world.entity.projectile.EntityArrow; -import org.apache.commons.lang.Validate; import org.bukkit.block.Block; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.AbstractArrow; -import org.bukkit.entity.AbstractArrow.PickupStatus; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.projectiles.ProjectileSource; @@ -20,7 +18,7 @@ public class CraftArrow extends AbstractProjectile implements AbstractArrow { @Override public void setKnockbackStrength(int knockbackStrength) { - Validate.isTrue(knockbackStrength >= 0, "Knockback cannot be negative"); + Preconditions.checkArgument(knockbackStrength >= 0, "Knockback value (%s) cannot be negative", knockbackStrength); getHandle().setKnockback(knockbackStrength); } @@ -36,7 +34,7 @@ public class CraftArrow extends AbstractProjectile implements AbstractArrow { @Override public void setDamage(double damage) { - Preconditions.checkArgument(damage >= 0, "Damage must be positive"); + Preconditions.checkArgument(damage >= 0, "Damage value (%s) must be positive", damage); getHandle().setBaseDamage(damage); } @@ -47,7 +45,7 @@ public class CraftArrow extends AbstractProjectile implements AbstractArrow { @Override public void setPierceLevel(int pierceLevel) { - Preconditions.checkArgument(0 <= pierceLevel && pierceLevel <= Byte.MAX_VALUE, "Pierce level out of range, expected 0 < level < 127"); + Preconditions.checkArgument(0 <= pierceLevel && pierceLevel <= Byte.MAX_VALUE, "Pierce level (%s) out of range, expected 0 < level < 127", pierceLevel); getHandle().setPierceLevel((byte) pierceLevel); } @@ -99,7 +97,7 @@ public class CraftArrow extends AbstractProjectile implements AbstractArrow { @Override public void setPickupStatus(PickupStatus status) { - Preconditions.checkNotNull(status, "status"); + Preconditions.checkArgument(status != null, "PickupStatus cannot be null"); getHandle().pickup = EntityArrow.PickupStatus.byOrdinal(status.ordinal()); } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java index bf03b0bc94..08c4025aac 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java @@ -615,7 +615,7 @@ public abstract class CraftEntity implements org.bukkit.entity.Entity { @Override public void setFreezeTicks(int ticks) { - Preconditions.checkArgument(0 <= ticks, "Ticks cannot be less than 0"); + Preconditions.checkArgument(0 <= ticks, "Ticks (%s) cannot be less than 0", ticks); getHandle().setTicksFrozen(ticks); } @@ -681,17 +681,12 @@ public abstract class CraftEntity implements org.bukkit.entity.Entity { @Override public List getPassengers() { - return Lists.newArrayList(Lists.transform(getHandle().passengers, new Function() { - @Override - public org.bukkit.entity.Entity apply(Entity input) { - return input.getBukkitEntity(); - } - })); + return Lists.newArrayList(Lists.transform(getHandle().passengers, (Function) input -> input.getBukkitEntity())); } @Override public boolean addPassenger(org.bukkit.entity.Entity passenger) { - Preconditions.checkArgument(passenger != null, "passenger == null"); + Preconditions.checkArgument(passenger != null, "Entity passenger cannot be null"); Preconditions.checkArgument(!this.equals(passenger), "Entity cannot ride itself."); return ((CraftEntity) passenger).getHandle().startRiding(getHandle(), true); @@ -699,7 +694,7 @@ public abstract class CraftEntity implements org.bukkit.entity.Entity { @Override public boolean removePassenger(org.bukkit.entity.Entity passenger) { - Preconditions.checkArgument(passenger != null, "passenger == null"); + Preconditions.checkArgument(passenger != null, "Entity passenger cannot be null"); ((CraftEntity) passenger).getHandle().stopRiding(); return true; @@ -752,9 +747,7 @@ public abstract class CraftEntity implements org.bukkit.entity.Entity { @Override public void setTicksLived(int value) { - if (value <= 0) { - throw new IllegalArgumentException("Age must be at least 1 tick"); - } + Preconditions.checkArgument(value > 0, "Age value (%s) must be positive", value); getHandle().tickCount = value; } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFireball.java b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFireball.java index 44a5a58732..64e766f5b4 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFireball.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFireball.java @@ -1,7 +1,7 @@ package org.bukkit.craftbukkit.entity; +import com.google.common.base.Preconditions; import net.minecraft.world.entity.projectile.EntityFireball; -import org.apache.commons.lang.Validate; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.EntityType; import org.bukkit.entity.Fireball; @@ -55,7 +55,7 @@ public class CraftFireball extends AbstractProjectile implements Fireball { @Override public void setDirection(Vector direction) { - Validate.notNull(direction, "Direction can not be null"); + Preconditions.checkArgument(direction != null, "Vector direction cannot be null"); getHandle().setDirection(direction.getX(), direction.getY(), direction.getZ()); update(); // SPIGOT-6579 } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFishHook.java b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFishHook.java index b165fe1196..fda83e13f3 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFishHook.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFishHook.java @@ -1,14 +1,12 @@ package org.bukkit.craftbukkit.entity; +import com.google.common.base.Preconditions; import net.minecraft.core.BlockPosition; -import net.minecraft.util.MathHelper; import net.minecraft.world.entity.projectile.EntityFishingHook; -import org.apache.commons.lang.Validate; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.FishHook; -import org.bukkit.entity.FishHook.HookState; public class CraftFishHook extends CraftProjectile implements FishHook { private double biteChance = -1; @@ -39,8 +37,8 @@ public class CraftFishHook extends CraftProjectile implements FishHook { @Override public void setMinWaitTime(int minWaitTime) { + Preconditions.checkArgument(minWaitTime >= 0 && minWaitTime <= this.getMaxWaitTime(), "The minimum wait time should be between %s and %s (the maximum wait time)", 0, this.getMaxWaitTime()); EntityFishingHook hook = getHandle(); - Validate.isTrue(minWaitTime >= 0 && minWaitTime <= this.getMaxWaitTime(), "The minimum wait time should be between 0 and the maximum wait time."); hook.minWaitTime = minWaitTime; } @@ -51,14 +49,14 @@ public class CraftFishHook extends CraftProjectile implements FishHook { @Override public void setMaxWaitTime(int maxWaitTime) { + Preconditions.checkArgument(maxWaitTime >= 0 && maxWaitTime >= this.getMinWaitTime(), "The maximum wait time should be between %s and %s (the minimum wait time)", 0, this.getMinWaitTime()); EntityFishingHook hook = getHandle(); - Validate.isTrue(maxWaitTime >= 0 && maxWaitTime >= this.getMinWaitTime(), "The maximum wait time should be higher than or equal to 0 and the minimum wait time."); hook.maxWaitTime = maxWaitTime; } @Override public void setWaitTime(int min, int max) { - Validate.isTrue(min >= 0 && max >= 0 && min <= max, "The minimum/maximum wait time should be higher than or equal to 0 and the minimum wait time."); + Preconditions.checkArgument(min >= 0 && max >= 0 && min <= max, "The minimum/maximum wait time should be higher than or equal to 0 and the minimum wait time"); getHandle().minWaitTime = min; getHandle().maxWaitTime = max; } @@ -70,7 +68,7 @@ public class CraftFishHook extends CraftProjectile implements FishHook { @Override public void setMinLureTime(int minLureTime) { - Validate.isTrue(minLureTime >= 0 && minLureTime <= this.getMaxLureTime(), "The minimum lure time should be between 0 and the maximum wait time."); + Preconditions.checkArgument(minLureTime >= 0 && minLureTime <= this.getMaxLureTime(), "The minimum lure time (%s) should be between 0 and %s (the maximum wait time)", minLureTime, this.getMaxLureTime()); getHandle().minLureTime = minLureTime; } @@ -81,13 +79,13 @@ public class CraftFishHook extends CraftProjectile implements FishHook { @Override public void setMaxLureTime(int maxLureTime) { - Validate.isTrue(maxLureTime >= 0 && maxLureTime >= this.getMinLureTime(), "The maximum lure time should be higher than or equal to 0 and the minimum wait time."); + Preconditions.checkArgument(maxLureTime >= 0 && maxLureTime >= this.getMinLureTime(), "The maximum lure time (%s) should be higher than or equal to 0 and %s (the minimum wait time)", maxLureTime, this.getMinLureTime()); getHandle().maxLureTime = maxLureTime; } @Override public void setLureTime(int min, int max) { - Validate.isTrue(min >= 0 && max >= 0 && min <= max, "The minimum/maximum lure time should be higher than or equal to 0 and the minimum wait time."); + Preconditions.checkArgument(min >= 0 && max >= 0 && min <= max, "The minimum/maximum lure time should be higher than or equal to 0 and the minimum wait time."); getHandle().minLureTime = min; getHandle().maxLureTime = max; } @@ -99,7 +97,7 @@ public class CraftFishHook extends CraftProjectile implements FishHook { @Override public void setMinLureAngle(float minLureAngle) { - Validate.isTrue(minLureAngle <= this.getMaxLureAngle(), "The minimum lure angle should be less than the maximum lure angle."); + Preconditions.checkArgument(minLureAngle <= this.getMaxLureAngle(), "The minimum lure angle (%s) should be less than %s (the maximum lure angle)", minLureAngle, this.getMaxLureAngle()); getHandle().minLureAngle = minLureAngle; } @@ -110,13 +108,13 @@ public class CraftFishHook extends CraftProjectile implements FishHook { @Override public void setMaxLureAngle(float maxLureAngle) { - Validate.isTrue(maxLureAngle >= this.getMinLureAngle(), "The minimum lure angle should be less than the maximum lure angle."); + Preconditions.checkArgument(maxLureAngle >= this.getMinLureAngle(), "The minimum lure angle (%s) should be less than %s (the maximum lure angle)", maxLureAngle, this.getMinLureAngle()); getHandle().maxLureAngle = maxLureAngle; } @Override public void setLureAngle(float min, float max) { - Validate.isTrue(min <= max, "The minimum lure angle should be less than the maximum lure angle."); + Preconditions.checkArgument(min <= max, "The minimum lure (%s) angle should be less than the maximum lure angle (%s)", min, max); getHandle().minLureAngle = min; getHandle().maxLureAngle = max; } @@ -166,7 +164,7 @@ public class CraftFishHook extends CraftProjectile implements FishHook { @Override public void setBiteChance(double chance) { - Validate.isTrue(chance >= 0 && chance <= 1, "The bite chance must be between 0 and 1."); + Preconditions.checkArgument(chance >= 0 && chance <= 1, "The bite chance must be between 0 and 1"); this.biteChance = chance; } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFox.java b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFox.java index d3319f1431..909513c50f 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFox.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFox.java @@ -85,8 +85,8 @@ public class CraftFox extends CraftAnimals implements Fox { @Override public void setFirstTrustedPlayer(AnimalTamer player) { - if (player == null && getHandle().getEntityData().get(EntityFox.DATA_TRUSTED_ID_1).isPresent()) { - throw new IllegalStateException("Must remove second trusted player first"); + if (player == null) { + Preconditions.checkState(getHandle().getEntityData().get(EntityFox.DATA_TRUSTED_ID_1).isEmpty(), "Must remove second trusted player first"); } getHandle().getEntityData().set(EntityFox.DATA_TRUSTED_ID_0, player == null ? Optional.empty() : Optional.of(player.getUniqueId())); @@ -109,8 +109,8 @@ public class CraftFox extends CraftAnimals implements Fox { @Override public void setSecondTrustedPlayer(AnimalTamer player) { - if (player != null && !getHandle().getEntityData().get(EntityFox.DATA_TRUSTED_ID_0).isPresent()) { - throw new IllegalStateException("Must add first trusted player first"); + if (player != null) { + Preconditions.checkState(getHandle().getEntityData().get(EntityFox.DATA_TRUSTED_ID_0).isPresent(), "Must add first trusted player first"); } getHandle().getEntityData().set(EntityFox.DATA_TRUSTED_ID_1, player == null ? Optional.empty() : Optional.of(player.getUniqueId())); diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftHorse.java b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftHorse.java index 6a4712b940..27a525be87 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftHorse.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftHorse.java @@ -1,16 +1,13 @@ package org.bukkit.craftbukkit.entity; +import com.google.common.base.Preconditions; import net.minecraft.world.entity.animal.horse.EntityHorse; import net.minecraft.world.entity.animal.horse.HorseColor; import net.minecraft.world.entity.animal.horse.HorseStyle; -import org.apache.commons.lang.Validate; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.inventory.CraftInventoryHorse; import org.bukkit.entity.EntityType; import org.bukkit.entity.Horse; -import org.bukkit.entity.Horse.Color; -import org.bukkit.entity.Horse.Style; -import org.bukkit.entity.Horse.Variant; import org.bukkit.inventory.HorseInventory; public class CraftHorse extends CraftAbstractHorse implements Horse { @@ -36,7 +33,7 @@ public class CraftHorse extends CraftAbstractHorse implements Horse { @Override public void setColor(Color color) { - Validate.notNull(color, "Color cannot be null"); + Preconditions.checkArgument(color != null, "Color cannot be null"); getHandle().setVariantAndMarkings(HorseColor.byId(color.ordinal()), getHandle().getMarkings()); } @@ -47,7 +44,7 @@ public class CraftHorse extends CraftAbstractHorse implements Horse { @Override public void setStyle(Style style) { - Validate.notNull(style, "Style cannot be null"); + Preconditions.checkArgument(style != null, "Style cannot be null"); getHandle().setVariantAndMarkings(getHandle().getVariant(), HorseStyle.byId(style.ordinal())); } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java index c25f8bcf84..b4a2a50d51 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java @@ -247,9 +247,7 @@ public class CraftHumanEntity extends CraftLivingEntity implements HumanEntity { @Override public void setGameMode(GameMode mode) { - if (mode == null) { - throw new IllegalArgumentException("Mode cannot be null"); - } + Preconditions.checkArgument(mode != null, "GameMode cannot be null"); this.mode = mode; } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftItemFrame.java b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftItemFrame.java index 1ff379bf6f..d89b0336d0 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftItemFrame.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftItemFrame.java @@ -5,7 +5,6 @@ import net.minecraft.core.EnumDirection; import net.minecraft.world.entity.decoration.EntityHanging; import net.minecraft.world.entity.decoration.EntityItemFrame; import net.minecraft.world.level.block.Blocks; -import org.apache.commons.lang.Validate; import org.bukkit.Rotation; import org.bukkit.block.BlockFace; import org.bukkit.craftbukkit.CraftServer; @@ -75,7 +74,7 @@ public class CraftItemFrame extends CraftHanging implements ItemFrame { @Override public void setItemDropChance(float chance) { - Preconditions.checkArgument(0.0 <= chance && chance <= 1.0, "Chance outside range [0, 1]"); + Preconditions.checkArgument(0.0 <= chance && chance <= 1.0, "Chance (%s) outside range [0, 1]", chance); getHandle().dropChance = chance; } @@ -110,7 +109,7 @@ public class CraftItemFrame extends CraftHanging implements ItemFrame { @Override public void setRotation(Rotation rotation) { - Validate.notNull(rotation, "Rotation cannot be null"); + Preconditions.checkArgument(rotation != null, "Rotation cannot be null"); getHandle().setRotation(toInteger(rotation)); } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftLivingEntity.java b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftLivingEntity.java index aa9c4cb13c..e88342e714 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftLivingEntity.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftLivingEntity.java @@ -40,7 +40,6 @@ import net.minecraft.world.entity.projectile.EntityThrownExpBottle; import net.minecraft.world.entity.projectile.EntityThrownTrident; import net.minecraft.world.entity.projectile.EntityTippedArrow; import net.minecraft.world.entity.projectile.EntityWitherSkull; -import org.apache.commons.lang.Validate; import org.bukkit.FluidCollisionMode; import org.bukkit.Location; import org.bukkit.Material; @@ -113,9 +112,7 @@ public class CraftLivingEntity extends CraftEntity implements LivingEntity { @Override public void setHealth(double health) { health = (float) health; - if ((health < 0) || (health > getMaxHealth())) { - throw new IllegalArgumentException("Health must be between 0 and " + getMaxHealth() + "(" + health + ")"); - } + Preconditions.checkArgument(health >= 0 && health <= this.getMaxHealth(), "Health value (%s) must be between 0 and %s", health, this.getMaxHealth()); // during world generation, we don't want to run logic for dropping items and xp if (getHandle().generation && health == 0) { @@ -149,7 +146,7 @@ public class CraftLivingEntity extends CraftEntity implements LivingEntity { @Override public void setMaxHealth(double amount) { - Validate.isTrue(amount > 0, "Max health must be greater than 0"); + Preconditions.checkArgument(amount > 0, "Max health amount (%s) must be greater than 0", amount); getHandle().getAttribute(GenericAttributes.MAX_HEALTH).setBaseValue(amount); @@ -486,7 +483,7 @@ public class CraftLivingEntity extends CraftEntity implements LivingEntity { launch.moveTo(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); } - Validate.notNull(launch, "Projectile not supported"); + Preconditions.checkArgument(launch != null, "Projectile (%s) not supported", projectile.getName()); if (velocity != null) { ((T) launch.getBukkitEntity()).setVelocity(velocity); @@ -562,9 +559,7 @@ public class CraftLivingEntity extends CraftEntity implements LivingEntity { @Override public Entity getLeashHolder() throws IllegalStateException { - if (!isLeashed()) { - throw new IllegalStateException("Entity not leashed"); - } + Preconditions.checkState(isLeashed(), "Entity not leashed"); return ((EntityInsentient) getHandle()).getLeashHolder().getBukkitEntity(); } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java index c600da19ff..6eb60cab5c 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java @@ -92,7 +92,6 @@ import net.minecraft.world.level.border.IWorldBorderListener; import net.minecraft.world.level.saveddata.maps.MapIcon; import net.minecraft.world.level.saveddata.maps.WorldMap; import net.minecraft.world.phys.Vec3D; -import org.apache.commons.lang.Validate; import org.bukkit.BanList; import org.bukkit.Bukkit; import org.bukkit.DyeColor; @@ -242,15 +241,13 @@ public class CraftPlayer extends CraftHumanEntity implements Player { @Override public void sendRawMessage(String message) { - if (getHandle().connection == null) return; - - for (IChatBaseComponent component : CraftChatMessage.fromString(message)) { - getHandle().sendSystemMessage(component); - } + this.sendRawMessage(null, message); } @Override public void sendRawMessage(UUID sender, String message) { + Preconditions.checkArgument(message != null, "message cannot be null"); + if (getHandle().connection == null) return; for (IChatBaseComponent component : CraftChatMessage.fromString(message)) { @@ -382,6 +379,8 @@ public class CraftPlayer extends CraftHumanEntity implements Player { @Override public void setCompassTarget(Location loc) { + Preconditions.checkArgument(loc != null, "Location cannot be null"); + if (getHandle().connection == null) return; // Do not directly assign here, from the packethandler we'll assign it. @@ -395,6 +394,8 @@ public class CraftPlayer extends CraftHumanEntity implements Player { @Override public void chat(String msg) { + Preconditions.checkArgument(msg != null, "msg cannot be null"); + if (getHandle().connection == null) return; getHandle().connection.chat(msg, PlayerChatMessage.system(msg), false); @@ -402,109 +403,44 @@ public class CraftPlayer extends CraftHumanEntity implements Player { @Override public boolean performCommand(String command) { + Preconditions.checkArgument(command != null, "command cannot be null"); return server.dispatchCommand(this, command); } @Override public void playNote(Location loc, byte instrument, byte note) { - if (getHandle().connection == null) return; - - String instrumentName = null; - switch (instrument) { - case 0: - instrumentName = "harp"; - break; - case 1: - instrumentName = "basedrum"; - break; - case 2: - instrumentName = "snare"; - break; - case 3: - instrumentName = "hat"; - break; - case 4: - instrumentName = "bass"; - break; - case 5: - instrumentName = "flute"; - break; - case 6: - instrumentName = "bell"; - break; - case 7: - instrumentName = "guitar"; - break; - case 8: - instrumentName = "chime"; - break; - case 9: - instrumentName = "xylophone"; - break; - } - - float f = (float) Math.pow(2.0D, (note - 12.0D) / 12.0D); - getHandle().connection.send(new PacketPlayOutNamedSoundEffect(BuiltInRegistries.SOUND_EVENT.wrapAsHolder(CraftSound.getSoundEffect("block.note_block." + instrumentName)), net.minecraft.sounds.SoundCategory.RECORDS, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), 3.0f, f, getHandle().getRandom().nextLong())); + playNote(loc, Instrument.getByType(instrument), new Note(note)); } @Override public void playNote(Location loc, Instrument instrument, Note note) { + Preconditions.checkArgument(loc != null, "Location cannot be null"); + Preconditions.checkArgument(instrument != null, "Instrument cannot be null"); + Preconditions.checkArgument(note != null, "Note cannot be null"); + if (getHandle().connection == null) return; - String instrumentName = null; - switch (instrument.ordinal()) { - case 0: - instrumentName = "harp"; - break; - case 1: - instrumentName = "basedrum"; - break; - case 2: - instrumentName = "snare"; - break; - case 3: - instrumentName = "hat"; - break; - case 4: - instrumentName = "bass"; - break; - case 5: - instrumentName = "flute"; - break; - case 6: - instrumentName = "bell"; - break; - case 7: - instrumentName = "guitar"; - break; - case 8: - instrumentName = "chime"; - break; - case 9: - instrumentName = "xylophone"; - break; - case 10: - instrumentName = "iron_xylophone"; - break; - case 11: - instrumentName = "cow_bell"; - break; - case 12: - instrumentName = "didgeridoo"; - break; - case 13: - instrumentName = "bit"; - break; - case 14: - instrumentName = "banjo"; - break; - case 15: - instrumentName = "pling"; - break; - case 16: - instrumentName = "xylophone"; - break; - } + String instrumentName = switch (instrument.ordinal()) { + case 0 -> "harp"; + case 1 -> "basedrum"; + case 2 -> "snare"; + case 3 -> "hat"; + case 4 -> "bass"; + case 5 -> "flute"; + case 6 -> "bell"; + case 7 -> "guitar"; + case 8 -> "chime"; + case 9 -> "xylophone"; + case 10 -> "iron_xylophone"; + case 11 -> "cow_bell"; + case 12 -> "didgeridoo"; + case 13 -> "bit"; + case 14 -> "banjo"; + case 15 -> "pling"; + case 16 -> "xylophone"; + default -> null; + }; + float f = (float) Math.pow(2.0D, (note.getId() - 12.0D) / 12.0D); getHandle().connection.send(new PacketPlayOutNamedSoundEffect(BuiltInRegistries.SOUND_EVENT.wrapAsHolder(CraftSound.getSoundEffect("block.note_block." + instrumentName)), net.minecraft.sounds.SoundCategory.RECORDS, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), 3.0f, f, getHandle().getRandom().nextLong())); } @@ -521,17 +457,26 @@ public class CraftPlayer extends CraftHumanEntity implements Player { @Override public void playSound(Location loc, Sound sound, org.bukkit.SoundCategory category, float volume, float pitch) { - if (loc == null || sound == null || category == null || getHandle().connection == null) return; + Preconditions.checkArgument(sound != null, "Sound cannot be null"); + Preconditions.checkArgument(category != null, "Category cannot be null"); - PacketPlayOutNamedSoundEffect packet = new PacketPlayOutNamedSoundEffect(BuiltInRegistries.SOUND_EVENT.wrapAsHolder(CraftSound.getSoundEffect(sound)), net.minecraft.sounds.SoundCategory.valueOf(category.name()), loc.getX(), loc.getY(), loc.getZ(), volume, pitch, getHandle().getRandom().nextLong()); - getHandle().connection.send(packet); + playSound0(loc, BuiltInRegistries.SOUND_EVENT.wrapAsHolder(CraftSound.getSoundEffect(sound)), net.minecraft.sounds.SoundCategory.valueOf(category.name()), volume, pitch); } @Override public void playSound(Location loc, String sound, org.bukkit.SoundCategory category, float volume, float pitch) { - if (loc == null || sound == null || category == null || getHandle().connection == null) return; + Preconditions.checkArgument(sound != null, "sound cannot be null"); + Preconditions.checkArgument(category != null, "Category cannot be null"); - PacketPlayOutNamedSoundEffect packet = new PacketPlayOutNamedSoundEffect(Holder.direct(SoundEffect.createVariableRangeEvent(new MinecraftKey(sound))), net.minecraft.sounds.SoundCategory.valueOf(category.name()), loc.getX(), loc.getY(), loc.getZ(), volume, pitch, getHandle().getRandom().nextLong()); + playSound0(loc, Holder.direct(SoundEffect.createVariableRangeEvent(new MinecraftKey(sound))), net.minecraft.sounds.SoundCategory.valueOf(category.name()), volume, pitch); + } + + private void playSound0(Location loc, Holder soundEffectHolder, net.minecraft.sounds.SoundCategory categoryNMS, float volume, float pitch) { + Preconditions.checkArgument(loc != null, "Location cannot be null"); + + if (getHandle().connection == null) return; + + PacketPlayOutNamedSoundEffect packet = new PacketPlayOutNamedSoundEffect(soundEffectHolder, categoryNMS, loc.getX(), loc.getY(), loc.getZ(), volume, pitch, getHandle().getRandom().nextLong()); getHandle().connection.send(packet); } @@ -547,17 +492,29 @@ public class CraftPlayer extends CraftHumanEntity implements Player { @Override public void playSound(org.bukkit.entity.Entity entity, Sound sound, org.bukkit.SoundCategory category, float volume, float pitch) { - if (!(entity instanceof CraftEntity craftEntity) || sound == null || category == null || getHandle().connection == null) return; + Preconditions.checkArgument(category != null, "Category cannot be null"); + Preconditions.checkArgument(sound != null, "Sound cannot be null"); - PacketPlayOutEntitySound packet = new PacketPlayOutEntitySound(BuiltInRegistries.SOUND_EVENT.wrapAsHolder(CraftSound.getSoundEffect(sound)), net.minecraft.sounds.SoundCategory.valueOf(category.name()), craftEntity.getHandle(), volume, pitch, getHandle().getRandom().nextLong()); - getHandle().connection.send(packet); + playSound0(entity, BuiltInRegistries.SOUND_EVENT.wrapAsHolder(CraftSound.getSoundEffect(sound)), net.minecraft.sounds.SoundCategory.valueOf(category.name()), volume, pitch); } @Override public void playSound(org.bukkit.entity.Entity entity, String sound, org.bukkit.SoundCategory category, float volume, float pitch) { - if (!(entity instanceof CraftEntity craftEntity) || sound == null || category == null || getHandle().connection == null) return; + Preconditions.checkArgument(category != null, "Category cannot be null"); + Preconditions.checkArgument(sound != null, "sound cannot be null"); - PacketPlayOutEntitySound packet = new PacketPlayOutEntitySound(Holder.direct(SoundEffect.createVariableRangeEvent(new MinecraftKey(sound))), net.minecraft.sounds.SoundCategory.valueOf(category.name()), craftEntity.getHandle(), volume, pitch, getHandle().getRandom().nextLong()); + playSound0(entity, Holder.direct(SoundEffect.createVariableRangeEvent(new MinecraftKey(sound))), net.minecraft.sounds.SoundCategory.valueOf(category.name()), volume, pitch); + } + + private void playSound0(org.bukkit.entity.Entity entity, Holder soundEffectHolder, net.minecraft.sounds.SoundCategory categoryNMS, float volume, float pitch) { + Preconditions.checkArgument(entity != null, "Entity cannot be null"); + Preconditions.checkArgument(soundEffectHolder != null, "Holder of SoundEffect cannot be null"); + Preconditions.checkArgument(categoryNMS != null, "SoundCategory cannot be null"); + + if (getHandle().connection == null) return; + if (!(entity instanceof CraftEntity craftEntity)) return; + + PacketPlayOutEntitySound packet = new PacketPlayOutEntitySound(soundEffectHolder, categoryNMS, craftEntity.getHandle(), volume, pitch, getHandle().getRandom().nextLong()); getHandle().connection.send(packet); } @@ -599,6 +556,9 @@ public class CraftPlayer extends CraftHumanEntity implements Player { @Override public void playEffect(Location loc, Effect effect, int data) { + Preconditions.checkArgument(effect != null, "Effect cannot be null"); + Preconditions.checkArgument(loc != null, "Location cannot be null"); + if (getHandle().connection == null) return; int packetData = effect.getId(); @@ -608,11 +568,13 @@ public class CraftPlayer extends CraftHumanEntity implements Player { @Override public void playEffect(Location loc, Effect effect, T data) { + Preconditions.checkArgument(effect != null, "Effect cannot be null"); if (data != null) { - Validate.isTrue(effect.getData() != null && effect.getData().isAssignableFrom(data.getClass()), "Wrong kind of data for this effect!"); + Preconditions.checkArgument(effect.getData() != null, "Effect.%s does not have a valid Data", effect); + Preconditions.checkArgument(effect.getData().isAssignableFrom(data.getClass()), "%s data cannot be used for the %s effect", data.getClass().getName(), effect); } else { // Special case: the axis is optional for ELECTRIC_SPARK - Validate.isTrue(effect.getData() == null || effect == Effect.ELECTRIC_SPARK, "Wrong kind of data for this effect!"); + Preconditions.checkArgument(effect.getData() == null || effect == Effect.ELECTRIC_SPARK, "Wrong kind of data for the %s effect", effect); } int datavalue = CraftEffect.getDataValue(effect, data); @@ -725,19 +687,15 @@ public class CraftPlayer extends CraftHumanEntity implements Player { @Override public void sendSignChange(Location loc, String[] lines, DyeColor dyeColor, boolean hasGlowingText) { - if (getHandle().connection == null) { - return; - } + Preconditions.checkArgument(loc != null, "Location cannot be null"); + Preconditions.checkArgument(dyeColor != null, "DyeColor cannot be null"); if (lines == null) { lines = new String[4]; } + Preconditions.checkArgument(lines.length < 4, "lines (%s) must be lower than 4", lines.length); - Validate.notNull(loc, "Location can not be null"); - Validate.notNull(dyeColor, "DyeColor can not be null"); - if (lines.length < 4) { - throw new IllegalArgumentException("Must have at least 4 lines"); - } + if (getHandle().connection == null) return; IChatBaseComponent[] components = CraftSign.sanitizeLines(lines); TileEntitySign sign = new TileEntitySign(CraftLocation.toBlockPosition(loc), Blocks.OAK_SIGN.defaultBlockState()); @@ -758,8 +716,8 @@ public class CraftPlayer extends CraftHumanEntity implements Player { @Override public void sendEquipmentChange(LivingEntity entity, Map items) { - Preconditions.checkArgument(entity != null, "entity must not be null"); - Preconditions.checkArgument(items != null, "items must not be null"); + Preconditions.checkArgument(entity != null, "Entity cannot be null"); + Preconditions.checkArgument(items != null, "items cannot be null"); if (getHandle().connection == null) { return; @@ -1232,12 +1190,9 @@ public class CraftPlayer extends CraftHumanEntity implements Player { @Override public void setGameMode(GameMode mode) { + Preconditions.checkArgument(mode != null, "GameMode cannot be null"); if (getHandle().connection == null) return; - if (mode == null) { - throw new IllegalArgumentException("Mode cannot be null"); - } - getHandle().setGameMode(EnumGamemode.byId(mode.getValue())); } @@ -1334,14 +1289,14 @@ public class CraftPlayer extends CraftHumanEntity implements Player { @Override public void hideEntity(Plugin plugin, org.bukkit.entity.Entity entity) { - Validate.notNull(plugin, "Plugin cannot be null"); - Validate.isTrue(plugin.isEnabled(), "Plugin attempted to hide player while disabled"); + Preconditions.checkArgument(plugin != null, "Plugin cannot be null"); + Preconditions.checkArgument(plugin.isEnabled(), "Plugin (%s) cannot be disabled", plugin.getName()); hideEntity0(plugin, entity); } private void hideEntity0(@Nullable Plugin plugin, org.bukkit.entity.Entity entity) { - Validate.notNull(entity, "hidden entity cannot be null"); + Preconditions.checkArgument(entity != null, "Entity hidden cannot be null"); if (getHandle().connection == null) return; if (equals(entity)) return; @@ -1416,14 +1371,14 @@ public class CraftPlayer extends CraftHumanEntity implements Player { @Override public void showEntity(Plugin plugin, org.bukkit.entity.Entity entity) { - Validate.notNull(plugin, "Plugin cannot be null"); + Preconditions.checkArgument(plugin != null, "Plugin cannot be null"); // Don't require that plugin be enabled. A plugin must be allowed to call // showPlayer during its onDisable() method. showEntity0(plugin, entity); } private void showEntity0(@Nullable Plugin plugin, org.bukkit.entity.Entity entity) { - Validate.notNull(entity, "shown entity cannot be null"); + Preconditions.checkArgument(entity != null, "Entity show cannot be null"); if (getHandle().connection == null) return; if (equals(entity)) return; @@ -1661,10 +1616,10 @@ public class CraftPlayer extends CraftHumanEntity implements Player { @Override public void setResourcePack(String url, byte[] hash, String prompt, boolean force) { - Validate.notNull(url, "Resource pack URL cannot be null"); + Preconditions.checkArgument(url != null, "Resource pack URL cannot be null"); if (hash != null) { - Validate.isTrue(hash.length == 20, "Resource pack hash should be 20 bytes long but was " + hash.length); + Preconditions.checkArgument(hash.length == 20, "Resource pack hash should be 20 bytes long but was %s", hash.length); getHandle().sendTexturePack(url, BaseEncoding.base16().lowerCase().encode(hash), force, CraftChatMessage.fromStringOrNull(prompt, true)); } else { @@ -1759,8 +1714,8 @@ public class CraftPlayer extends CraftHumanEntity implements Player { @Override public void setFlying(boolean value) { - if (!getAllowFlight() && value) { - throw new IllegalArgumentException("Cannot make player fly if getAllowFlight() is false"); + if (!getAllowFlight()) { + Preconditions.checkArgument(!value, "Player is not allowed to fly (check #getAllowFlight())"); } getHandle().getAbilities().flying = value; @@ -1826,21 +1781,13 @@ public class CraftPlayer extends CraftHumanEntity implements Player { } private void validateSpeed(float value) { - if (value < 0) { - if (value < -1f) { - throw new IllegalArgumentException(value + " is too low"); - } - } else { - if (value > 1f) { - throw new IllegalArgumentException(value + " is too high"); - } - } + Preconditions.checkArgument(value <= 1f && value >= -1f, "Speed value (%s) need to be between -1f and 1f", value); } @Override public void setMaxHealth(double amount) { super.setMaxHealth(amount); - this.health = Math.min(this.health, health); + this.health = Math.min(this.health, amount); getHandle().resetSentInfo(); } @@ -1857,21 +1804,16 @@ public class CraftPlayer extends CraftHumanEntity implements Player { @Override public void setScoreboard(Scoreboard scoreboard) { - Validate.notNull(scoreboard, "Scoreboard cannot be null"); - PlayerConnection playerConnection = getHandle().connection; - if (playerConnection == null) { - throw new IllegalStateException("Cannot set scoreboard yet"); - } - if (playerConnection.isDisconnected()) { - throw new IllegalStateException("Cannot set scoreboard for invalid CraftPlayer"); - } + Preconditions.checkArgument(scoreboard != null, "Scoreboard cannot be null"); + Preconditions.checkState(getHandle().connection != null, "Cannot set scoreboard yet (invalid player connection)"); + Preconditions.checkState(getHandle().connection.isDisconnected(), "Cannot set scoreboard for invalid CraftPlayer (player is disconnected)"); this.server.getScoreboardManager().setPlayerBoard(this, scoreboard); } @Override public void setHealthScale(double value) { - Validate.isTrue((float) value > 0F, "Must be greater than 0"); + Preconditions.checkArgument(value > 0F, "Health value (%s) must be greater than 0", value); healthScale = value; scaledHealth = true; updateScaledHealth(); @@ -2044,8 +1986,8 @@ public class CraftPlayer extends CraftHumanEntity implements Player { @Override public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) { - if (data != null && !particle.getDataType().isInstance(data)) { - throw new IllegalArgumentException("data should be " + particle.getDataType() + " got " + data.getClass()); + if (data != null) { + Preconditions.checkArgument(particle.getDataType().isInstance(data), "data (%s) should be %s", data.getClass(), particle.getDataType()); } PacketPlayOutWorldParticles packetplayoutworldparticles = new PacketPlayOutWorldParticles(CraftParticle.toNMS(particle, data), true, (float) x, (float) y, (float) z, (float) offsetX, (float) offsetY, (float) offsetZ, (float) extra, count); getHandle().connection.send(packetplayoutworldparticles); @@ -2087,8 +2029,8 @@ public class CraftPlayer extends CraftHumanEntity implements Player { @Override public void openBook(ItemStack book) { - Validate.isTrue(book != null, "book == null"); - Validate.isTrue(book.getType() == Material.WRITTEN_BOOK, "Book must be Material.WRITTEN_BOOK"); + Preconditions.checkArgument(book != null, "ItemStack cannot be null"); + Preconditions.checkArgument(book.getType() == Material.WRITTEN_BOOK, "ItemStack Material (%s) must be Material.WRITTEN_BOOK", book.getType()); ItemStack hand = getInventory().getItemInMainHand(); getInventory().setItemInMainHand(book); diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownPotion.java b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownPotion.java index 1ba54f2bac..f94b53a9cd 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownPotion.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownPotion.java @@ -1,11 +1,11 @@ package org.bukkit.craftbukkit.entity; +import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import java.util.Collection; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.entity.projectile.EntityPotion; import net.minecraft.world.item.alchemy.PotionUtil; -import org.apache.commons.lang.Validate; import org.bukkit.Material; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.inventory.CraftItemStack; @@ -36,11 +36,8 @@ public class CraftThrownPotion extends CraftThrowableProjectile implements Throw @Override public void setItem(ItemStack item) { - // The ItemStack must not be null. - Validate.notNull(item, "ItemStack cannot be null."); - - // The ItemStack must be a potion. - Validate.isTrue(item.getType() == Material.LINGERING_POTION || item.getType() == Material.SPLASH_POTION, "ItemStack must be a lingering or splash potion. This item stack was " + item.getType() + "."); + Preconditions.checkArgument(item != null, "ItemStack cannot be null"); + Preconditions.checkArgument(item.getType() == Material.LINGERING_POTION || item.getType() == Material.SPLASH_POTION, "ItemStack material must be Material.LINGERING_POTION or Material.SPLASH_POTION but was Material.%s", item.getType()); getHandle().setItem(CraftItemStack.asNMSCopy(item)); } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftTippedArrow.java b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftTippedArrow.java index 425b5b6c53..c5d7ae5ec4 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftTippedArrow.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftTippedArrow.java @@ -1,11 +1,11 @@ package org.bukkit.craftbukkit.entity; +import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import java.util.List; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffectList; import net.minecraft.world.entity.projectile.EntityTippedArrow; -import org.apache.commons.lang.Validate; import org.bukkit.Color; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.potion.CraftPotionUtil; @@ -105,7 +105,7 @@ public class CraftTippedArrow extends CraftArrow implements Arrow { @Override public void setBasePotionData(PotionData data) { - Validate.notNull(data, "PotionData cannot be null"); + Preconditions.checkArgument(data != null, "PotionData cannot be null"); getHandle().setPotionType(CraftPotionUtil.fromBukkit(data)); } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftVillager.java b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftVillager.java index adf6e03747..d3d40af607 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftVillager.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftVillager.java @@ -10,7 +10,6 @@ import net.minecraft.world.entity.npc.EntityVillager; import net.minecraft.world.entity.npc.VillagerProfession; import net.minecraft.world.level.block.BlockBed; import net.minecraft.world.level.block.state.IBlockData; -import org.apache.commons.lang.Validate; import org.bukkit.Location; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.util.CraftLocation; @@ -55,7 +54,7 @@ public class CraftVillager extends CraftAbstractVillager implements Villager { @Override public void setProfession(Profession profession) { - Validate.notNull(profession); + Preconditions.checkArgument(profession != null, "Profession cannot be null"); getHandle().setVillagerData(getHandle().getVillagerData().setProfession(CraftVillager.bukkitToNmsProfession(profession))); } @@ -66,7 +65,7 @@ public class CraftVillager extends CraftAbstractVillager implements Villager { @Override public void setVillagerType(Type type) { - Validate.notNull(type); + Preconditions.checkArgument(type != null, "Type cannot be null"); getHandle().setVillagerData(getHandle().getVillagerData().setType(BuiltInRegistries.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(type.getKey())))); } @@ -77,7 +76,7 @@ public class CraftVillager extends CraftAbstractVillager implements Villager { @Override public void setVillagerLevel(int level) { - Preconditions.checkArgument(1 <= level && level <= 5, "level must be between [1, 5]"); + Preconditions.checkArgument(1 <= level && level <= 5, "level (%s) must be between [1, 5]", level); getHandle().setVillagerData(getHandle().getVillagerData().setLevel(level)); } @@ -89,7 +88,7 @@ public class CraftVillager extends CraftAbstractVillager implements Villager { @Override public void setVillagerExperience(int experience) { - Preconditions.checkArgument(experience >= 0, "Experience must be positive"); + Preconditions.checkArgument(experience >= 0, "Experience (%s) must be positive", experience); getHandle().setVillagerXp(experience); } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftVillagerZombie.java b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftVillagerZombie.java index 9b46e75111..764a5e219a 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftVillagerZombie.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/entity/CraftVillagerZombie.java @@ -2,12 +2,10 @@ package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; import java.util.Locale; -import java.util.UUID; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.MinecraftKey; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.monster.EntityZombieVillager; -import org.apache.commons.lang.Validate; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.craftbukkit.CraftServer; @@ -44,7 +42,7 @@ public class CraftVillagerZombie extends CraftZombie implements ZombieVillager { @Override public void setVillagerProfession(Villager.Profession profession) { - Validate.notNull(profession); + Preconditions.checkArgument(profession != null, "Villager.Profession cannot be null"); getHandle().setVillagerData(getHandle().getVillagerData().setProfession(BuiltInRegistries.VILLAGER_PROFESSION.get(new MinecraftKey(profession.name().toLowerCase(Locale.ROOT))))); } @@ -55,7 +53,7 @@ public class CraftVillagerZombie extends CraftZombie implements ZombieVillager { @Override public void setVillagerType(Villager.Type type) { - Validate.notNull(type); + Preconditions.checkArgument(type != null, "Villager.Type cannot be null"); getHandle().setVillagerData(getHandle().getVillagerData().setType(BuiltInRegistries.VILLAGER_TYPE.get(CraftNamespacedKey.toMinecraft(type.getKey())))); } @@ -79,7 +77,7 @@ public class CraftVillagerZombie extends CraftZombie implements ZombieVillager { getHandle().conversionStarter = null; getHandle().removeEffect(MobEffects.DAMAGE_BOOST, org.bukkit.event.entity.EntityPotionEffectEvent.Cause.CONVERSION); } else { - getHandle().startConverting((UUID) null, time); + getHandle().startConverting(null, time); } } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java b/paper-server/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java index a59a335321..222a92eb85 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java @@ -2,6 +2,7 @@ package org.bukkit.craftbukkit.event; import com.google.common.base.Function; import com.google.common.base.Functions; +import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.mojang.datafixers.util.Either; import java.net.InetAddress; @@ -1610,9 +1611,8 @@ public class CraftEventFactory { PotionEffect bukkitOldEffect = (oldEffect == null) ? null : CraftPotionUtil.toBukkit(oldEffect); PotionEffect bukkitNewEffect = (newEffect == null) ? null : CraftPotionUtil.toBukkit(newEffect); - if (bukkitOldEffect == null && bukkitNewEffect == null) { - throw new IllegalStateException("Old and new potion effect are both null"); - } + Preconditions.checkState(bukkitOldEffect != null, "Old and new potion is null"); + Preconditions.checkState(bukkitNewEffect != null, "New potion effect is null"); EntityPotionEffectEvent event = new EntityPotionEffectEvent((LivingEntity) entity.getBukkitEntity(), bukkitOldEffect, bukkitNewEffect, cause, action, willOverride); Bukkit.getPluginManager().callEvent(event); diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/generator/CraftChunkData.java b/paper-server/src/main/java/org/bukkit/craftbukkit/generator/CraftChunkData.java index cc80893211..1c9f2f1204 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/generator/CraftChunkData.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/generator/CraftChunkData.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.generator; +import com.google.common.base.Preconditions; import java.lang.ref.WeakReference; import net.minecraft.core.BlockPosition; import net.minecraft.world.level.block.Blocks; @@ -38,9 +39,7 @@ public final class CraftChunkData implements ChunkGenerator.ChunkData { public IChunkAccess getHandle() { IChunkAccess access = weakChunk.get(); - if (access == null) { - throw new IllegalStateException("IChunkAccess no longer present, are you using it in a different tick?"); - } + Preconditions.checkState(access != null, "IChunkAccess no longer present, are you using it in a different tick?"); return access; } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/generator/CraftLimitedRegion.java b/paper-server/src/main/java/org/bukkit/craftbukkit/generator/CraftLimitedRegion.java index c9663aafed..4dbfc006b6 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/generator/CraftLimitedRegion.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/generator/CraftLimitedRegion.java @@ -68,9 +68,7 @@ public class CraftLimitedRegion extends CraftRegionAccessor implements LimitedRe public GeneratorAccessSeed getHandle() { GeneratorAccessSeed handle = weakAccess.get(); - if (handle == null) { - throw new IllegalStateException("GeneratorAccessSeed no longer present, are you using it in a different tick?"); - } + Preconditions.checkState(handle != null, "GeneratorAccessSeed no longer present, are you using it in a different tick?"); return handle; } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/help/CommandAliasHelpTopic.java b/paper-server/src/main/java/org/bukkit/craftbukkit/help/CommandAliasHelpTopic.java index 9f2238c9a7..da88fa68d1 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/help/CommandAliasHelpTopic.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/help/CommandAliasHelpTopic.java @@ -1,6 +1,6 @@ package org.bukkit.craftbukkit.help; -import org.apache.commons.lang.Validate; +import com.google.common.base.Preconditions; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.help.HelpMap; @@ -15,12 +15,13 @@ public class CommandAliasHelpTopic extends HelpTopic { this.aliasFor = aliasFor.startsWith("/") ? aliasFor : "/" + aliasFor; this.helpMap = helpMap; this.name = alias.startsWith("/") ? alias : "/" + alias; - Validate.isTrue(!this.name.equals(this.aliasFor), "Command " + this.name + " cannot be alias for itself"); + Preconditions.checkArgument(!this.name.equals(this.aliasFor), "Command %s cannot be alias for itself", this.name); this.shortText = ChatColor.YELLOW + "Alias for " + ChatColor.WHITE + this.aliasFor; } @Override public String getFullText(CommandSender forWho) { + Preconditions.checkArgument(forWho != null, "CommandServer forWho cannot be null"); StringBuilder sb = new StringBuilder(shortText); HelpTopic aliasForTopic = helpMap.getHelpTopic(aliasFor); if (aliasForTopic != null) { @@ -32,6 +33,7 @@ public class CommandAliasHelpTopic extends HelpTopic { @Override public boolean canSee(CommandSender commandSender) { + Preconditions.checkArgument(commandSender != null, "CommandServer cannot be null"); if (amendedPermission == null) { HelpTopic aliasForTopic = helpMap.getHelpTopic(aliasFor); if (aliasForTopic != null) { diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/help/SimpleHelpMap.java b/paper-server/src/main/java/org/bukkit/craftbukkit/help/SimpleHelpMap.java index 2358ba5bdc..a369fd7533 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/help/SimpleHelpMap.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/help/SimpleHelpMap.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.help; +import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Collections2; @@ -223,9 +224,7 @@ public class SimpleHelpMap implements HelpMap { @Override public void registerHelpTopicFactory(Class commandClass, HelpTopicFactory factory) { - if (!Command.class.isAssignableFrom(commandClass) && !CommandExecutor.class.isAssignableFrom(commandClass)) { - throw new IllegalArgumentException("commandClass must implement either Command or CommandExecutor!"); - } + Preconditions.checkArgument(Command.class.isAssignableFrom(commandClass) && CommandExecutor.class.isAssignableFrom(commandClass), "commandClass (%s) must implement either Command or CommandExecutor", commandClass.getName()); topicFactoryMap.put(commandClass, factory); } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventory.java b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventory.java index 93e6a6fcc4..6fa6df14e2 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventory.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventory.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.inventory; +import com.google.common.base.Preconditions; import java.util.HashMap; import java.util.List; import java.util.ListIterator; @@ -21,7 +22,6 @@ import net.minecraft.world.level.block.entity.TileEntityJukeBox; import net.minecraft.world.level.block.entity.TileEntityLectern; import net.minecraft.world.level.block.entity.TileEntityShulkerBox; import net.minecraft.world.level.block.entity.TileEntitySmoker; -import org.apache.commons.lang.Validate; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.craftbukkit.util.CraftLegacy; @@ -84,9 +84,7 @@ public class CraftInventory implements Inventory { @Override public void setContents(ItemStack[] items) { - if (getSize() < items.length) { - throw new IllegalArgumentException("Invalid inventory size; expected " + getSize() + " or less"); - } + Preconditions.checkArgument(getSize() < items.length, "Invalid inventory size (%s); expected %s or less", items.length, getSize()); for (int i = 0; i < getSize(); i++) { if (i >= items.length) { @@ -104,7 +102,7 @@ public class CraftInventory implements Inventory { @Override public boolean contains(Material material) { - Validate.notNull(material, "Material cannot be null"); + Preconditions.checkArgument(material != null, "Material cannot be null"); material = CraftLegacy.fromLegacy(material); for (ItemStack item : getStorageContents()) { if (item != null && item.getType() == material) { @@ -129,7 +127,7 @@ public class CraftInventory implements Inventory { @Override public boolean contains(Material material, int amount) { - Validate.notNull(material, "Material cannot be null"); + Preconditions.checkArgument(material != null, "Material cannot be null"); material = CraftLegacy.fromLegacy(material); if (amount <= 0) { return true; @@ -178,9 +176,9 @@ public class CraftInventory implements Inventory { @Override public HashMap all(Material material) { - Validate.notNull(material, "Material cannot be null"); + Preconditions.checkArgument(material != null, "Material cannot be null"); material = CraftLegacy.fromLegacy(material); - HashMap slots = new HashMap(); + HashMap slots = new HashMap<>(); ItemStack[] inventory = getStorageContents(); for (int i = 0; i < inventory.length; i++) { @@ -194,7 +192,7 @@ public class CraftInventory implements Inventory { @Override public HashMap all(ItemStack item) { - HashMap slots = new HashMap(); + HashMap slots = new HashMap<>(); if (item != null) { ItemStack[] inventory = getStorageContents(); for (int i = 0; i < inventory.length; i++) { @@ -208,7 +206,7 @@ public class CraftInventory implements Inventory { @Override public int first(Material material) { - Validate.notNull(material, "Material cannot be null"); + Preconditions.checkArgument(material != null, "Material cannot be null"); material = CraftLegacy.fromLegacy(material); ItemStack[] inventory = getStorageContents(); for (int i = 0; i < inventory.length; i++) { @@ -257,7 +255,7 @@ public class CraftInventory implements Inventory { } public int firstPartial(Material material) { - Validate.notNull(material, "Material cannot be null"); + Preconditions.checkArgument(material != null, "Material cannot be null"); material = CraftLegacy.fromLegacy(material); ItemStack[] inventory = getStorageContents(); for (int i = 0; i < inventory.length; i++) { @@ -286,8 +284,8 @@ public class CraftInventory implements Inventory { @Override public HashMap addItem(ItemStack... items) { - Validate.noNullElements(items, "Item cannot be null"); - HashMap leftover = new HashMap(); + Preconditions.checkArgument(items != null, "items cannot be null"); + HashMap leftover = new HashMap<>(); /* TODO: some optimization * - Create a 'firstPartial' with a 'fromIndex' @@ -297,6 +295,7 @@ public class CraftInventory implements Inventory { for (int i = 0; i < items.length; i++) { ItemStack item = items[i]; + Preconditions.checkArgument(item != null, "ItemStack cannot be null"); while (true) { // Do we already have a stack of it? int firstPartial = firstPartial(item); @@ -352,13 +351,14 @@ public class CraftInventory implements Inventory { @Override public HashMap removeItem(ItemStack... items) { - Validate.notNull(items, "Items cannot be null"); + Preconditions.checkArgument(items != null, "items cannot be null"); HashMap leftover = new HashMap(); // TODO: optimization for (int i = 0; i < items.length; i++) { ItemStack item = items[i]; + Preconditions.checkArgument(item != null, "ItemStack cannot be null"); int toDelete = item.getAmount(); while (true) { @@ -400,7 +400,7 @@ public class CraftInventory implements Inventory { @Override public void remove(Material material) { - Validate.notNull(material, "Material cannot be null"); + Preconditions.checkArgument(material != null, "Material cannot be null"); material = CraftLegacy.fromLegacy(material); ItemStack[] items = getStorageContents(); for (int i = 0; i < items.length; i++) { diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCrafting.java b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCrafting.java index ed33581cf3..154f1837b1 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCrafting.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCrafting.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.inventory; +import com.google.common.base.Preconditions; import java.util.Arrays; import java.util.List; import net.minecraft.world.IInventory; @@ -31,9 +32,7 @@ public class CraftInventoryCrafting extends CraftInventory implements CraftingIn @Override public void setContents(ItemStack[] items) { - if (getSize() > items.length) { - throw new IllegalArgumentException("Invalid inventory size; expected " + getSize() + " or less"); - } + Preconditions.checkArgument(getSize() <= items.length, "Invalid inventory size (%s); expected %s or less", items.length, getSize()); setContents(items[0], Arrays.copyOfRange(items, 1, items.length)); } @@ -97,9 +96,7 @@ public class CraftInventoryCrafting extends CraftInventory implements CraftingIn @Override public void setMatrix(ItemStack[] contents) { - if (getMatrixInventory().getContainerSize() > contents.length) { - throw new IllegalArgumentException("Invalid inventory size; expected " + getMatrixInventory().getContainerSize() + " or less"); - } + Preconditions.checkArgument(getMatrixInventory().getContainerSize() <= contents.length, "Invalid inventory size (%s); expected %s or less", contents.length, getMatrixInventory().getContainerSize()); for (int i = 0; i < getMatrixInventory().getContainerSize(); i++) { if (i < contents.length) { diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCustom.java b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCustom.java index 45f2a229f0..38e2eae5aa 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCustom.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCustom.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.inventory; +import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -7,7 +8,6 @@ import net.minecraft.core.NonNullList; import net.minecraft.world.IInventory; import net.minecraft.world.entity.player.EntityHuman; import net.minecraft.world.item.ItemStack; -import org.apache.commons.lang.Validate; import org.bukkit.Location; import org.bukkit.craftbukkit.entity.CraftHumanEntity; import org.bukkit.entity.HumanEntity; @@ -54,7 +54,7 @@ public class CraftInventoryCustom extends CraftInventory { } public MinecraftInventory(InventoryHolder owner, int size, String title) { - Validate.notNull(title, "Title cannot be null"); + Preconditions.checkArgument(title != null, "title cannot be null"); this.items = NonNullList.withSize(size, ItemStack.EMPTY); this.title = title; this.viewers = new ArrayList(); diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryDoubleChest.java b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryDoubleChest.java index b6fa37e798..3ccfb1fbee 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryDoubleChest.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryDoubleChest.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.inventory; +import com.google.common.base.Preconditions; import net.minecraft.world.ITileInventory; import net.minecraft.world.InventoryLargeChest; import net.minecraft.world.level.block.BlockChest; @@ -47,9 +48,7 @@ public class CraftInventoryDoubleChest extends CraftInventory implements DoubleC @Override public void setContents(ItemStack[] items) { - if (getInventory().getContainerSize() < items.length) { - throw new IllegalArgumentException("Invalid inventory size; expected " + getInventory().getContainerSize() + " or less"); - } + Preconditions.checkArgument(getInventory().getContainerSize() >= items.length, "Invalid inventory size (%s); expected %s or less", items.length, getInventory().getContainerSize()); ItemStack[] leftItems = new ItemStack[left.getSize()], rightItems = new ItemStack[right.getSize()]; System.arraycopy(items, 0, leftItems, 0, Math.min(left.getSize(), items.length)); left.setContents(leftItems); diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryPlayer.java b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryPlayer.java index 55f17e3aa9..4479cdf926 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryPlayer.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryPlayer.java @@ -5,7 +5,6 @@ import net.minecraft.network.protocol.game.PacketPlayOutHeldItemSlot; import net.minecraft.network.protocol.game.PacketPlayOutSetSlot; import net.minecraft.server.level.EntityPlayer; import net.minecraft.world.entity.player.PlayerInventory; -import org.apache.commons.lang.Validate; import org.bukkit.craftbukkit.entity.CraftPlayer; import org.bukkit.entity.HumanEntity; import org.bukkit.inventory.EntityEquipment; @@ -175,7 +174,7 @@ public class CraftInventoryPlayer extends CraftInventory implements org.bukkit.i @Override public void setHeldItemSlot(int slot) { - Validate.isTrue(slot >= 0 && slot < PlayerInventory.getSelectionSize(), "Slot is not between 0 and 8 inclusive"); + Preconditions.checkArgument(slot >= 0 && slot < PlayerInventory.getSelectionSize(), "Slot (%s) is not between 0 and %s inclusive", slot, PlayerInventory.getSelectionSize() - 1); this.getInventory().selected = slot; ((CraftPlayer) this.getHolder()).getHandle().connection.send(new PacketPlayOutHeldItemSlot(slot)); } @@ -249,7 +248,7 @@ public class CraftInventoryPlayer extends CraftInventory implements org.bukkit.i if (items == null) { items = new ItemStack[length]; } - Preconditions.checkArgument(items.length <= length, "items.length must be < %s", length); + Preconditions.checkArgument(items.length <= length, "items.length must be <= %s", length); for (int i = 0; i < length; i++) { if (i >= items.length) { diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java index 4b721bfcd2..f7b9155864 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java @@ -1,13 +1,12 @@ package org.bukkit.craftbukkit.inventory; +import com.google.common.base.Preconditions; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; import net.minecraft.commands.arguments.item.ArgumentParserItemStack; -import net.minecraft.core.HolderLookup; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.item.Item; -import org.apache.commons.lang.Validate; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.configuration.serialization.ConfigurationSerialization; @@ -42,16 +41,15 @@ public final class CraftItemFactory implements ItemFactory { if (type == null || meta == null) { return false; } - if (!(meta instanceof CraftMetaItem)) { - throw new IllegalArgumentException("Meta of " + meta.getClass().toString() + " not created by " + CraftItemFactory.class.getName()); - } + + Preconditions.checkArgument(meta instanceof CraftMetaItem, "Meta of %s not created by %s", meta.getClass().toString(), CraftItemFactory.class.getName()); return ((CraftMetaItem) meta).applicableTo(type); } @Override public ItemMeta getItemMeta(Material material) { - Validate.notNull(material, "Material cannot be null"); + Preconditions.checkArgument(material != null, "Material cannot be null"); return getItemMeta(material, null); } @@ -366,16 +364,15 @@ public final class CraftItemFactory implements ItemFactory { if (meta1 == meta2) { return true; } - if (meta1 != null && !(meta1 instanceof CraftMetaItem)) { - throw new IllegalArgumentException("First meta of " + meta1.getClass().getName() + " does not belong to " + CraftItemFactory.class.getName()); - } - if (meta2 != null && !(meta2 instanceof CraftMetaItem)) { - throw new IllegalArgumentException("Second meta " + meta2.getClass().getName() + " does not belong to " + CraftItemFactory.class.getName()); - } - if (meta1 == null) { + + if (meta1 != null) { + Preconditions.checkArgument(meta1 instanceof CraftMetaItem, "First meta of %s does not belong to %s", meta1.getClass().getName(), CraftItemFactory.class.getName()); + } else { return ((CraftMetaItem) meta2).isEmpty(); } - if (meta2 == null) { + if (meta2 != null) { + Preconditions.checkArgument(meta2 instanceof CraftMetaItem, "Second meta of %s does not belong to %s", meta2.getClass().getName(), CraftItemFactory.class.getName()); + } else { return ((CraftMetaItem) meta1).isEmpty(); } @@ -401,16 +398,14 @@ public final class CraftItemFactory implements ItemFactory { @Override public ItemMeta asMetaFor(ItemMeta meta, ItemStack stack) { - Validate.notNull(stack, "Stack cannot be null"); + Preconditions.checkArgument(stack != null, "ItemStack stack cannot be null"); return asMetaFor(meta, stack.getType()); } @Override public ItemMeta asMetaFor(ItemMeta meta, Material material) { - Validate.notNull(material, "Material cannot be null"); - if (!(meta instanceof CraftMetaItem)) { - throw new IllegalArgumentException("Meta of " + (meta != null ? meta.getClass().toString() : "null") + " not created by " + CraftItemFactory.class.getName()); - } + Preconditions.checkArgument(material != null, "Material cannot be null"); + Preconditions.checkArgument(meta instanceof CraftMetaItem, "ItemMeta of %s not created by %s", (meta != null ? meta.getClass().toString() : "null"), CraftItemFactory.class.getName()); return getItemMeta(material, (CraftMetaItem) meta); } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java index dc8c1c65fd..c0857787b9 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java @@ -1,13 +1,13 @@ package org.bukkit.craftbukkit.inventory; import static org.bukkit.craftbukkit.inventory.CraftMetaItem.*; +import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import java.util.Map; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.world.item.Item; import net.minecraft.world.item.enchantment.EnchantmentManager; -import org.apache.commons.lang.Validate; import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.configuration.serialization.DelegateDeserialization; @@ -176,7 +176,7 @@ public final class CraftItemStack extends ItemStack { @Override public void addUnsafeEnchantment(Enchantment ench, int level) { - Validate.notNull(ench, "Cannot add null enchantment"); + Preconditions.checkArgument(ench != null, "Enchantment cannot be null"); if (!makeTag(handle)) { return; @@ -221,7 +221,7 @@ public final class CraftItemStack extends ItemStack { @Override public int getEnchantmentLevel(Enchantment ench) { - Validate.notNull(ench, "Cannot find null enchantment"); + Preconditions.checkArgument(ench != null, "Enchantment cannot be null"); if (handle == null) { return 0; } @@ -230,7 +230,7 @@ public final class CraftItemStack extends ItemStack { @Override public int removeEnchantment(Enchantment ench) { - Validate.notNull(ench, "Cannot remove null enchantment"); + Preconditions.checkArgument(ench != null, "Enchantment cannot be null"); NBTTagList list = getEnchantmentList(handle), listCopy; if (list == null) { diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantCustom.java b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantCustom.java index e859d9e225..87325cc415 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantCustom.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantCustom.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.inventory; +import com.google.common.base.Preconditions; import net.minecraft.network.chat.IChatBaseComponent; import net.minecraft.sounds.SoundEffect; import net.minecraft.sounds.SoundEffects; @@ -8,8 +9,6 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.trading.IMerchant; import net.minecraft.world.item.trading.MerchantRecipe; import net.minecraft.world.item.trading.MerchantRecipeList; -import net.minecraft.world.level.World; -import org.apache.commons.lang.Validate; import org.bukkit.craftbukkit.util.CraftChatMessage; public class CraftMerchantCustom extends CraftMerchant { @@ -37,7 +36,7 @@ public class CraftMerchantCustom extends CraftMerchant { protected CraftMerchant craftMerchant; public MinecraftMerchant(String title) { - Validate.notNull(title, "Title cannot be null"); + Preconditions.checkArgument(title != null, "Title cannot be null"); this.title = CraftChatMessage.fromString(title)[0]; } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBanner.java b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBanner.java index 3e218c6ea3..6dbd000d75 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBanner.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBanner.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.inventory; +import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; @@ -114,9 +115,7 @@ public class CraftMetaBanner extends CraftMetaItem implements BannerMeta { } for (Object obj : rawPatternList) { - if (!(obj instanceof Pattern)) { - throw new IllegalArgumentException("Object in pattern list is not valid. " + obj.getClass()); - } + Preconditions.checkArgument(obj instanceof Pattern, "Object (%s) in pattern list is not valid", obj.getClass()); addPattern((Pattern) obj); } } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBlockState.java b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBlockState.java index 6b70017307..ff9e55da1c 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBlockState.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBlockState.java @@ -1,13 +1,13 @@ package org.bukkit.craftbukkit.inventory; import com.google.common.base.Objects; +import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import java.util.Map; import java.util.Set; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; -import org.apache.commons.lang.Validate; import org.bukkit.Material; import org.bukkit.block.BlockState; import org.bukkit.configuration.serialization.DelegateDeserialization; @@ -274,11 +274,11 @@ public class CraftMetaBlockState extends CraftMetaItem implements BlockStateMeta @Override public void setBlockState(BlockState blockState) { - Validate.notNull(blockState, "blockState must not be null"); + Preconditions.checkArgument(blockState != null, "blockState must not be null"); Material stateMaterial = (material != Material.SHIELD) ? material : shieldToBannerHack(blockEntityTag); Class blockStateType = CraftBlockStates.getBlockStateType(stateMaterial); - Validate.isTrue(blockStateType == blockState.getClass() && blockState instanceof CraftBlockEntityState, "Invalid blockState for " + material); + Preconditions.checkArgument(blockStateType == blockState.getClass() && blockState instanceof CraftBlockEntityState, "Invalid blockState for " + material); blockEntityTag = ((CraftBlockEntityState) blockState).getSnapshotNBT(); // Set shield base diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBook.java b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBook.java index 8615d7bcfb..d522ff8813 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBook.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBook.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.inventory; +import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.Lists; @@ -12,7 +13,6 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; import net.minecraft.network.chat.IChatBaseComponent; -import org.apache.commons.lang.Validate; import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.craftbukkit.inventory.CraftMetaItem.SerializableMeta; @@ -256,16 +256,14 @@ public class CraftMetaBook extends CraftMetaItem implements BookMeta { @Override public String getPage(final int page) { - Validate.isTrue(isValidPage(page), "Invalid page number"); + Preconditions.checkArgument(isValidPage(page), "Invalid page number (%s)", page); // assert: pages != null return convertDataToPlainPage(pages.get(page - 1)); } @Override public void setPage(final int page, final String text) { - if (!isValidPage(page)) { - throw new IllegalArgumentException("Invalid page number " + page + "/" + getPageCount()); - } + Preconditions.checkArgument(isValidPage(page), "Invalid page number (%s/%s)", page, getPageCount()); // assert: pages != null String newText = validatePage(text); @@ -379,8 +377,7 @@ public class CraftMetaBook extends CraftMetaItem implements BookMeta { if (!super.equalsCommon(meta)) { return false; } - if (meta instanceof CraftMetaBook) { - CraftMetaBook that = (CraftMetaBook) meta; + if (meta instanceof CraftMetaBook that) { return (hasTitle() ? that.hasTitle() && this.title.equals(that.title) : !that.hasTitle()) && (hasAuthor() ? that.hasAuthor() && this.author.equals(that.author) : !that.hasAuthor()) diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaFirework.java b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaFirework.java index 7d2be3c48a..0b9fdd563f 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaFirework.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaFirework.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.inventory; +import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap.Builder; import java.util.ArrayList; @@ -8,7 +9,6 @@ import java.util.List; import java.util.Map; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; -import org.apache.commons.lang.Validate; import org.bukkit.Color; import org.bukkit.FireworkEffect; import org.bukkit.FireworkEffect.Type; @@ -58,16 +58,14 @@ class CraftMetaFirework extends CraftMetaItem implements FireworkMeta { CraftMetaFirework(CraftMetaItem meta) { super(meta); - if (!(meta instanceof CraftMetaFirework)) { + if (!(meta instanceof CraftMetaFirework that)) { return; } - CraftMetaFirework that = (CraftMetaFirework) meta; - this.power = that.power; if (that.hasEffects()) { - this.effects = new ArrayList(that.effects); + this.effects = new ArrayList<>(that.effects); } } @@ -200,15 +198,12 @@ class CraftMetaFirework extends CraftMetaItem implements FireworkMeta { List effects = this.effects; if (effects == null) { - effects = this.effects = new ArrayList(); + effects = this.effects = new ArrayList<>(); } for (Object obj : collection) { - if (obj instanceof FireworkEffect) { - effects.add((FireworkEffect) obj); - } else { - throw new IllegalArgumentException(obj + " in " + collection + " is not a FireworkEffect"); - } + Preconditions.checkArgument(obj instanceof FireworkEffect, "%s in %s is not a FireworkEffect", obj, collection); + effects.add((FireworkEffect) obj); } } @@ -276,8 +271,7 @@ class CraftMetaFirework extends CraftMetaItem implements FireworkMeta { return false; } - if (meta instanceof CraftMetaFirework) { - CraftMetaFirework that = (CraftMetaFirework) meta; + if (meta instanceof CraftMetaFirework that) { return (hasPower() ? that.hasPower() && this.power == that.power : !that.hasPower()) && (hasEffects() ? that.hasEffects() && this.effects.equals(that.effects) : !that.hasEffects()); @@ -332,7 +326,7 @@ class CraftMetaFirework extends CraftMetaItem implements FireworkMeta { @Override public void addEffect(FireworkEffect effect) { - Validate.notNull(effect, "Effect cannot be null"); + Preconditions.checkArgument(effect != null, "FireworkEffect cannot be null"); if (this.effects == null) { this.effects = new ArrayList(); } @@ -341,7 +335,7 @@ class CraftMetaFirework extends CraftMetaItem implements FireworkMeta { @Override public void addEffects(FireworkEffect... effects) { - Validate.notNull(effects, "Effects cannot be null"); + Preconditions.checkArgument(effects != null, "effects cannot be null"); if (effects.length == 0) { return; } @@ -352,14 +346,14 @@ class CraftMetaFirework extends CraftMetaItem implements FireworkMeta { } for (FireworkEffect effect : effects) { - Validate.notNull(effect, "Effect cannot be null"); + Preconditions.checkArgument(effect != null, "effects cannot contain null FireworkEffect"); list.add(effect); } } @Override public void addEffects(Iterable effects) { - Validate.notNull(effects, "Effects cannot be null"); + Preconditions.checkArgument(effects != null, "effects cannot be null"); safelyAddEffects(effects); } @@ -394,8 +388,8 @@ class CraftMetaFirework extends CraftMetaItem implements FireworkMeta { @Override public void setPower(int power) { - Validate.isTrue(power >= 0, "Power cannot be less than zero: ", power); - Validate.isTrue(power < 0x80, "Power cannot be more than 127: ", power); + Preconditions.checkArgument(power >= 0, "power cannot be less than zero: %s", power); + Preconditions.checkArgument(power < 0x80, "power cannot be more than 127: %s", power); this.power = power; } } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java index 2d10c1c02b..a584c1a03c 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java @@ -46,7 +46,6 @@ import net.minecraft.network.chat.IChatBaseComponent; import net.minecraft.world.entity.EnumItemSlot; import net.minecraft.world.item.ItemBlock; import net.minecraft.world.level.block.state.IBlockData; -import org.apache.commons.lang.Validate; import org.apache.commons.lang3.EnumUtils; import org.bukkit.Material; import org.bukkit.attribute.Attribute; @@ -180,7 +179,7 @@ class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta { } public static ItemMeta deserialize(Map map) throws Throwable { - Validate.notNull(map, "Cannot deserialize null map"); + Preconditions.checkArgument(map != null, "Cannot deserialize null map"); String type = getString(map, TYPE_FIELD, false); Constructor constructor = constructorMap.get(type); @@ -789,13 +788,13 @@ class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta { @Override public boolean hasEnchant(Enchantment ench) { - Validate.notNull(ench, "Enchantment cannot be null"); + Preconditions.checkArgument(ench != null, "Enchantment cannot be null"); return hasEnchants() && enchantments.containsKey(ench); } @Override public int getEnchantLevel(Enchantment ench) { - Validate.notNull(ench, "Enchantment cannot be null"); + Preconditions.checkArgument(ench != null, "Enchantment cannot be null"); Integer level = hasEnchants() ? enchantments.get(ench) : null; if (level == null) { return 0; @@ -810,7 +809,7 @@ class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta { @Override public boolean addEnchant(Enchantment ench, int level, boolean ignoreRestrictions) { - Validate.notNull(ench, "Enchantment cannot be null"); + Preconditions.checkArgument(ench != null, "Enchantment cannot be null"); if (enchantments == null) { enchantments = new LinkedHashMap(4); } @@ -824,7 +823,7 @@ class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta { @Override public boolean removeEnchant(Enchantment ench) { - Validate.notNull(ench, "Enchantment cannot be null"); + Preconditions.checkArgument(ench != null, "Enchantment cannot be null"); return hasEnchants() && enchantments.remove(ench) != null; } @@ -1330,9 +1329,7 @@ class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta { for (Object object : addFrom) { if (!(object instanceof String)) { - if (object != null) { - throw new IllegalArgumentException(addFrom + " cannot contain non-string " + object.getClass().getName()); - } + Preconditions.checkArgument(object == null, "%s cannot contain non-string %s", addFrom, object.getClass().getName()); addTo.add(CraftChatMessage.toJSON(IChatBaseComponent.empty())); } else { diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaPotion.java b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaPotion.java index 2c8d270c8b..96cad37f19 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaPotion.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaPotion.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.inventory; +import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.Sets; @@ -10,7 +11,6 @@ import java.util.Map; import java.util.Set; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; -import org.apache.commons.lang.Validate; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; @@ -51,14 +51,13 @@ class CraftMetaPotion extends CraftMetaItem implements PotionMeta { CraftMetaPotion(CraftMetaItem meta) { super(meta); - if (!(meta instanceof CraftMetaPotion)) { + if (!(meta instanceof CraftMetaPotion potionMeta)) { return; } - CraftMetaPotion potionMeta = (CraftMetaPotion) meta; this.type = potionMeta.type; this.color = potionMeta.color; if (potionMeta.hasCustomEffects()) { - this.customEffects = new ArrayList(potionMeta.customEffects); + this.customEffects = new ArrayList<>(potionMeta.customEffects); } } @@ -77,7 +76,7 @@ class CraftMetaPotion extends CraftMetaItem implements PotionMeta { if (tag.contains(POTION_EFFECTS.NBT)) { NBTTagList list = tag.getList(POTION_EFFECTS.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND); int length = list.size(); - customEffects = new ArrayList(length); + customEffects = new ArrayList<>(length); for (int i = 0; i < length; i++) { NBTTagCompound effect = list.getCompound(i); @@ -112,9 +111,7 @@ class CraftMetaPotion extends CraftMetaItem implements PotionMeta { } for (Object obj : rawEffectList) { - if (!(obj instanceof PotionEffect)) { - throw new IllegalArgumentException("Object in effect list is not valid. " + obj.getClass()); - } + Preconditions.checkArgument(obj instanceof PotionEffect, "Object (%s) in effect list is not valid", obj.getClass()); addCustomEffect((PotionEffect) obj, true); } } @@ -165,14 +162,14 @@ class CraftMetaPotion extends CraftMetaItem implements PotionMeta { CraftMetaPotion clone = (CraftMetaPotion) super.clone(); clone.type = type; if (this.customEffects != null) { - clone.customEffects = new ArrayList(this.customEffects); + clone.customEffects = new ArrayList<>(this.customEffects); } return clone; } @Override public void setBasePotionData(PotionData data) { - Validate.notNull(data, "PotionData cannot be null"); + Preconditions.checkArgument(data != null, "PotionData cannot be null"); this.type = data; } @@ -196,7 +193,7 @@ class CraftMetaPotion extends CraftMetaItem implements PotionMeta { @Override public boolean addCustomEffect(PotionEffect effect, boolean overwrite) { - Validate.notNull(effect, "Potion effect must not be null"); + Preconditions.checkArgument(effect != null, "Potion effect cannot be null"); int index = indexOfEffect(effect.getType()); if (index != -1) { @@ -212,7 +209,7 @@ class CraftMetaPotion extends CraftMetaItem implements PotionMeta { } } else { if (customEffects == null) { - customEffects = new ArrayList(); + customEffects = new ArrayList<>(); } customEffects.add(effect); return true; @@ -221,7 +218,7 @@ class CraftMetaPotion extends CraftMetaItem implements PotionMeta { @Override public boolean removeCustomEffect(PotionEffectType type) { - Validate.notNull(type, "Potion effect type must not be null"); + Preconditions.checkArgument(type != null, "Potion effect type cannot be null"); if (!hasCustomEffects()) { return false; @@ -244,13 +241,13 @@ class CraftMetaPotion extends CraftMetaItem implements PotionMeta { @Override public boolean hasCustomEffect(PotionEffectType type) { - Validate.notNull(type, "Potion effect type must not be null"); + Preconditions.checkArgument(type != null, "Potion effect type cannot be null"); return indexOfEffect(type) != -1; } @Override public boolean setMainEffect(PotionEffectType type) { - Validate.notNull(type, "Potion effect type must not be null"); + Preconditions.checkArgument(type != null, "Potion effect type cannot be null"); int index = indexOfEffect(type); if (index == -1 || index == 0) { return false; diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSuspiciousStew.java b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSuspiciousStew.java index e403a4c010..269fe8a680 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSuspiciousStew.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSuspiciousStew.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.inventory; +import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap.Builder; import java.util.ArrayList; @@ -8,11 +9,8 @@ import java.util.List; import java.util.Map; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; -import org.apache.commons.lang.Validate; import org.bukkit.Material; import org.bukkit.configuration.serialization.DelegateDeserialization; -import org.bukkit.craftbukkit.inventory.CraftMetaItem.ItemMetaKey; -import org.bukkit.craftbukkit.inventory.CraftMetaItem.SerializableMeta; import org.bukkit.craftbukkit.util.CraftMagicNumbers; import org.bukkit.inventory.meta.SuspiciousStewMeta; import org.bukkit.potion.PotionEffect; @@ -29,12 +27,11 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious CraftMetaSuspiciousStew(CraftMetaItem meta) { super(meta); - if (!(meta instanceof CraftMetaSuspiciousStew)) { + if (!(meta instanceof CraftMetaSuspiciousStew stewMeta)) { return; } - CraftMetaSuspiciousStew stewMeta = ((CraftMetaSuspiciousStew) meta); if (stewMeta.hasCustomEffects()) { - this.customEffects = new ArrayList(stewMeta.customEffects); + this.customEffects = new ArrayList<>(stewMeta.customEffects); } } @@ -43,7 +40,7 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious if (tag.contains(EFFECTS.NBT)) { NBTTagList list = tag.getList(EFFECTS.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND); int length = list.size(); - customEffects = new ArrayList(length); + customEffects = new ArrayList<>(length); for (int i = 0; i < length; i++) { NBTTagCompound effect = list.getCompound(i); @@ -66,9 +63,7 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious } for (Object obj : rawEffectList) { - if (!(obj instanceof PotionEffect)) { - throw new IllegalArgumentException("Object in effect list is not valid. " + obj.getClass()); - } + Preconditions.checkArgument(obj instanceof PotionEffect, "Object (%s) in effect list is not valid", obj.getClass()); addCustomEffect((PotionEffect) obj, true); } } @@ -108,7 +103,7 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious public CraftMetaSuspiciousStew clone() { CraftMetaSuspiciousStew clone = ((CraftMetaSuspiciousStew) super.clone()); if (this.customEffects != null) { - clone.customEffects = new ArrayList(this.customEffects); + clone.customEffects = new ArrayList<>(this.customEffects); } return clone; } @@ -128,7 +123,7 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious @Override public boolean addCustomEffect(PotionEffect effect, boolean overwrite) { - Validate.notNull(effect, "Potion effect must not be null"); + Preconditions.checkArgument(effect != null, "Potion effect cannot be null"); int index = indexOfEffect(effect.getType()); if (index != -1) { @@ -144,7 +139,7 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious } } else { if (customEffects == null) { - customEffects = new ArrayList(); + customEffects = new ArrayList<>(); } customEffects.add(effect); return true; @@ -153,7 +148,7 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious @Override public boolean removeCustomEffect(PotionEffectType type) { - Validate.notNull(type, "Potion effect type must not be null"); + Preconditions.checkArgument(type != null, "Potion effect type cannot be null"); if (!hasCustomEffects()) { return false; @@ -176,7 +171,7 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious @Override public boolean hasCustomEffect(PotionEffectType type) { - Validate.notNull(type, "Potion effect type must not be null"); + Preconditions.checkArgument(type != null, "Potion effect type cannot be null"); return indexOfEffect(type) != -1; } @@ -215,9 +210,7 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious if (!super.equalsCommon(meta)) { return false; } - if (meta instanceof CraftMetaSuspiciousStew) { - CraftMetaSuspiciousStew that = (CraftMetaSuspiciousStew) meta; - + if (meta instanceof CraftMetaSuspiciousStew that) { return (this.hasCustomEffects() ? that.hasCustomEffects() && this.customEffects.equals(that.customEffects) : !that.hasCustomEffects()); } return true; diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftRecipe.java b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftRecipe.java index 6c1641b850..16f3a87706 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftRecipe.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftRecipe.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.inventory; +import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.List; import net.minecraft.world.item.crafting.RecipeItemStack; @@ -29,8 +30,8 @@ public interface CraftRecipe extends Recipe { } stack.getItems(); - if (requireNotEmpty && stack.itemStacks.length == 0) { - throw new IllegalArgumentException("Recipe requires at least one non-air choice!"); + if (requireNotEmpty) { + Preconditions.checkArgument(stack.itemStacks.length != 0, "Recipe requires at least one non-air choice"); } return stack; diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/InventoryIterator.java b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/InventoryIterator.java index de558eef3f..10dec4165c 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/InventoryIterator.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/InventoryIterator.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.inventory; +import com.google.common.base.Preconditions; import java.util.ListIterator; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; @@ -53,9 +54,7 @@ public class InventoryIterator implements ListIterator { @Override public void set(ItemStack item) { - if (lastDirection == null) { - throw new IllegalStateException("No current item!"); - } + Preconditions.checkState(lastDirection != null, "No current item!"); int i = lastDirection ? nextIndex - 1 : nextIndex; inventory.setItem(i, item); } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/RecipeIterator.java b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/RecipeIterator.java index e4598a65b8..e1e1c1199b 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/RecipeIterator.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/RecipeIterator.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.inventory; +import com.google.common.base.Preconditions; import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; import java.util.Iterator; import java.util.Map; @@ -43,10 +44,7 @@ public class RecipeIterator implements Iterator { @Override public void remove() { - if (current == null) { - throw new IllegalStateException("next() not yet called"); - } - + Preconditions.checkState(current != null, "next() not yet called"); current.remove(); } } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedContainerTagType.java b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedContainerTagType.java index b2d113b483..3df2876b02 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedContainerTagType.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/inventory/tags/DeprecatedContainerTagType.java @@ -1,6 +1,6 @@ package org.bukkit.craftbukkit.inventory.tags; -import org.apache.commons.lang3.Validate; +import com.google.common.base.Preconditions; import org.bukkit.craftbukkit.persistence.CraftPersistentDataContainer; import org.bukkit.inventory.meta.tags.CustomItemTagContainer; import org.bukkit.inventory.meta.tags.ItemTagType; @@ -29,11 +29,11 @@ public final class DeprecatedContainerTagType implements PersistentDataType

implements PersistentDataType

= 0) { - try { - color = Byte.parseByte(text.substring(i + 1, j)); - i = j; - continue; - } catch (NumberFormatException ex) { - } + Preconditions.checkArgument(j >= 0, "text (%s) unterminated color string", text); + try { + color = Byte.parseByte(text.substring(i + 1, j)); + i = j; + continue; + } catch (NumberFormatException ex) { } - throw new IllegalArgumentException("Text contains unterminated color string"); } CharacterSprite sprite = font.getChar(text.charAt(i)); diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/map/CraftMapView.java b/paper-server/src/main/java/org/bukkit/craftbukkit/map/CraftMapView.java index 33255728d8..c291e30939 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/map/CraftMapView.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/map/CraftMapView.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.map; +import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -16,7 +17,6 @@ import org.bukkit.craftbukkit.CraftWorld; import org.bukkit.craftbukkit.entity.CraftPlayer; import org.bukkit.map.MapRenderer; import org.bukkit.map.MapView; -import org.bukkit.map.MapView.Scale; public final class CraftMapView implements MapView { @@ -33,14 +33,11 @@ public final class CraftMapView implements MapView { @Override public int getId() { String text = worldMap.id; - if (text.startsWith("map_")) { - try { - return Integer.parseInt(text.substring("map_".length())); - } catch (NumberFormatException ex) { - throw new IllegalStateException("Map has non-numeric ID"); - } - } else { - throw new IllegalStateException("Map has invalid ID"); + Preconditions.checkState(text.startsWith("map_"), "Map has a invalid ID"); + try { + return Integer.parseInt(text.substring("map_".length())); + } catch (NumberFormatException ex) { + throw new IllegalStateException("Map has non-numeric ID"); } } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/metadata/BlockMetadataStore.java b/paper-server/src/main/java/org/bukkit/craftbukkit/metadata/BlockMetadataStore.java index 93681b52dd..ae2c85dbba 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/metadata/BlockMetadataStore.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/metadata/BlockMetadataStore.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.metadata; +import com.google.common.base.Preconditions; import java.util.List; import org.bukkit.World; import org.bukkit.block.Block; @@ -42,11 +43,8 @@ public class BlockMetadataStore extends MetadataStoreBase implements Meta */ @Override public List getMetadata(Block block, String metadataKey) { - if (block.getWorld() == owningWorld) { - return super.getMetadata(block, metadataKey); - } else { - throw new IllegalArgumentException("Block does not belong to world " + owningWorld.getName()); - } + Preconditions.checkArgument(block.getWorld() == this.owningWorld, "Block does not belong to world %s", owningWorld.getName()); + return super.getMetadata(block, metadataKey); } /** @@ -56,11 +54,8 @@ public class BlockMetadataStore extends MetadataStoreBase implements Meta */ @Override public boolean hasMetadata(Block block, String metadataKey) { - if (block.getWorld() == owningWorld) { - return super.hasMetadata(block, metadataKey); - } else { - throw new IllegalArgumentException("Block does not belong to world " + owningWorld.getName()); - } + Preconditions.checkArgument(block.getWorld() == this.owningWorld, "Block does not belong to world %s", owningWorld.getName()); + return super.hasMetadata(block, metadataKey); } /** @@ -70,11 +65,8 @@ public class BlockMetadataStore extends MetadataStoreBase implements Meta */ @Override public void removeMetadata(Block block, String metadataKey, Plugin owningPlugin) { - if (block.getWorld() == owningWorld) { - super.removeMetadata(block, metadataKey, owningPlugin); - } else { - throw new IllegalArgumentException("Block does not belong to world " + owningWorld.getName()); - } + Preconditions.checkArgument(block.getWorld() == this.owningWorld, "Block does not belong to world %s", owningWorld.getName()); + super.removeMetadata(block, metadataKey, owningPlugin); } /** @@ -84,10 +76,7 @@ public class BlockMetadataStore extends MetadataStoreBase implements Meta */ @Override public void setMetadata(Block block, String metadataKey, MetadataValue newMetadataValue) { - if (block.getWorld() == owningWorld) { - super.setMetadata(block, metadataKey, newMetadataValue); - } else { - throw new IllegalArgumentException("Block does not belong to world " + owningWorld.getName()); - } + Preconditions.checkArgument(block.getWorld() == this.owningWorld, "Block does not belong to world %s", owningWorld.getName()); + super.setMetadata(block, metadataKey, newMetadataValue); } } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataContainer.java b/paper-server/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataContainer.java index 7c9ae68529..754fa79598 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataContainer.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataContainer.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.persistence; +import com.google.common.base.Preconditions; import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -8,7 +9,6 @@ import java.util.Objects; import java.util.Set; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; -import org.apache.commons.lang.Validate; import org.bukkit.NamespacedKey; import org.bukkit.craftbukkit.util.CraftNBTTagConfigSerializer; import org.bukkit.persistence.PersistentDataAdapterContext; @@ -34,17 +34,17 @@ public class CraftPersistentDataContainer implements PersistentDataContainer { @Override public void set(NamespacedKey key, PersistentDataType type, Z value) { - Validate.notNull(key, "The provided key for the custom value was null"); - Validate.notNull(type, "The provided type for the custom value was null"); - Validate.notNull(value, "The provided value for the custom value was null"); + Preconditions.checkArgument(key != null, "The NamespacedKey key cannot be null"); + Preconditions.checkArgument(type != null, "The provided type cannot be null"); + Preconditions.checkArgument(value != null, "The provided value cannot be null"); this.customDataTags.put(key.toString(), registry.wrap(type.getPrimitiveType(), type.toPrimitive(value, adapterContext))); } @Override public boolean has(NamespacedKey key, PersistentDataType type) { - Validate.notNull(key, "The provided key for the custom value was null"); - Validate.notNull(type, "The provided type for the custom value was null"); + Preconditions.checkArgument(key != null, "The NamespacedKey key cannot be null"); + Preconditions.checkArgument(type != null, "The provided type cannot be null"); NBTBase value = this.customDataTags.get(key.toString()); if (value == null) { @@ -56,8 +56,8 @@ public class CraftPersistentDataContainer implements PersistentDataContainer { @Override public Z get(NamespacedKey key, PersistentDataType type) { - Validate.notNull(key, "The provided key for the custom value was null"); - Validate.notNull(type, "The provided type for the custom value was null"); + Preconditions.checkArgument(key != null, "The NamespacedKey key cannot be null"); + Preconditions.checkArgument(type != null, "The provided type cannot be null"); NBTBase value = this.customDataTags.get(key.toString()); if (value == null) { @@ -89,7 +89,7 @@ public class CraftPersistentDataContainer implements PersistentDataContainer { @Override public void remove(NamespacedKey key) { - Validate.notNull(key, "The provided key for the custom value was null"); + Preconditions.checkArgument(key != null, "The NamespacedKey key cannot be null"); this.customDataTags.remove(key.toString()); } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataTypeRegistry.java b/paper-server/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataTypeRegistry.java index 9a8fe9f414..b261aa2e0e 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataTypeRegistry.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/persistence/CraftPersistentDataTypeRegistry.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.persistence; +import com.google.common.base.Preconditions; import com.google.common.primitives.Primitives; import java.util.Arrays; import java.util.HashMap; @@ -56,9 +57,7 @@ public final class CraftPersistentDataTypeRegistry { * extractor function */ T extract(NBTBase base) { - if (!nbtBaseType.isInstance(base)) { - throw new IllegalArgumentException(String.format("The provided NBTBase was of the type %s. Expected type %s", base.getClass().getSimpleName(), nbtBaseType.getSimpleName())); - } + Preconditions.checkArgument(nbtBaseType.isInstance(base), "The provided NBTBase was of the type %s. Expected type %s", base.getClass().getSimpleName(), nbtBaseType.getSimpleName()); return this.extractor.apply(nbtBaseType.cast(base)); } @@ -74,9 +73,7 @@ public final class CraftPersistentDataTypeRegistry { * function */ Z build(Object value) { - if (!primitiveType.isInstance(value)) { - throw new IllegalArgumentException(String.format("The provided value was of the type %s. Expected type %s", value.getClass().getSimpleName(), primitiveType.getSimpleName())); - } + Preconditions.checkArgument(primitiveType.isInstance(value), "The provided value was of the type %s. Expected type %s", value.getClass().getSimpleName(), primitiveType.getSimpleName()); return this.builder.apply(primitiveType.cast(value)); } @@ -250,14 +247,10 @@ public final class CraftPersistentDataTypeRegistry { */ public T extract(Class type, NBTBase tag) throws ClassCastException, IllegalArgumentException { TagAdapter adapter = this.adapters.computeIfAbsent(type, CREATE_ADAPTER); - if (!adapter.isInstance(tag)) { - throw new IllegalArgumentException(String.format("`The found tag instance cannot store %s as it is a %s", type.getSimpleName(), tag.getClass().getSimpleName())); - } + Preconditions.checkArgument(adapter.isInstance(tag), "The found tag instance (%s) cannot store %s", tag.getClass().getSimpleName(), type.getSimpleName()); Object foundValue = adapter.extract(tag); - if (!type.isInstance(foundValue)) { - throw new IllegalArgumentException(String.format("The found object is of the type %s. Expected type %s", foundValue.getClass().getSimpleName(), type.getSimpleName())); - } + Preconditions.checkArgument(type.isInstance(foundValue), "The found object is of the type %s. Expected type %s", foundValue.getClass().getSimpleName(), type.getSimpleName()); return type.cast(foundValue); } } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/profile/CraftPlayerProfile.java b/paper-server/src/main/java/org/bukkit/craftbukkit/profile/CraftPlayerProfile.java index 472457b0d0..3c08f3d43b 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/profile/CraftPlayerProfile.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/profile/CraftPlayerProfile.java @@ -263,9 +263,7 @@ public final class CraftPlayerProfile implements PlayerProfile { if (map.containsKey("properties")) { for (Object propertyData : (List) map.get("properties")) { - if (!(propertyData instanceof Map)) { - throw new IllegalArgumentException("Property data (" + propertyData + ") is not a valid Map"); - } + Preconditions.checkArgument(propertyData instanceof Map, "Propertu data (%s) is not a valid Map", propertyData); Property property = CraftProfileProperty.deserialize((Map) propertyData); profile.properties.put(property.getName(), property); } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/projectiles/CraftBlockProjectileSource.java b/paper-server/src/main/java/org/bukkit/craftbukkit/projectiles/CraftBlockProjectileSource.java index e7b1079adb..b1256f82bb 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/projectiles/CraftBlockProjectileSource.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/projectiles/CraftBlockProjectileSource.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.projectiles; +import com.google.common.base.Preconditions; import net.minecraft.core.EnumDirection; import net.minecraft.core.IPosition; import net.minecraft.core.SourceBlock; @@ -20,7 +21,6 @@ import net.minecraft.world.entity.projectile.EntityTippedArrow; import net.minecraft.world.entity.projectile.IProjectile; import net.minecraft.world.level.block.BlockDispenser; import net.minecraft.world.level.block.entity.TileEntityDispenser; -import org.apache.commons.lang.Validate; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.craftbukkit.inventory.CraftItemStack; @@ -63,7 +63,7 @@ public class CraftBlockProjectileSource implements BlockProjectileSource { @Override public T launchProjectile(Class projectile, Vector velocity) { - Validate.isTrue(getBlock().getType() == Material.DISPENSER, "Block is no longer dispenser"); + Preconditions.checkArgument(getBlock().getType() == Material.DISPENSER, "Block is no longer dispenser"); // Copied from BlockDispenser.dispense() SourceBlock isourceblock = new SourceBlock((WorldServer) dispenserBlock.getLevel(), dispenserBlock.getBlockPos()); // Copied from DispenseBehaviorProjectile @@ -132,7 +132,7 @@ public class CraftBlockProjectileSource implements BlockProjectileSource { ((EntityFireball) launch).projectileSource = this; } - Validate.notNull(launch, "Projectile not supported"); + Preconditions.checkArgument(launch != null, "Projectile not supported"); if (launch instanceof IProjectile) { if (launch instanceof EntityProjectile) { diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/scheduler/CraftScheduler.java b/paper-server/src/main/java/org/bukkit/craftbukkit/scheduler/CraftScheduler.java index cd43b45516..1fb9b4582e 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/scheduler/CraftScheduler.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/scheduler/CraftScheduler.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.scheduler; +import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.util.ArrayList; import java.util.Comparator; @@ -16,7 +17,6 @@ import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.IntUnaryOperator; import java.util.logging.Level; -import org.apache.commons.lang.Validate; import org.bukkit.plugin.IllegalPluginAccessException; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitRunnable; @@ -283,7 +283,7 @@ public class CraftScheduler implements BukkitScheduler { @Override public void cancelTasks(final Plugin plugin) { - Validate.notNull(plugin, "Cannot cancel tasks of null plugin"); + Preconditions.checkArgument(plugin != null, "Cannot cancel tasks of null plugin"); final CraftTask task = new CraftTask( new Runnable() { @Override @@ -459,16 +459,15 @@ public class CraftScheduler implements BukkitScheduler { } private static void validate(final Plugin plugin, final Object task) { - Validate.notNull(plugin, "Plugin cannot be null"); - Validate.notNull(task, "Task cannot be null"); - Validate.isTrue(task instanceof Runnable || task instanceof Consumer || task instanceof Callable, "Task must be Runnable, Consumer, or Callable"); + Preconditions.checkArgument(plugin != null, "Plugin cannot be null"); + Preconditions.checkArgument(task instanceof Runnable || task instanceof Consumer || task instanceof Callable, "Task must be Runnable, Consumer, or Callable"); if (!plugin.isEnabled()) { throw new IllegalPluginAccessException("Plugin attempted to register task while disabled"); } } private int nextId() { - Validate.isTrue(runners.size() < Integer.MAX_VALUE, "There are already " + Integer.MAX_VALUE + " tasks scheduled! Cannot schedule more."); + Preconditions.checkArgument(runners.size() < Integer.MAX_VALUE, "There are already %s tasks scheduled! Cannot schedule more", Integer.MAX_VALUE); int id; do { id = ids.updateAndGet(INCREMENT_IDS); diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java b/paper-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java index 6aeaf5cb0c..8c7e0a6db1 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java @@ -1,8 +1,8 @@ package org.bukkit.craftbukkit.scoreboard; +import com.google.common.base.Preconditions; import net.minecraft.world.scores.Scoreboard; import net.minecraft.world.scores.ScoreboardObjective; -import org.apache.commons.lang.Validate; import org.bukkit.OfflinePlayer; import org.bukkit.craftbukkit.util.CraftChatMessage; import org.bukkit.scoreboard.Criteria; @@ -27,44 +27,44 @@ final class CraftObjective extends CraftScoreboardComponent implements Objective @Override public String getName() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); + checkState(); return objective.getName(); } @Override public String getDisplayName() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); + checkState(); return CraftChatMessage.fromComponent(objective.getDisplayName()); } @Override public void setDisplayName(String displayName) throws IllegalStateException, IllegalArgumentException { - Validate.notNull(displayName, "Display name cannot be null"); - Validate.isTrue(displayName.length() <= 128, "Display name '" + displayName + "' is longer than the limit of 128 characters"); - CraftScoreboard scoreboard = checkState(); + Preconditions.checkArgument(displayName != null, "Display name cannot be null"); + Preconditions.checkArgument(displayName.length() <= 128, "Display name '" + displayName + "' is longer than the limit of 128 characters"); + checkState(); objective.setDisplayName(CraftChatMessage.fromString(displayName)[0]); // SPIGOT-4112: not nullable } @Override public String getCriteria() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); + checkState(); return criteria.bukkitName; } @Override public Criteria getTrackedCriteria() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); + checkState(); return criteria; } @Override public boolean isModifiable() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); + checkState(); return !criteria.criteria.isReadOnly(); } @@ -102,32 +102,32 @@ final class CraftObjective extends CraftScoreboardComponent implements Objective @Override public void setRenderType(RenderType renderType) throws IllegalStateException { - Validate.notNull(renderType, "RenderType cannot be null"); - CraftScoreboard scoreboard = checkState(); + Preconditions.checkArgument(renderType != null, "RenderType cannot be null"); + checkState(); this.objective.setRenderType(CraftScoreboardTranslations.fromBukkitRender(renderType)); } @Override public RenderType getRenderType() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); + checkState(); return CraftScoreboardTranslations.toBukkitRender(this.objective.getRenderType()); } @Override public Score getScore(OfflinePlayer player) throws IllegalArgumentException, IllegalStateException { - Validate.notNull(player, "Player cannot be null"); - CraftScoreboard scoreboard = checkState(); + Preconditions.checkArgument(player != null, "Player cannot be null"); + checkState(); return new CraftScore(this, player.getName()); } @Override public Score getScore(String entry) throws IllegalArgumentException, IllegalStateException { - Validate.notNull(entry, "Entry cannot be null"); - Validate.isTrue(entry.length() <= Short.MAX_VALUE, "Score '" + entry + "' is longer than the limit of 32767 characters"); - CraftScoreboard scoreboard = checkState(); + Preconditions.checkArgument(entry != null, "Entry cannot be null"); + Preconditions.checkArgument(entry.length() <= Short.MAX_VALUE, "Score '" + entry + "' is longer than the limit of 32767 characters"); + checkState(); return new CraftScore(this, entry); } @@ -141,9 +141,7 @@ final class CraftObjective extends CraftScoreboardComponent implements Objective @Override CraftScoreboard checkState() throws IllegalStateException { - if (getScoreboard().board.getObjective(objective.getName()) == null) { - throw new IllegalStateException("Unregistered scoreboard component"); - } + Preconditions.checkState(getScoreboard().board.getObjective(objective.getName()) != null, "Unregistered scoreboard component"); return getScoreboard(); } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java b/paper-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java index 3c148b995c..1154ee1994 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java @@ -1,13 +1,12 @@ package org.bukkit.craftbukkit.scoreboard; import com.google.common.base.Function; +import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; -import java.util.Collection; import net.minecraft.world.scores.Scoreboard; import net.minecraft.world.scores.ScoreboardObjective; import net.minecraft.world.scores.ScoreboardTeam; -import org.apache.commons.lang.Validate; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.craftbukkit.util.CraftChatMessage; @@ -47,13 +46,13 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard { @Override public CraftObjective registerNewObjective(String name, Criteria criteria, String displayName, RenderType renderType) throws IllegalArgumentException { - Validate.notNull(name, "Objective name cannot be null"); - Validate.notNull(criteria, "Criteria cannot be null"); - Validate.notNull(displayName, "Display name cannot be null"); - Validate.notNull(renderType, "RenderType cannot be null"); - Validate.isTrue(name.length() <= Short.MAX_VALUE, "The name '" + name + "' is longer than the limit of 32767 characters"); - Validate.isTrue(displayName.length() <= 128, "The display name '" + displayName + "' is longer than the limit of 128 characters"); - Validate.isTrue(board.getObjective(name) == null, "An objective of name '" + name + "' already exists"); + Preconditions.checkArgument(name != null, "Objective name cannot be null"); + Preconditions.checkArgument(criteria != null, "Criteria cannot be null"); + Preconditions.checkArgument(displayName != null, "Display name cannot be null"); + Preconditions.checkArgument(renderType != null, "RenderType cannot be null"); + Preconditions.checkArgument(name.length() <= Short.MAX_VALUE, "The name '%s' is longer than the limit of 32767 characters (%s)", name, name.length()); + Preconditions.checkArgument(displayName.length() <= 128, "The display name '%s' is longer than the limit of 128 characters (%s)", displayName, displayName.length()); + Preconditions.checkArgument(board.getObjective(name) == null, "An objective of name '%s' already exists", name); ScoreboardObjective objective = board.addObjective(name, ((CraftCriteria) criteria).criteria, CraftChatMessage.fromStringOrNull(displayName), CraftScoreboardTranslations.fromBukkitRender(renderType)); return new CraftObjective(this, objective); @@ -61,17 +60,17 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard { @Override public Objective getObjective(String name) throws IllegalArgumentException { - Validate.notNull(name, "Name cannot be null"); + Preconditions.checkArgument(name != null, "Objective name cannot be null"); ScoreboardObjective nms = board.getObjective(name); return nms == null ? null : new CraftObjective(this, nms); } @Override public ImmutableSet getObjectivesByCriteria(String criteria) throws IllegalArgumentException { - Validate.notNull(criteria, "Criteria cannot be null"); + Preconditions.checkArgument(criteria != null, "Criteria name cannot be null"); ImmutableSet.Builder objectives = ImmutableSet.builder(); - for (ScoreboardObjective netObjective : (Collection) this.board.getObjectives()) { + for (ScoreboardObjective netObjective : this.board.getObjectives()) { CraftObjective objective = new CraftObjective(this, netObjective); if (objective.getCriteria().equals(criteria)) { objectives.add(objective); @@ -82,7 +81,7 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard { @Override public ImmutableSet getObjectivesByCriteria(Criteria criteria) throws IllegalArgumentException { - Validate.notNull(criteria, "Criteria cannot be null"); + Preconditions.checkArgument(criteria != null, "Criteria cannot be null"); ImmutableSet.Builder objectives = ImmutableSet.builder(); for (ScoreboardObjective netObjective : board.getObjectives()) { @@ -97,18 +96,12 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard { @Override public ImmutableSet getObjectives() { - return ImmutableSet.copyOf(Iterables.transform((Collection) this.board.getObjectives(), new Function() { - - @Override - public Objective apply(ScoreboardObjective input) { - return new CraftObjective(CraftScoreboard.this, input); - } - })); + return ImmutableSet.copyOf(Iterables.transform(this.board.getObjectives(), (Function) input -> new CraftObjective(CraftScoreboard.this, input))); } @Override public Objective getObjective(DisplaySlot slot) throws IllegalArgumentException { - Validate.notNull(slot, "Display slot cannot be null"); + Preconditions.checkArgument(slot != null, "Display slot cannot be null"); ScoreboardObjective objective = board.getDisplayObjective(CraftScoreboardTranslations.fromBukkitSlot(slot)); if (objective == null) { return null; @@ -118,17 +111,17 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard { @Override public ImmutableSet getScores(OfflinePlayer player) throws IllegalArgumentException { - Validate.notNull(player, "OfflinePlayer cannot be null"); + Preconditions.checkArgument(player != null, "OfflinePlayer cannot be null"); return getScores(player.getName()); } @Override public ImmutableSet getScores(String entry) throws IllegalArgumentException { - Validate.notNull(entry, "Entry cannot be null"); + Preconditions.checkArgument(entry != null, "Entry cannot be null"); ImmutableSet.Builder scores = ImmutableSet.builder(); - for (ScoreboardObjective objective : (Collection) this.board.getObjectives()) { + for (ScoreboardObjective objective : this.board.getObjectives()) { scores.add(new CraftScore(new CraftObjective(this, objective), entry)); } return scores.build(); @@ -136,23 +129,23 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard { @Override public void resetScores(OfflinePlayer player) throws IllegalArgumentException { - Validate.notNull(player, "OfflinePlayer cannot be null"); + Preconditions.checkArgument(player != null, "OfflinePlayer cannot be null"); resetScores(player.getName()); } @Override public void resetScores(String entry) throws IllegalArgumentException { - Validate.notNull(entry, "Entry cannot be null"); + Preconditions.checkArgument(entry != null, "Entry cannot be null"); - for (ScoreboardObjective objective : (Collection) this.board.getObjectives()) { + for (ScoreboardObjective objective : this.board.getObjectives()) { board.resetPlayerScore(entry, objective); } } @Override public Team getPlayerTeam(OfflinePlayer player) throws IllegalArgumentException { - Validate.notNull(player, "OfflinePlayer cannot be null"); + Preconditions.checkArgument(player != null, "OfflinePlayer cannot be null"); ScoreboardTeam team = board.getPlayersTeam(player.getName()); return team == null ? null : new CraftTeam(this, team); @@ -160,7 +153,7 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard { @Override public Team getEntryTeam(String entry) throws IllegalArgumentException { - Validate.notNull(entry, "Entry cannot be null"); + Preconditions.checkArgument(entry != null, "Entry cannot be null"); ScoreboardTeam team = board.getPlayersTeam(entry); return team == null ? null : new CraftTeam(this, team); @@ -168,7 +161,7 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard { @Override public Team getTeam(String teamName) throws IllegalArgumentException { - Validate.notNull(teamName, "Team name cannot be null"); + Preconditions.checkArgument(teamName != null, "Team name cannot be null"); ScoreboardTeam team = board.getPlayerTeam(teamName); return team == null ? null : new CraftTeam(this, team); @@ -176,20 +169,14 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard { @Override public ImmutableSet getTeams() { - return ImmutableSet.copyOf(Iterables.transform((Collection) this.board.getPlayerTeams(), new Function() { - - @Override - public Team apply(ScoreboardTeam input) { - return new CraftTeam(CraftScoreboard.this, input); - } - })); + return ImmutableSet.copyOf(Iterables.transform(this.board.getPlayerTeams(), (Function) input -> new CraftTeam(CraftScoreboard.this, input))); } @Override public Team registerNewTeam(String name) throws IllegalArgumentException { - Validate.notNull(name, "Team name cannot be null"); - Validate.isTrue(name.length() <= Short.MAX_VALUE, "Team name '" + name + "' is longer than the limit of 32767 characters"); - Validate.isTrue(board.getPlayerTeam(name) == null, "Team name '" + name + "' is already in use"); + Preconditions.checkArgument(name != null, "Team name cannot be null"); + Preconditions.checkArgument(name.length() <= Short.MAX_VALUE, "Team name '%s' is longer than the limit of 32767 characters (%s)", name, name.length()); + Preconditions.checkArgument(board.getPlayerTeam(name) == null, "Team name '%s' is already in use", name); return new CraftTeam(this, board.addPlayerTeam(name)); } @@ -214,7 +201,7 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard { @Override public void clearSlot(DisplaySlot slot) throws IllegalArgumentException { - Validate.notNull(slot, "Slot cannot be null"); + Preconditions.checkArgument(slot != null, "Slot cannot be null"); board.setDisplayObjective(CraftScoreboardTranslations.fromBukkitSlot(slot), null); } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardManager.java b/paper-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardManager.java index 659c1b272a..230841a84a 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardManager.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardManager.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.scoreboard; +import com.google.common.base.Preconditions; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; @@ -16,7 +17,6 @@ import net.minecraft.world.scores.ScoreboardObjective; import net.minecraft.world.scores.ScoreboardScore; import net.minecraft.world.scores.ScoreboardTeam; import net.minecraft.world.scores.criteria.IScoreboardCriteria; -import org.apache.commons.lang.Validate; import org.bukkit.craftbukkit.entity.CraftPlayer; import org.bukkit.craftbukkit.util.WeakCollection; import org.bukkit.entity.Player; @@ -54,7 +54,7 @@ public final class CraftScoreboardManager implements ScoreboardManager { // CraftBukkit method public void setPlayerBoard(CraftPlayer player, org.bukkit.scoreboard.Scoreboard bukkitScoreboard) throws IllegalArgumentException { - Validate.isTrue(bukkitScoreboard instanceof CraftScoreboard, "Cannot set player scoreboard to an unregistered Scoreboard"); + Preconditions.checkArgument(bukkitScoreboard instanceof CraftScoreboard, "Cannot set player scoreboard to an unregistered Scoreboard"); CraftScoreboard scoreboard = (CraftScoreboard) bukkitScoreboard; net.minecraft.world.scores.Scoreboard oldboard = getPlayerBoard(player).getHandle(); diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java b/paper-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java index fa542fdc37..8eeea71057 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java @@ -1,19 +1,17 @@ package org.bukkit.craftbukkit.scoreboard; +import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import java.util.Set; import net.minecraft.world.scores.ScoreboardTeam; import net.minecraft.world.scores.ScoreboardTeamBase; import net.minecraft.world.scores.ScoreboardTeamBase.EnumNameTagVisibility; -import org.apache.commons.lang.Validate; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.craftbukkit.util.CraftChatMessage; import org.bukkit.scoreboard.NameTagVisibility; import org.bukkit.scoreboard.Team; -import org.bukkit.scoreboard.Team.Option; -import org.bukkit.scoreboard.Team.OptionStatus; final class CraftTeam extends CraftScoreboardComponent implements Team { private final ScoreboardTeam team; @@ -25,119 +23,121 @@ final class CraftTeam extends CraftScoreboardComponent implements Team { @Override public String getName() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); + checkState(); return team.getName(); } @Override public String getDisplayName() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); + checkState(); return CraftChatMessage.fromComponent(team.getDisplayName()); } @Override public void setDisplayName(String displayName) throws IllegalStateException { - Validate.notNull(displayName, "Display name cannot be null"); - Validate.isTrue(ChatColor.stripColor(displayName).length() <= 128, "Display name '" + displayName + "' is longer than the limit of 128 characters"); - CraftScoreboard scoreboard = checkState(); + Preconditions.checkArgument(displayName != null, "Display name cannot be null"); + int lengthStripedDisplayName = ChatColor.stripColor(displayName).length(); + Preconditions.checkArgument(lengthStripedDisplayName <= 128, "Display name '%s' is longer than the limit of 128 characters (%s)", displayName, lengthStripedDisplayName); + checkState(); team.setDisplayName(CraftChatMessage.fromString(displayName)[0]); // SPIGOT-4112: not nullable } @Override public String getPrefix() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); + checkState(); return CraftChatMessage.fromComponent(team.getPlayerPrefix()); } @Override public void setPrefix(String prefix) throws IllegalStateException, IllegalArgumentException { - Validate.notNull(prefix, "Prefix cannot be null"); - Validate.isTrue(ChatColor.stripColor(prefix).length() <= 64, "Prefix '" + prefix + "' is longer than the limit of 64 characters"); - CraftScoreboard scoreboard = checkState(); + Preconditions.checkArgument(prefix != null, "Prefix cannot be null"); + int lengthStripedPrefix = ChatColor.stripColor(prefix).length(); + Preconditions.checkArgument(lengthStripedPrefix <= 64, "Prefix '%s' is longer than the limit of 64 characters (%s)", prefix, lengthStripedPrefix); + checkState(); team.setPlayerPrefix(CraftChatMessage.fromStringOrNull(prefix)); } @Override public String getSuffix() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); + checkState(); return CraftChatMessage.fromComponent(team.getPlayerSuffix()); } @Override public void setSuffix(String suffix) throws IllegalStateException, IllegalArgumentException { - Validate.notNull(suffix, "Suffix cannot be null"); - Validate.isTrue(ChatColor.stripColor(suffix).length() <= 64, "Suffix '" + suffix + "' is longer than the limit of 64 characters"); - CraftScoreboard scoreboard = checkState(); + Preconditions.checkArgument(suffix != null, "Suffix cannot be null"); + int lengthStripedSuffix = ChatColor.stripColor(suffix).length(); + Preconditions.checkArgument(lengthStripedSuffix <= 64, "Suffix '%s' is longer than the limit of 64 characters (%s)", suffix, lengthStripedSuffix); team.setPlayerSuffix(CraftChatMessage.fromStringOrNull(suffix)); } @Override public ChatColor getColor() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); + checkState(); return CraftChatMessage.getColor(team.getColor()); } @Override public void setColor(ChatColor color) { - Validate.notNull(color, "Color cannot be null"); - CraftScoreboard scoreboard = checkState(); + Preconditions.checkArgument(color != null, "Color cannot be null"); + checkState(); team.setColor(CraftChatMessage.getColor(color)); } @Override public boolean allowFriendlyFire() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); + checkState(); return team.isAllowFriendlyFire(); } @Override public void setAllowFriendlyFire(boolean enabled) throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); + checkState(); team.setAllowFriendlyFire(enabled); } @Override public boolean canSeeFriendlyInvisibles() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); + checkState(); return team.canSeeFriendlyInvisibles(); } @Override public void setCanSeeFriendlyInvisibles(boolean enabled) throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); + checkState(); team.setSeeFriendlyInvisibles(enabled); } @Override public NameTagVisibility getNameTagVisibility() throws IllegalArgumentException { - CraftScoreboard scoreboard = checkState(); + checkState(); return notchToBukkit(team.getNameTagVisibility()); } @Override public void setNameTagVisibility(NameTagVisibility visibility) throws IllegalArgumentException { - CraftScoreboard scoreboard = checkState(); + checkState(); team.setNameTagVisibility(bukkitToNotch(visibility)); } @Override public Set getPlayers() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); + checkState(); ImmutableSet.Builder players = ImmutableSet.builder(); for (String playerName : team.getPlayers()) { @@ -148,7 +148,7 @@ final class CraftTeam extends CraftScoreboardComponent implements Team { @Override public Set getEntries() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); + checkState(); ImmutableSet.Builder entries = ImmutableSet.builder(); for (String playerName : team.getPlayers()) { @@ -159,20 +159,20 @@ final class CraftTeam extends CraftScoreboardComponent implements Team { @Override public int getSize() throws IllegalStateException { - CraftScoreboard scoreboard = checkState(); + checkState(); return team.getPlayers().size(); } @Override public void addPlayer(OfflinePlayer player) throws IllegalStateException, IllegalArgumentException { - Validate.notNull(player, "OfflinePlayer cannot be null"); + Preconditions.checkArgument(player != null, "OfflinePlayer cannot be null"); addEntry(player.getName()); } @Override public void addEntry(String entry) throws IllegalStateException, IllegalArgumentException { - Validate.notNull(entry, "Entry cannot be null"); + Preconditions.checkArgument(entry != null, "Entry cannot be null"); CraftScoreboard scoreboard = checkState(); scoreboard.board.addPlayerToTeam(entry, team); @@ -180,13 +180,13 @@ final class CraftTeam extends CraftScoreboardComponent implements Team { @Override public boolean removePlayer(OfflinePlayer player) throws IllegalStateException, IllegalArgumentException { - Validate.notNull(player, "OfflinePlayer cannot be null"); + Preconditions.checkArgument(player != null, "OfflinePlayer cannot be null"); return removeEntry(player.getName()); } @Override public boolean removeEntry(String entry) throws IllegalStateException, IllegalArgumentException { - Validate.notNull(entry, "Entry cannot be null"); + Preconditions.checkArgument(entry != null, "Entry cannot be null"); CraftScoreboard scoreboard = checkState(); if (!team.getPlayers().contains(entry)) { @@ -199,15 +199,14 @@ final class CraftTeam extends CraftScoreboardComponent implements Team { @Override public boolean hasPlayer(OfflinePlayer player) throws IllegalArgumentException, IllegalStateException { - Validate.notNull(player, "OfflinePlayer cannot be null"); + Preconditions.checkArgument(player != null, "OfflinePlayer cannot be null"); return hasEntry(player.getName()); } @Override public boolean hasEntry(String entry) throws IllegalArgumentException, IllegalStateException { - Validate.notNull("Entry cannot be null"); - - CraftScoreboard scoreboard = checkState(); + Preconditions.checkArgument(entry != null, "Entry cannot be null"); + checkState(); return team.getPlayers().contains(entry); } @@ -286,9 +285,7 @@ final class CraftTeam extends CraftScoreboardComponent implements Team { @Override CraftScoreboard checkState() throws IllegalStateException { - if (getScoreboard().board.getPlayerTeam(team.getName()) == null) { - throw new IllegalStateException("Unregistered scoreboard component"); - } + Preconditions.checkState(getScoreboard().board.getPlayerTeam(team.getName()) != null, "Unregistered scoreboard component"); return getScoreboard(); } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/structure/CraftStructure.java b/paper-server/src/main/java/org/bukkit/craftbukkit/structure/CraftStructure.java index 84dcd5f4fb..0a2ca21676 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/structure/CraftStructure.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/structure/CraftStructure.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.structure; +import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -14,7 +15,6 @@ import net.minecraft.world.level.block.EnumBlockRotation; import net.minecraft.world.level.levelgen.structure.templatesystem.DefinedStructure; import net.minecraft.world.level.levelgen.structure.templatesystem.DefinedStructureInfo; import net.minecraft.world.level.levelgen.structure.templatesystem.DefinedStructureProcessorRotation; -import org.apache.commons.lang3.Validate; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.RegionAccessor; @@ -42,9 +42,10 @@ public class CraftStructure implements Structure { @Override public void place(Location location, boolean includeEntities, StructureRotation structureRotation, Mirror mirror, int palette, float integrity, Random random) { + Preconditions.checkArgument(location != null, "Location cannot be null"); location.checkFinite(); World world = location.getWorld(); - Validate.notNull(world, "location#getWorld() cannot be null"); + Preconditions.checkArgument(world != null, "The World of Location cannot be null"); BlockVector blockVector = new BlockVector(location.getBlockX(), location.getBlockY(), location.getBlockZ()); place(world, blockVector, includeEntities, structureRotation, mirror, palette, integrity, random); @@ -52,12 +53,11 @@ public class CraftStructure implements Structure { @Override public void place(RegionAccessor regionAccessor, BlockVector location, boolean includeEntities, StructureRotation structureRotation, Mirror mirror, int palette, float integrity, Random random) { - Validate.notNull(regionAccessor, "regionAccessor can not be null"); + Preconditions.checkArgument(location != null, "Location cannot be null"); + Preconditions.checkArgument(regionAccessor != null, "RegionAccessor cannot be null"); location.checkFinite(); - if (integrity < 0F || integrity > 1F) { - throw new IllegalArgumentException("Integrity must be between 0 and 1 inclusive. Was \"" + integrity + "\""); - } + Preconditions.checkArgument(integrity >= 0F && integrity <= 1F, "Integrity value (%S) must be between 0 and 1 inclusive", integrity); RandomSource randomSource = new RandomSourceWrapper(random); DefinedStructureInfo definedstructureinfo = new DefinedStructureInfo() @@ -74,10 +74,10 @@ public class CraftStructure implements Structure { @Override public void fill(Location corner1, Location corner2, boolean includeEntities) { - Validate.notNull(corner1, "corner1 cannot be null"); - Validate.notNull(corner2, "corner2 cannot be null"); + Preconditions.checkArgument(corner1 != null, "Location corner1 cannot be null"); + Preconditions.checkArgument(corner2 != null, "Location corner2 cannot be null"); World world = corner1.getWorld(); - Validate.notNull(world, "corner1#getWorld() cannot be null"); + Preconditions.checkArgument(world != null, "World of corner1 Location cannot be null"); Location origin = new Location(world, Math.min(corner1.getBlockX(), corner2.getBlockX()), Math.min(corner1.getBlockY(), corner2.getBlockY()), Math.min(corner1.getBlockZ(), corner2.getBlockZ())); BlockVector size = new BlockVector(Math.abs(corner1.getBlockX() - corner2.getBlockX()), Math.abs(corner1.getBlockY() - corner2.getBlockY()), Math.abs(corner1.getBlockZ() - corner2.getBlockZ())); @@ -86,13 +86,11 @@ public class CraftStructure implements Structure { @Override public void fill(Location origin, BlockVector size, boolean includeEntities) { - Validate.notNull(origin, "origin cannot be null"); + Preconditions.checkArgument(origin != null, "Location origin cannot be null"); World world = origin.getWorld(); - Validate.notNull(world, "origin#getWorld() cannot be null"); - Validate.notNull(size, "size cannot be null"); - if (size.getBlockX() < 1 || size.getBlockY() < 1 || size.getBlockZ() < 1) { - throw new IllegalArgumentException("Size must be at least 1x1x1 but was " + size.getBlockX() + "x" + size.getBlockY() + "x" + size.getBlockZ()); - } + Preconditions.checkArgument(world != null, "World of Location origin cannot be null"); + Preconditions.checkArgument(size != null, "BlockVector size cannot be null"); + Preconditions.checkArgument(size.getBlockX() >= 1 && size.getBlockY() >= 1 && size.getBlockZ() >= 1, "Size must be at least 1x1x1 but was %sx%sx%s", size.getBlockX(), size.getBlockY(), size.getBlockZ()); structure.fillFromWorld(((CraftWorld) world).getHandle(), CraftLocation.toBlockPosition(origin), CraftBlockVector.toBlockPosition(size), includeEntities, Blocks.STRUCTURE_VOID); } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/structure/CraftStructureManager.java b/paper-server/src/main/java/org/bukkit/craftbukkit/structure/CraftStructureManager.java index baeda93d36..4c36b11f39 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/structure/CraftStructureManager.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/structure/CraftStructureManager.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.structure; +import com.google.common.base.Preconditions; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -17,7 +18,6 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.resources.MinecraftKey; import net.minecraft.world.level.levelgen.structure.templatesystem.DefinedStructure; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; -import org.apache.commons.lang3.Validate; import org.bukkit.NamespacedKey; import org.bukkit.craftbukkit.util.CraftNamespacedKey; import org.bukkit.structure.Structure; @@ -35,16 +35,14 @@ public class CraftStructureManager implements StructureManager { public Map getStructures() { Map cachedStructures = new HashMap<>(); for (Map.Entry> entry : structureManager.structureRepository.entrySet()) { - entry.getValue().ifPresent(definedStructure -> { - cachedStructures.put(CraftNamespacedKey.fromMinecraft(entry.getKey()), new CraftStructure(definedStructure)); - }); + entry.getValue().ifPresent(definedStructure -> cachedStructures.put(CraftNamespacedKey.fromMinecraft(entry.getKey()), new CraftStructure(definedStructure))); } return Collections.unmodifiableMap(cachedStructures); } @Override public Structure getStructure(NamespacedKey structureKey) { - Validate.notNull(structureKey, "structureKey cannot be null"); + Preconditions.checkArgument(structureKey != null, "NamespacedKey structureKey cannot be null"); final Optional definedStructure = structureManager.structureRepository.get(CraftNamespacedKey.toMinecraft(structureKey)); if (definedStructure == null) { @@ -83,7 +81,8 @@ public class CraftStructureManager implements StructureManager { @Override public void saveStructure(NamespacedKey structureKey, Structure structure) throws IOException { - Validate.notNull(structure, "structure cannot be null"); + Preconditions.checkArgument(structureKey != null, "NamespacedKey structure cannot be null"); + Preconditions.checkArgument(structure != null, "Structure cannot be null"); File structureFile = getStructureFile(structureKey); Files.createDirectories(structureFile.toPath().getParent()); @@ -92,7 +91,8 @@ public class CraftStructureManager implements StructureManager { @Override public Structure registerStructure(NamespacedKey structureKey, Structure structure) { - Validate.notNull(structure, "structure cannot be null"); + Preconditions.checkArgument(structureKey != null, "NamespacedKey structureKey cannot be null"); + Preconditions.checkArgument(structure != null, "Structure cannot be null"); MinecraftKey minecraftKey = createAndValidateMinecraftStructureKey(structureKey); final Optional optionalDefinedStructure = Optional.of(((CraftStructure) structure).getHandle()); @@ -102,6 +102,7 @@ public class CraftStructureManager implements StructureManager { @Override public Structure unregisterStructure(NamespacedKey structureKey) { + Preconditions.checkArgument(structureKey != null, "NamespacedKey structureKey cannot be null"); MinecraftKey minecraftKey = createAndValidateMinecraftStructureKey(structureKey); final Optional previousStructure = structureManager.structureRepository.remove(minecraftKey); @@ -132,7 +133,7 @@ public class CraftStructureManager implements StructureManager { @Override public Structure loadStructure(File file) throws IOException { - Validate.notNull(file, "file cannot be null"); + Preconditions.checkArgument(file != null, "File cannot be null"); FileInputStream fileinputstream = new FileInputStream(file); return loadStructure(fileinputstream); @@ -140,15 +141,15 @@ public class CraftStructureManager implements StructureManager { @Override public Structure loadStructure(InputStream inputStream) throws IOException { - Validate.notNull(inputStream, "inputStream cannot be null"); + Preconditions.checkArgument(inputStream != null, "inputStream cannot be null"); return new CraftStructure(structureManager.readStructure(inputStream)); } @Override public void saveStructure(File file, Structure structure) throws IOException { - Validate.notNull(file, "file cannot be null"); - Validate.notNull(structure, "structure cannot be null"); + Preconditions.checkArgument(file != null, "file cannot be null"); + Preconditions.checkArgument(structure != null, "structure cannot be null"); FileOutputStream fileoutputstream = new FileOutputStream(file); saveStructure(fileoutputstream, structure); @@ -156,8 +157,8 @@ public class CraftStructureManager implements StructureManager { @Override public void saveStructure(OutputStream outputStream, Structure structure) throws IOException { - Validate.notNull(outputStream, "outputStream cannot be null"); - Validate.notNull(structure, "structure cannot be null"); + Preconditions.checkArgument(outputStream != null, "outputStream cannot be null"); + Preconditions.checkArgument(structure != null, "structure cannot be null"); NBTTagCompound nbttagcompound = ((CraftStructure) structure).getHandle().save(new NBTTagCompound()); NBTCompressedStreamTools.writeCompressed(nbttagcompound, outputStream); @@ -169,17 +170,16 @@ public class CraftStructureManager implements StructureManager { } private MinecraftKey createAndValidateMinecraftStructureKey(NamespacedKey structureKey) { - Validate.notNull(structureKey, "structureKey cannot be null"); + Preconditions.checkArgument(structureKey != null, "NamespacedKey structureKey cannot be null"); MinecraftKey minecraftkey = CraftNamespacedKey.toMinecraft(structureKey); - if (minecraftkey.getPath().contains("//")) { - throw new IllegalArgumentException("Resource key for Structures can not contain \"//\""); - } + Preconditions.checkArgument(!minecraftkey.getPath().contains("//"), "Resource key for Structures can not contain \"//\""); return minecraftkey; } @Override public Structure copy(Structure structure) { + Preconditions.checkArgument(structure != null, "Structure cannot be null"); return new CraftStructure(structureManager.readStructure(((CraftStructure) structure).getHandle().save(new NBTTagCompound()))); } } diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java b/paper-server/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java index 1210807bed..083f09068a 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java @@ -268,9 +268,7 @@ public final class CraftMagicNumbers implements UnsafeValues { @Override public Advancement loadAdvancement(NamespacedKey key, String advancement) { - if (Bukkit.getAdvancement(key) != null) { - throw new IllegalArgumentException("Advancement " + key + " already exists."); - } + Preconditions.checkArgument(Bukkit.getAdvancement(key) == null, "Advancement %s already exists", key); MinecraftKey minecraftkey = CraftNamespacedKey.toMinecraft(key); JsonElement jsonelement = AdvancementDataWorld.GSON.fromJson(advancement, JsonElement.class); diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java b/paper-server/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java index e7b9250ebd..fa47193677 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.util; +import com.google.common.base.Preconditions; import java.util.HashSet; import java.util.List; import net.minecraft.server.MinecraftServer; @@ -16,9 +17,7 @@ public class LazyPlayerSet extends LazyHashSet { @Override HashSet makeReference() { - if (reference != null) { - throw new IllegalStateException("Reference already created!"); - } + Preconditions.checkState(reference == null, "Reference already created!"); List players = server.getPlayerList().players; HashSet reference = new HashSet(players.size()); for (EntityPlayer player : players) { diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/util/UnsafeList.java b/paper-server/src/main/java/org/bukkit/craftbukkit/util/UnsafeList.java index 1aec70a1f1..3d5cc8189d 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/util/UnsafeList.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/util/UnsafeList.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.util; +import com.google.common.base.Preconditions; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; @@ -273,9 +274,7 @@ public class UnsafeList extends AbstractList implements List, RandomAcc @Override public void remove() { - if (lastRet < 0) { - throw new IllegalStateException(); - } + Preconditions.checkState(lastRet >= 0, ""); if (modCount != expectedModCount) { throw new ConcurrentModificationException(); diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/util/Waitable.java b/paper-server/src/main/java/org/bukkit/craftbukkit/util/Waitable.java index 9c23b76932..73be17fcc0 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/util/Waitable.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/util/Waitable.java @@ -1,5 +1,6 @@ package org.bukkit.craftbukkit.util; +import com.google.common.base.Preconditions; import java.util.concurrent.ExecutionException; public abstract class Waitable implements Runnable { @@ -15,9 +16,7 @@ public abstract class Waitable implements Runnable { @Override public final void run() { synchronized (this) { - if (status != Status.WAITING) { - throw new IllegalStateException("Invalid state " + status); - } + Preconditions.checkState(status == Status.WAITING, "Invalid state %s", status); status = Status.RUNNING; } try { diff --git a/paper-server/src/main/java/org/bukkit/craftbukkit/util/WeakCollection.java b/paper-server/src/main/java/org/bukkit/craftbukkit/util/WeakCollection.java index 3c89468373..489f548b5d 100644 --- a/paper-server/src/main/java/org/bukkit/craftbukkit/util/WeakCollection.java +++ b/paper-server/src/main/java/org/bukkit/craftbukkit/util/WeakCollection.java @@ -1,23 +1,23 @@ package org.bukkit.craftbukkit.util; +import com.google.common.base.Preconditions; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; -import org.apache.commons.lang.Validate; public final class WeakCollection implements Collection { static final Object NO_VALUE = new Object(); private final Collection> collection; public WeakCollection() { - collection = new ArrayList>(); + collection = new ArrayList<>(); } @Override public boolean add(T value) { - Validate.notNull(value, "Cannot add null value"); + Preconditions.checkArgument(value != null, "Cannot add null value"); return collection.add(new WeakReference(value)); } @@ -26,7 +26,7 @@ public final class WeakCollection implements Collection { Collection> values = this.collection; boolean ret = false; for (T value : collection) { - Validate.notNull(value, "Cannot add null value"); + Preconditions.checkArgument(value != null, "Cannot add null value"); ret |= values.add(new WeakReference(value)); } return ret; @@ -103,9 +103,7 @@ public final class WeakCollection implements Collection { @Override public void remove() throws IllegalStateException { - if (value != NO_VALUE) { - throw new IllegalStateException("No last element"); - } + Preconditions.checkState(value == NO_VALUE, "No last element"); value = null; it.remove();