13
0
geforkt von Mirrors/Paper

#1182: Consolidate Preconditions use and minor cleanup

By: Doc <nachito94@msn.com>
Dieser Commit ist enthalten in:
CraftBukkit/Spigot 2023-06-12 19:41:02 +10:00
Ursprung 5ff68bfbcb
Commit ff78bf30f6
72 geänderte Dateien mit 695 neuen und 855 gelöschten Zeilen

Datei anzeigen

@ -152,19 +152,33 @@ if (false && !this.world.isClientSide && !this.isDead && (d0*d0) + d1 + (d2*d2)
this.h(); this.h();
} }
``` ```
* For checks related to API where an exception needs to be thrown in a specific case we recommend use the package `Preconditions`
* 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. * For checking arguments we recommend using `Preconditions#checkArgument` where a failing check should throw a `IllegalArgumentException`
* The Preconditions package works just as well. Either are acceptable; though these are, by no means, the only accepted validation strategies. * 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:__ __For example, you should use:__
```java ```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:__ __Instead of:__
```java ```java
private Object messenger;
public void sendMessage(Sender sender, String message) {
if (sender == null) { if (sender == null) {
throw new IllegalArgumentException("Sender cannot be null"); throw new IllegalArgumentException("Sender cannot be null");
} }
if (this.messenger == null) {
throw new IllegalStateException("The messenger instance cannot be used");
}
}
``` ```
* When the change you are trying to make involves removing code, or delegating it somewhere else, instead of removing it, you should comment it out. * When the change you are trying to make involves removing code, or delegating it somewhere else, instead of removing it, you should comment it out.

Datei anzeigen

@ -1,8 +1,8 @@
package org.bukkit.craftbukkit; package org.bukkit.craftbukkit;
import com.google.common.base.Preconditions;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import org.apache.commons.lang.Validate;
import org.bukkit.Axis; import org.bukkit.Axis;
import org.bukkit.Color; import org.bukkit.Color;
import org.bukkit.Effect; import org.bukkit.Effect;
@ -25,7 +25,7 @@ public class CraftEffect {
datavalue = ((Color) data).asRGB(); datavalue = ((Color) data).asRGB();
break; break;
case RECORD_PLAY: 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)); datavalue = Item.getId(CraftMagicNumbers.getItem((Material) data));
break; break;
case SMOKE: case SMOKE:
@ -59,7 +59,7 @@ public class CraftEffect {
} }
break; break;
case STEP_SOUND: 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()); datavalue = Block.getId(CraftMagicNumbers.getBlock((Material) data).defaultBlockState());
break; break;
case COMPOSTER_FILL_ATTEMPT: case COMPOSTER_FILL_ATTEMPT:

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit; package org.bukkit.craftbukkit;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import java.io.IOException; import java.io.IOException;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
@ -9,7 +10,6 @@ import java.util.logging.Level;
import net.minecraft.server.players.IpBanEntry; import net.minecraft.server.players.IpBanEntry;
import net.minecraft.server.players.IpBanList; import net.minecraft.server.players.IpBanList;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
public class CraftIpBanList implements org.bukkit.BanList { public class CraftIpBanList implements org.bukkit.BanList {
@ -21,7 +21,7 @@ public class CraftIpBanList implements org.bukkit.BanList {
@Override @Override
public org.bukkit.BanEntry getBanEntry(String target) { 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); IpBanEntry entry = (IpBanEntry) list.get(target);
if (entry == null) { if (entry == null) {
@ -33,7 +33,7 @@ public class CraftIpBanList implements org.bukkit.BanList {
@Override @Override
public org.bukkit.BanEntry addBan(String target, String reason, Date expires, String source) { 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(), IpBanEntry entry = new IpBanEntry(target, new Date(),
StringUtils.isBlank(source) ? null : source, expires, StringUtils.isBlank(source) ? null : source, expires,
@ -62,14 +62,14 @@ public class CraftIpBanList implements org.bukkit.BanList {
@Override @Override
public boolean isBanned(String target) { 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)); return list.isBanned(InetSocketAddress.createUnresolved(target, 0));
} }
@Override @Override
public void pardon(String target) { public void pardon(String target) {
Validate.notNull(target, "Target cannot be null"); Preconditions.checkArgument(target != null, "Target cannot be null");
list.remove(target); list.remove(target);
} }

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit; package org.bukkit.craftbukkit;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import java.io.IOException; 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.GameProfileBanList;
import net.minecraft.server.players.JsonListEntry; import net.minecraft.server.players.JsonListEntry;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
public class CraftProfileBanList implements org.bukkit.BanList { public class CraftProfileBanList implements org.bukkit.BanList {
@ -24,7 +24,7 @@ public class CraftProfileBanList implements org.bukkit.BanList {
@Override @Override
public org.bukkit.BanEntry getBanEntry(String target) { 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); GameProfile profile = getProfile(target);
if (profile == null) { if (profile == null) {
@ -41,7 +41,7 @@ public class CraftProfileBanList implements org.bukkit.BanList {
@Override @Override
public org.bukkit.BanEntry addBan(String target, String reason, Date expires, String source) { 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); GameProfile profile = getProfile(target);
if (profile == null) { if (profile == null) {
@ -77,7 +77,7 @@ public class CraftProfileBanList implements org.bukkit.BanList {
@Override @Override
public boolean isBanned(String target) { public boolean isBanned(String target) {
Validate.notNull(target, "Target cannot be null"); Preconditions.checkArgument(target != null, "Target cannot be null");
GameProfile profile = getProfile(target); GameProfile profile = getProfile(target);
if (profile == null) { if (profile == null) {
@ -89,7 +89,7 @@ public class CraftProfileBanList implements org.bukkit.BanList {
@Override @Override
public void pardon(String target) { public void pardon(String target) {
Validate.notNull(target, "Target cannot be null"); Preconditions.checkArgument(target != null, "Target cannot be null");
GameProfile profile = getProfile(target); GameProfile profile = getProfile(target);
list.remove(profile); list.remove(profile);

Datei anzeigen

@ -585,9 +585,8 @@ public abstract class CraftRegionAccessor implements RegionAccessor {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public net.minecraft.world.entity.Entity createEntity(Location location, Class<? extends Entity> clazz, boolean randomizeData) throws IllegalArgumentException { public net.minecraft.world.entity.Entity createEntity(Location location, Class<? extends Entity> clazz, boolean randomizeData) throws IllegalArgumentException {
if (location == null || clazz == null) { Preconditions.checkArgument(location != null, "Location cannot be null");
throw new IllegalArgumentException("Location or entity class cannot be null"); Preconditions.checkArgument(clazz != null, "Entity class cannot be null");
}
net.minecraft.world.entity.Entity entity = null; net.minecraft.world.entity.Entity entity = null;
net.minecraft.world.level.World world = getHandle().getMinecraftWorld(); net.minecraft.world.level.World world = getHandle().getMinecraftWorld();
@ -798,11 +797,8 @@ public abstract class CraftRegionAccessor implements RegionAccessor {
entity = EntityTypes.WITHER.create(world); entity = EntityTypes.WITHER.create(world);
} else if (ComplexLivingEntity.class.isAssignableFrom(clazz)) { } else if (ComplexLivingEntity.class.isAssignableFrom(clazz)) {
if (EnderDragon.class.isAssignableFrom(clazz)) { if (EnderDragon.class.isAssignableFrom(clazz)) {
if (isNormalWorld()) { Preconditions.checkArgument(this.isNormalWorld(), "Cannot spawn entity %s during world generation", clazz.getName());
entity = EntityTypes.ENDER_DRAGON.create(getHandle().getMinecraftWorld()); entity = EntityTypes.ENDER_DRAGON.create(getHandle().getMinecraftWorld());
} else {
throw new IllegalArgumentException("Cannot spawn entity " + clazz.getName() + " during world generation");
}
} }
} else if (Ambient.class.isAssignableFrom(clazz)) { } else if (Ambient.class.isAssignableFrom(clazz)) {
if (Bat.class.isAssignableFrom(clazz)) { if (Bat.class.isAssignableFrom(clazz)) {

Datei anzeigen

@ -117,7 +117,6 @@ import net.minecraft.world.level.storage.WorldNBTStorage;
import net.minecraft.world.level.storage.loot.LootDataManager; import net.minecraft.world.level.storage.loot.LootDataManager;
import net.minecraft.world.level.validation.ContentValidationException; import net.minecraft.world.level.validation.ContentValidationException;
import net.minecraft.world.phys.Vec3D; import net.minecraft.world.phys.Vec3D;
import org.apache.commons.lang.Validate;
import org.bukkit.BanList; import org.bukkit.BanList;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
@ -553,7 +552,7 @@ public final class CraftServer implements Server {
@Override @Override
@Deprecated @Deprecated
public Player getPlayer(final String name) { 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); Player found = getPlayerExact(name);
// Try for an exact match first. // Try for an exact match first.
@ -579,7 +578,7 @@ public final class CraftServer implements Server {
@Override @Override
@Deprecated @Deprecated
public Player getPlayerExact(String name) { 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); EntityPlayer player = playerList.getPlayerByName(name);
return (player != null) ? player.getBukkitEntity() : null; return (player != null) ? player.getBukkitEntity() : null;
@ -587,8 +586,9 @@ public final class CraftServer implements Server {
@Override @Override
public Player getPlayer(UUID id) { 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) { if (player != null) {
return player.getBukkitEntity(); return player.getBukkitEntity();
} }
@ -604,9 +604,9 @@ public final class CraftServer implements Server {
@Override @Override
@Deprecated @Deprecated
public List<Player> matchPlayer(String partialName) { public List<Player> matchPlayer(String partialName) {
Validate.notNull(partialName, "PartialName cannot be null"); Preconditions.checkArgument(partialName != null, "partialName cannot be null");
List<Player> matchedPlayers = new ArrayList<Player>(); List<Player> matchedPlayers = new ArrayList<>();
for (Player iterPlayer : this.getOnlinePlayers()) { for (Player iterPlayer : this.getOnlinePlayers()) {
String iterPlayerName = iterPlayer.getName(); String iterPlayerName = iterPlayer.getName();
@ -792,8 +792,8 @@ public final class CraftServer implements Server {
@Override @Override
public int getTicksPerSpawns(SpawnCategory spawnCategory) { public int getTicksPerSpawns(SpawnCategory spawnCategory) {
Validate.notNull(spawnCategory, "SpawnCategory cannot be null"); Preconditions.checkArgument(spawnCategory != null, "SpawnCategory cannot be null");
Validate.isTrue(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory." + spawnCategory + " are not supported."); Preconditions.checkArgument(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory.%s are not supported", spawnCategory);
return this.configuration.getInt(CraftSpawnCategory.getConfigNameTicksPerSpawn(spawnCategory)); return this.configuration.getInt(CraftSpawnCategory.getConfigNameTicksPerSpawn(spawnCategory));
} }
@ -844,8 +844,8 @@ public final class CraftServer implements Server {
@Override @Override
public boolean dispatchCommand(CommandSender sender, String commandLine) { public boolean dispatchCommand(CommandSender sender, String commandLine) {
Validate.notNull(sender, "Sender cannot be null"); Preconditions.checkArgument(sender != null, "sender cannot be null");
Validate.notNull(commandLine, "CommandLine cannot be null"); Preconditions.checkArgument(commandLine != null, "commandLine cannot be null");
if (commandMap.dispatch(sender, commandLine)) { if (commandMap.dispatch(sender, commandLine)) {
return true; return true;
@ -1027,7 +1027,7 @@ public final class CraftServer implements Server {
@Override @Override
public World createWorld(WorldCreator creator) { public World createWorld(WorldCreator creator) {
Preconditions.checkState(console.getAllLevels().iterator().hasNext(), "Cannot create additional worlds on STARTUP"); 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(); String name = creator.name();
ChunkGenerator generator = creator.generator(); ChunkGenerator generator = creator.generator();
@ -1039,8 +1039,8 @@ public final class CraftServer implements Server {
return world; return world;
} }
if ((folder.exists()) && (!folder.isDirectory())) { if (folder.exists()) {
throw new IllegalArgumentException("File exists with the name '" + name + "' and isn't a folder"); Preconditions.checkArgument(folder.isDirectory(), "File (%s) exists and isn't a folder", name);
} }
if (generator == null) { if (generator == null) {
@ -1063,7 +1063,7 @@ public final class CraftServer implements Server {
actualDimension = WorldDimension.END; actualDimension = WorldDimension.END;
break; break;
default: default:
throw new IllegalArgumentException("Illegal dimension"); throw new IllegalArgumentException("Illegal dimension (" + creator.environment() + ")");
} }
Convertable.ConversionSession worldSession; Convertable.ConversionSession worldSession;
@ -1105,9 +1105,7 @@ public final class CraftServer implements Server {
worlddata.setModdedInfo(console.getServerModName(), console.getModdedStatus().shouldReportAsModified()); worlddata.setModdedInfo(console.getServerModName(), console.getModdedStatus().shouldReportAsModified());
if (console.options.has("forceUpgrade")) { if (console.options.has("forceUpgrade")) {
net.minecraft.server.Main.forceUpgrade(worldSession, DataConverterRegistry.getDataFixer(), console.options.has("eraseCache"), () -> { net.minecraft.server.Main.forceUpgrade(worldSession, DataConverterRegistry.getDataFixer(), console.options.has("eraseCache"), () -> true, iregistry);
return true;
}, iregistry);
} }
long j = BiomeManager.obfuscateSeed(creator.seed()); long j = BiomeManager.obfuscateSeed(creator.seed());
@ -1203,7 +1201,8 @@ public final class CraftServer implements Server {
@Override @Override
public World getWorld(String name) { 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)); return worlds.get(name.toLowerCase(java.util.Locale.ENGLISH));
} }
@ -1294,7 +1293,7 @@ public final class CraftServer implements Server {
@Override @Override
public List<Recipe> getRecipesFor(ItemStack result) { public List<Recipe> getRecipesFor(ItemStack result) {
Validate.notNull(result, "Result cannot be null"); Preconditions.checkArgument(result != null, "ItemStack cannot be null");
List<Recipe> results = new ArrayList<Recipe>(); List<Recipe> results = new ArrayList<Recipe>();
Iterator<Recipe> iter = recipeIterator(); Iterator<Recipe> iter = recipeIterator();
@ -1313,7 +1312,7 @@ public final class CraftServer implements Server {
@Override @Override
public Recipe getRecipe(NamespacedKey recipeKey) { 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); return getServer().getRecipeManager().byKey(CraftNamespacedKey.toMinecraft(recipeKey)).map(IRecipe::toBukkitRecipe).orElse(null);
} }
@ -1344,8 +1343,8 @@ public final class CraftServer implements Server {
@Override @Override
public ItemStack craftItem(ItemStack[] craftingMatrix, World world, Player player) { public ItemStack craftItem(ItemStack[] craftingMatrix, World world, Player player) {
Preconditions.checkArgument(world != null, "world must not be null"); Preconditions.checkArgument(world != null, "world cannot be null");
Preconditions.checkArgument(player != null, "player must not be null"); Preconditions.checkArgument(player != null, "player cannot be null");
CraftWorld craftWorld = (CraftWorld) world; CraftWorld craftWorld = (CraftWorld) world;
CraftPlayer craftPlayer = (CraftPlayer) player; CraftPlayer craftPlayer = (CraftPlayer) player;
@ -1575,7 +1574,7 @@ public final class CraftServer implements Server {
@Override @Override
public CraftMapView createMap(World world) { 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(); 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 // 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 @Override
public ItemStack createExplorerMap(World world, Location location, StructureType structureType, int radius, boolean findUnexplored) { public ItemStack createExplorerMap(World world, Location location, StructureType structureType, int radius, boolean findUnexplored) {
Validate.notNull(world, "World cannot be null"); Preconditions.checkArgument(world != null, "World cannot be null");
Validate.notNull(structureType, "StructureType cannot be null"); Preconditions.checkArgument(structureType != null, "StructureType cannot be null");
Validate.notNull(structureType.getMapIcon(), "Cannot create explorer maps for StructureType " + structureType.getName()); Preconditions.checkArgument(structureType.getMapIcon() != null, "Cannot create explorer maps for StructureType %s", structureType.getName());
WorldServer worldServer = ((CraftWorld) world).getHandle(); WorldServer worldServer = ((CraftWorld) world).getHandle();
Location structureLocation = world.locateNearestStructure(location, structureType, radius, findUnexplored); Location structureLocation = world.locateNearestStructure(location, structureType, radius, findUnexplored);
@ -1640,8 +1639,8 @@ public final class CraftServer implements Server {
@Override @Override
@Deprecated @Deprecated
public OfflinePlayer getOfflinePlayer(String name) { public OfflinePlayer getOfflinePlayer(String name) {
Validate.notNull(name, "Name cannot be null"); Preconditions.checkArgument(name != null, "name cannot be null");
Validate.notEmpty(name, "Name cannot be empty"); Preconditions.checkArgument(!name.isBlank(), "name cannot be empty");
OfflinePlayer result = getPlayerExact(name); OfflinePlayer result = getPlayerExact(name);
if (result == null) { if (result == null) {
@ -1663,7 +1662,7 @@ public final class CraftServer implements Server {
@Override @Override
public OfflinePlayer getOfflinePlayer(UUID id) { 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); OfflinePlayer result = getPlayer(id);
if (result == null) { if (result == null) {
@ -1708,14 +1707,16 @@ public final class CraftServer implements Server {
@Override @Override
public void banIP(String address) { 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); this.getBanList(org.bukkit.BanList.Type.IP).addBan(address, null, null, null);
} }
@Override @Override
public void unbanIP(String address) { 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); this.getBanList(org.bukkit.BanList.Type.IP).pardon(address);
} }
@ -1733,7 +1734,7 @@ public final class CraftServer implements Server {
@Override @Override
public BanList getBanList(BanList.Type type) { public BanList getBanList(BanList.Type type) {
Validate.notNull(type, "Type cannot be null"); Preconditions.checkArgument(type != null, "BanList.Type cannot be null");
switch (type) { switch (type) {
case IP: case IP:
@ -1794,7 +1795,7 @@ public final class CraftServer implements Server {
@Override @Override
public void setDefaultGameMode(GameMode mode) { public void setDefaultGameMode(GameMode mode) {
Validate.notNull(mode, "Mode cannot be null"); Preconditions.checkArgument(mode != null, "GameMode cannot be null");
for (World world : getWorlds()) { for (World world : getWorlds()) {
((CraftWorld) world).getHandle().serverLevelData.setGameType(EnumGamemode.byId(mode.getValue())); ((CraftWorld) world).getHandle().serverLevelData.setGameType(EnumGamemode.byId(mode.getValue()));
@ -1869,25 +1870,28 @@ public final class CraftServer implements Server {
@Override @Override
public Inventory createInventory(InventoryHolder owner, InventoryType type) { 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); return CraftInventoryCreator.INSTANCE.createInventory(owner, type);
} }
@Override @Override
public Inventory createInventory(InventoryHolder owner, InventoryType type, String title) { 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); return CraftInventoryCreator.INSTANCE.createInventory(owner, type, title);
} }
@Override @Override
public Inventory createInventory(InventoryHolder owner, int size) throws IllegalArgumentException { 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); return CraftInventoryCreator.INSTANCE.createInventory(owner, size);
} }
@Override @Override
public Inventory createInventory(InventoryHolder owner, int size, String title) throws IllegalArgumentException { 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); return CraftInventoryCreator.INSTANCE.createInventory(owner, size, title);
} }
@ -2063,10 +2067,8 @@ public final class CraftServer implements Server {
@Override @Override
public CraftIconCache loadServerIcon(File file) throws Exception { public CraftIconCache loadServerIcon(File file) throws Exception {
Validate.notNull(file, "File cannot be null"); Preconditions.checkArgument(file != null, "File cannot be null");
if (!file.isFile()) { Preconditions.checkArgument(file.isFile(), "File (%s) is not a valid file", file);
throw new IllegalArgumentException(file + " is not a file");
}
return loadServerIcon0(file); return loadServerIcon0(file);
} }
@ -2076,13 +2078,13 @@ public final class CraftServer implements Server {
@Override @Override
public CraftIconCache loadServerIcon(BufferedImage image) throws Exception { 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); return loadServerIcon0(image);
} }
static CraftIconCache loadServerIcon0(BufferedImage image) throws Exception { static CraftIconCache loadServerIcon0(BufferedImage image) throws Exception {
Validate.isTrue(image.getWidth() == 64, "Must be 64 pixels wide"); Preconditions.checkArgument(image.getWidth() == 64, "BufferedImage must be 64 pixels wide (%s)", image.getWidth());
Validate.isTrue(image.getHeight() == 64, "Must be 64 pixels high"); Preconditions.checkArgument(image.getHeight() == 64, "BufferedImage must be 64 pixels high (%s)", image.getHeight());
ByteArrayOutputStream bytebuf = new ByteArrayOutputStream(); ByteArrayOutputStream bytebuf = new ByteArrayOutputStream();
ImageIO.write(image, "PNG", bytebuf); ImageIO.write(image, "PNG", bytebuf);
@ -2102,7 +2104,7 @@ public final class CraftServer implements Server {
@Override @Override
public ChunkGenerator.ChunkData createChunkData(World world) { 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(); WorldServer handle = ((CraftWorld) world).getHandle();
return new OldCraftChunkData(world.getMinHeight(), world.getMaxHeight(), handle.registryAccess().registryOrThrow(Registries.BIOME)); return new OldCraftChunkData(world.getMinHeight(), world.getMaxHeight(), handle.registryAccess().registryOrThrow(Registries.BIOME));
} }
@ -2114,13 +2116,18 @@ public final class CraftServer implements Server {
@Override @Override
public KeyedBossBar createBossBar(NamespacedKey key, String title, BarColor barColor, BarStyle barStyle, BarFlag... barFlags) { 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]); BossBattleCustom bossBattleCustom = getServer().getCustomBossEvents().create(CraftNamespacedKey.toMinecraft(key), CraftChatMessage.fromString(title, true)[0]);
CraftKeyedBossbar craftKeyedBossbar = new CraftKeyedBossbar(bossBattleCustom); CraftKeyedBossbar craftKeyedBossbar = new CraftKeyedBossbar(bossBattleCustom);
craftKeyedBossbar.setColor(barColor); craftKeyedBossbar.setColor(barColor);
craftKeyedBossbar.setStyle(barStyle); craftKeyedBossbar.setStyle(barStyle);
for (BarFlag flag : barFlags) { for (BarFlag flag : barFlags) {
if (flag == null) {
continue;
}
craftKeyedBossbar.addFlag(flag); craftKeyedBossbar.addFlag(flag);
} }
@ -2161,7 +2168,7 @@ public final class CraftServer implements Server {
@Override @Override
public Entity getEntity(UUID uuid) { 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()) { for (WorldServer world : getServer().getAllLevels()) {
net.minecraft.world.entity.Entity entity = world.getEntity(uuid); net.minecraft.world.entity.Entity entity = world.getEntity(uuid);
@ -2175,7 +2182,7 @@ public final class CraftServer implements Server {
@Override @Override
public org.bukkit.advancement.Advancement getAdvancement(NamespacedKey key) { 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)); Advancement advancement = console.getAdvancements().getAdvancement(CraftNamespacedKey.toMinecraft(key));
return (advancement == null) ? null : advancement.bukkit; return (advancement == null) ? null : advancement.bukkit;
@ -2193,7 +2200,7 @@ public final class CraftServer implements Server {
@Override @Override
public BlockData createBlockData(org.bukkit.Material material) { 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); return createBlockData(material, (String) null);
} }
@ -2211,14 +2218,14 @@ public final class CraftServer implements Server {
@Override @Override
public BlockData createBlockData(String data) throws IllegalArgumentException { 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); return createBlockData(null, data);
} }
@Override @Override
public BlockData createBlockData(org.bukkit.Material material, String data) { 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); return CraftBlockData.newData(material, data);
} }
@ -2226,35 +2233,35 @@ public final class CraftServer implements Server {
@Override @Override
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T extends Keyed> org.bukkit.Tag<T> getTag(String registry, NamespacedKey tag, Class<T> clazz) { public <T extends Keyed> org.bukkit.Tag<T> getTag(String registry, NamespacedKey tag, Class<T> clazz) {
Validate.notNull(registry, "registry cannot be null"); Preconditions.checkArgument(registry != null, "registry cannot be null");
Validate.notNull(tag, "NamespacedKey cannot be null"); Preconditions.checkArgument(tag != null, "NamespacedKey tag cannot be null");
Validate.notNull(clazz, "Class cannot be null"); Preconditions.checkArgument(clazz != null, "Class clazz cannot be null");
MinecraftKey key = CraftNamespacedKey.toMinecraft(tag); MinecraftKey key = CraftNamespacedKey.toMinecraft(tag);
switch (registry) { switch (registry) {
case org.bukkit.Tag.REGISTRY_BLOCKS -> { 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<Block> blockTagKey = TagKey.create(Registries.BLOCK, key); TagKey<Block> blockTagKey = TagKey.create(Registries.BLOCK, key);
if (BuiltInRegistries.BLOCK.getTag(blockTagKey).isPresent()) { if (BuiltInRegistries.BLOCK.getTag(blockTagKey).isPresent()) {
return (org.bukkit.Tag<T>) new CraftBlockTag(BuiltInRegistries.BLOCK, blockTagKey); return (org.bukkit.Tag<T>) new CraftBlockTag(BuiltInRegistries.BLOCK, blockTagKey);
} }
} }
case org.bukkit.Tag.REGISTRY_ITEMS -> { 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<Item> itemTagKey = TagKey.create(Registries.ITEM, key); TagKey<Item> itemTagKey = TagKey.create(Registries.ITEM, key);
if (BuiltInRegistries.ITEM.getTag(itemTagKey).isPresent()) { if (BuiltInRegistries.ITEM.getTag(itemTagKey).isPresent()) {
return (org.bukkit.Tag<T>) new CraftItemTag(BuiltInRegistries.ITEM, itemTagKey); return (org.bukkit.Tag<T>) new CraftItemTag(BuiltInRegistries.ITEM, itemTagKey);
} }
} }
case org.bukkit.Tag.REGISTRY_FLUIDS -> { 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<FluidType> fluidTagKey = TagKey.create(Registries.FLUID, key); TagKey<FluidType> fluidTagKey = TagKey.create(Registries.FLUID, key);
if (BuiltInRegistries.FLUID.getTag(fluidTagKey).isPresent()) { if (BuiltInRegistries.FLUID.getTag(fluidTagKey).isPresent()) {
return (org.bukkit.Tag<T>) new CraftFluidTag(BuiltInRegistries.FLUID, fluidTagKey); return (org.bukkit.Tag<T>) new CraftFluidTag(BuiltInRegistries.FLUID, fluidTagKey);
} }
} }
case org.bukkit.Tag.REGISTRY_ENTITY_TYPES -> { 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<EntityTypes<?>> entityTagKey = TagKey.create(Registries.ENTITY_TYPE, key); TagKey<EntityTypes<?>> entityTagKey = TagKey.create(Registries.ENTITY_TYPE, key);
if (BuiltInRegistries.ENTITY_TYPE.getTag(entityTagKey).isPresent()) { if (BuiltInRegistries.ENTITY_TYPE.getTag(entityTagKey).isPresent()) {
return (org.bukkit.Tag<T>) new CraftEntityTag(BuiltInRegistries.ENTITY_TYPE, entityTagKey); return (org.bukkit.Tag<T>) new CraftEntityTag(BuiltInRegistries.ENTITY_TYPE, entityTagKey);
@ -2269,26 +2276,26 @@ public final class CraftServer implements Server {
@Override @Override
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T extends Keyed> Iterable<org.bukkit.Tag<T>> getTags(String registry, Class<T> clazz) { public <T extends Keyed> Iterable<org.bukkit.Tag<T>> getTags(String registry, Class<T> clazz) {
Validate.notNull(registry, "registry cannot be null"); Preconditions.checkArgument(registry != null, "registry cannot be null");
Validate.notNull(clazz, "Class cannot be null"); Preconditions.checkArgument(clazz != null, "Class clazz cannot be null");
switch (registry) { switch (registry) {
case org.bukkit.Tag.REGISTRY_BLOCKS -> { 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<Block> blockTags = BuiltInRegistries.BLOCK; IRegistry<Block> blockTags = BuiltInRegistries.BLOCK;
return blockTags.getTags().map(pair -> (org.bukkit.Tag<T>) new CraftBlockTag(blockTags, pair.getFirst())).collect(ImmutableList.toImmutableList()); return blockTags.getTags().map(pair -> (org.bukkit.Tag<T>) new CraftBlockTag(blockTags, pair.getFirst())).collect(ImmutableList.toImmutableList());
} }
case org.bukkit.Tag.REGISTRY_ITEMS -> { 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<Item> itemTags = BuiltInRegistries.ITEM; IRegistry<Item> itemTags = BuiltInRegistries.ITEM;
return itemTags.getTags().map(pair -> (org.bukkit.Tag<T>) new CraftItemTag(itemTags, pair.getFirst())).collect(ImmutableList.toImmutableList()); return itemTags.getTags().map(pair -> (org.bukkit.Tag<T>) new CraftItemTag(itemTags, pair.getFirst())).collect(ImmutableList.toImmutableList());
} }
case org.bukkit.Tag.REGISTRY_FLUIDS -> { 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<FluidType> fluidTags = BuiltInRegistries.FLUID; IRegistry<FluidType> fluidTags = BuiltInRegistries.FLUID;
return fluidTags.getTags().map(pair -> (org.bukkit.Tag<T>) new CraftFluidTag(fluidTags, pair.getFirst())).collect(ImmutableList.toImmutableList()); return fluidTags.getTags().map(pair -> (org.bukkit.Tag<T>) new CraftFluidTag(fluidTags, pair.getFirst())).collect(ImmutableList.toImmutableList());
} }
case org.bukkit.Tag.REGISTRY_ENTITY_TYPES -> { 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<EntityTypes<?>> entityTags = BuiltInRegistries.ENTITY_TYPE; IRegistry<EntityTypes<?>> entityTags = BuiltInRegistries.ENTITY_TYPE;
return entityTags.getTags().map(pair -> (org.bukkit.Tag<T>) new CraftEntityTag(entityTags, pair.getFirst())).collect(ImmutableList.toImmutableList()); return entityTags.getTags().map(pair -> (org.bukkit.Tag<T>) new CraftEntityTag(entityTags, pair.getFirst())).collect(ImmutableList.toImmutableList());
} }
@ -2298,7 +2305,7 @@ public final class CraftServer implements Server {
@Override @Override
public LootTable getLootTable(NamespacedKey key) { 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(); LootDataManager registry = getServer().getLootData();
return new CraftLootTable(key, registry.getLootTable(CraftNamespacedKey.toMinecraft(key))); return new CraftLootTable(key, registry.getLootTable(CraftNamespacedKey.toMinecraft(key)));
@ -2306,8 +2313,8 @@ public final class CraftServer implements Server {
@Override @Override
public List<Entity> selectEntities(CommandSender sender, String selector) { public List<Entity> selectEntities(CommandSender sender, String selector) {
Preconditions.checkArgument(selector != null, "Selector cannot be null"); Preconditions.checkArgument(selector != null, "selector cannot be null");
Preconditions.checkArgument(sender != null, "Sender cannot be null"); Preconditions.checkArgument(sender != null, "CommandSender sender cannot be null");
ArgumentEntity arg = ArgumentEntity.entities(); ArgumentEntity arg = ArgumentEntity.entities();
List<? extends net.minecraft.world.entity.Entity> nms; List<? extends net.minecraft.world.entity.Entity> nms;
@ -2315,7 +2322,7 @@ public final class CraftServer implements Server {
try { try {
StringReader reader = new StringReader(selector); StringReader reader = new StringReader(selector);
nms = arg.parse(reader, true).findEntities(VanillaCommandWrapper.getListener(sender)); 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) { } catch (CommandSyntaxException ex) {
throw new IllegalArgumentException("Could not parse selector: " + selector, ex); throw new IllegalArgumentException("Could not parse selector: " + selector, ex);
} }

Datei anzeigen

@ -11,7 +11,6 @@ import net.minecraft.stats.StatisticList;
import net.minecraft.world.entity.EntityTypes; import net.minecraft.world.entity.EntityTypes;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import org.apache.commons.lang.Validate;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Statistic; import org.bukkit.Statistic;
import org.bukkit.Statistic.Type; import org.bukkit.Statistic.Type;
@ -123,6 +122,7 @@ public enum CraftStatistic {
} }
public static org.bukkit.Statistic getBukkitStatistic(net.minecraft.stats.Statistic<?> statistic) { 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(); IRegistry statRegistry = statistic.getType().getRegistry();
MinecraftKey nmsKey = BuiltInRegistries.STAT_TYPE.getKey(statistic.getType()); 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) { 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) { if (entity.getName() != null) {
EntityTypes<?> nmsEntity = BuiltInRegistries.ENTITY_TYPE.get(new MinecraftKey(entity.getName())); 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<EntityTypes<?>> statistic) { public static EntityType getEntityTypeFromStatistic(net.minecraft.stats.Statistic<EntityTypes<?>> statistic) {
Preconditions.checkArgument(statistic != null, "NMS Statistic cannot be null");
MinecraftKey name = EntityTypes.getKey(statistic.getValue()); MinecraftKey name = EntityTypes.getKey(statistic.getValue());
return EntityType.fromName(name.getPath()); return EntityType.fromName(name.getPath());
} }
public static Material getMaterialFromStatistic(net.minecraft.stats.Statistic<?> statistic) { public static Material getMaterialFromStatistic(net.minecraft.stats.Statistic<?> statistic) {
if (statistic.getValue() instanceof Item) { if (statistic.getValue() instanceof Item statisticItemValue) {
return CraftMagicNumbers.getMaterial((Item) statistic.getValue()); return CraftMagicNumbers.getMaterial(statisticItemValue);
} }
if (statistic.getValue() instanceof Block) { if (statistic.getValue() instanceof Block statisticBlockValue) {
return CraftMagicNumbers.getMaterial((Block) statistic.getValue()); return CraftMagicNumbers.getMaterial(statisticBlockValue);
} }
return null; return null;
} }
@ -206,25 +208,25 @@ public enum CraftStatistic {
} }
public static int getStatistic(ServerStatisticManager manager, Statistic statistic) { public static int getStatistic(ServerStatisticManager manager, Statistic statistic) {
Validate.notNull(statistic, "Statistic cannot be null"); Preconditions.checkArgument(statistic != null, "Statistic cannot be null");
Validate.isTrue(statistic.getType() == Type.UNTYPED, "Must supply additional paramater for this statistic"); Preconditions.checkArgument(statistic.getType() == Type.UNTYPED, "Must supply additional parameter for this statistic");
return manager.getValue(CraftStatistic.getNMSStatistic(statistic)); return manager.getValue(CraftStatistic.getNMSStatistic(statistic));
} }
public static void incrementStatistic(ServerStatisticManager manager, Statistic statistic, int amount) { 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); setStatistic(manager, statistic, getStatistic(manager, statistic) + amount);
} }
public static void decrementStatistic(ServerStatisticManager manager, Statistic statistic, int 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); setStatistic(manager, statistic, getStatistic(manager, statistic) - amount);
} }
public static void setStatistic(ServerStatisticManager manager, Statistic statistic, int newValue) { public static void setStatistic(ServerStatisticManager manager, Statistic statistic, int newValue) {
Validate.notNull(statistic, "Statistic cannot be null"); Preconditions.checkArgument(statistic != null, "Statistic cannot be null");
Validate.isTrue(statistic.getType() == Type.UNTYPED, "Must supply additional paramater for this statistic"); Preconditions.checkArgument(statistic.getType() == Type.UNTYPED, "Must supply additional parameter for this statistic");
Validate.isTrue(newValue >= 0, "Value must be greater than or equal to 0"); Preconditions.checkArgument(newValue >= 0, "Value must be greater than or equal to 0");
net.minecraft.stats.Statistic nmsStatistic = CraftStatistic.getNMSStatistic(statistic); net.minecraft.stats.Statistic nmsStatistic = CraftStatistic.getNMSStatistic(statistic);
manager.setValue(null, nmsStatistic, newValue);; manager.setValue(null, nmsStatistic, newValue);;
} }
@ -238,31 +240,31 @@ public enum CraftStatistic {
} }
public static int getStatistic(ServerStatisticManager manager, Statistic statistic, Material material) { public static int getStatistic(ServerStatisticManager manager, Statistic statistic, Material material) {
Validate.notNull(statistic, "Statistic cannot be null"); Preconditions.checkArgument(statistic != null, "Statistic cannot be null");
Validate.notNull(material, "Material cannot be null"); Preconditions.checkArgument(material != null, "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.getType() == Type.BLOCK || statistic.getType() == Type.ITEM, "This statistic does not take a Material parameter");
net.minecraft.stats.Statistic nmsStatistic = CraftStatistic.getMaterialStatistic(statistic, material); 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); return manager.getValue(nmsStatistic);
} }
public static void incrementStatistic(ServerStatisticManager manager, Statistic statistic, Material material, int amount) { 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); setStatistic(manager, statistic, material, getStatistic(manager, statistic, material) + amount);
} }
public static void decrementStatistic(ServerStatisticManager manager, Statistic statistic, Material material, int 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); setStatistic(manager, statistic, material, getStatistic(manager, statistic, material) - amount);
} }
public static void setStatistic(ServerStatisticManager manager, Statistic statistic, Material material, int newValue) { public static void setStatistic(ServerStatisticManager manager, Statistic statistic, Material material, int newValue) {
Validate.notNull(statistic, "Statistic cannot be null"); Preconditions.checkArgument(statistic != null, "Statistic cannot be null");
Validate.notNull(material, "Material cannot be null"); Preconditions.checkArgument(material != null, "Material cannot be null");
Validate.isTrue(newValue >= 0, "Value must be greater than or equal to 0"); Preconditions.checkArgument(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.getType() == Type.BLOCK || statistic.getType() == Type.ITEM, "This statistic does not take a Material parameter");
net.minecraft.stats.Statistic nmsStatistic = CraftStatistic.getMaterialStatistic(statistic, material); 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); manager.setValue(null, nmsStatistic, newValue);
} }
@ -275,31 +277,31 @@ public enum CraftStatistic {
} }
public static int getStatistic(ServerStatisticManager manager, Statistic statistic, EntityType entityType) { public static int getStatistic(ServerStatisticManager manager, Statistic statistic, EntityType entityType) {
Validate.notNull(statistic, "Statistic cannot be null"); Preconditions.checkArgument(statistic != null, "Statistic cannot be null");
Validate.notNull(entityType, "EntityType cannot be null"); Preconditions.checkArgument(entityType != null, "EntityType cannot be null");
Validate.isTrue(statistic.getType() == Type.ENTITY, "This statistic does not take an EntityType parameter"); Preconditions.checkArgument(statistic.getType() == Type.ENTITY, "This statistic does not take an EntityType parameter");
net.minecraft.stats.Statistic nmsStatistic = CraftStatistic.getEntityStatistic(statistic, entityType); 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); return manager.getValue(nmsStatistic);
} }
public static void incrementStatistic(ServerStatisticManager manager, Statistic statistic, EntityType entityType, int amount) { 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); setStatistic(manager, statistic, entityType, getStatistic(manager, statistic, entityType) + amount);
} }
public static void decrementStatistic(ServerStatisticManager manager, Statistic statistic, EntityType entityType, int 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); setStatistic(manager, statistic, entityType, getStatistic(manager, statistic, entityType) - amount);
} }
public static void setStatistic(ServerStatisticManager manager, Statistic statistic, EntityType entityType, int newValue) { public static void setStatistic(ServerStatisticManager manager, Statistic statistic, EntityType entityType, int newValue) {
Validate.notNull(statistic, "Statistic cannot be null"); Preconditions.checkArgument(statistic != null, "Statistic cannot be null");
Validate.notNull(entityType, "EntityType cannot be null"); Preconditions.checkArgument(entityType != null, "EntityType cannot be null");
Validate.isTrue(newValue >= 0, "Value must be greater than or equal to 0"); Preconditions.checkArgument(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.getType() == Type.ENTITY, "This statistic does not take an EntityType parameter");
net.minecraft.stats.Statistic nmsStatistic = CraftStatistic.getEntityStatistic(statistic, entityType); 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); manager.setValue(null, nmsStatistic, newValue);
} }
} }

Datei anzeigen

@ -67,7 +67,6 @@ import net.minecraft.world.level.storage.SavedFile;
import net.minecraft.world.phys.AxisAlignedBB; import net.minecraft.world.phys.AxisAlignedBB;
import net.minecraft.world.phys.MovingObjectPosition; import net.minecraft.world.phys.MovingObjectPosition;
import net.minecraft.world.phys.Vec3D; import net.minecraft.world.phys.Vec3D;
import org.apache.commons.lang.Validate;
import org.bukkit.BlockChangeDelegate; import org.bukkit.BlockChangeDelegate;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Chunk; import org.bukkit.Chunk;
@ -486,14 +485,17 @@ public class CraftWorld extends CraftRegionAccessor implements World {
@Override @Override
public org.bukkit.entity.Item dropItem(Location loc, ItemStack item, Consumer<org.bukkit.entity.Item> function) { public org.bukkit.entity.Item dropItem(Location loc, ItemStack item, Consumer<org.bukkit.entity.Item> 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)); 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; entity.pickupDelay = 10;
if (function != null) { if (function != null) {
function.accept((org.bukkit.entity.Item) entity.getBukkitEntity()); function.accept(itemEntity);
} }
world.addFreshEntity(entity, SpawnReason.CUSTOM); world.addFreshEntity(entity, SpawnReason.CUSTOM);
return (org.bukkit.entity.Item) entity.getBukkitEntity(); return itemEntity;
} }
@Override @Override
@ -503,13 +505,13 @@ public class CraftWorld extends CraftRegionAccessor implements World {
@Override @Override
public org.bukkit.entity.Item dropItemNaturally(Location loc, ItemStack item, Consumer<org.bukkit.entity.Item> function) { public org.bukkit.entity.Item dropItemNaturally(Location loc, ItemStack item, Consumer<org.bukkit.entity.Item> 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 xs = (world.random.nextFloat() * 0.5F) + 0.25D;
double ys = (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; double zs = (world.random.nextFloat() * 0.5F) + 0.25D;
loc = loc.clone(); loc = loc.clone().add(xs, ys, zs);
loc.setX(loc.getX() + xs);
loc.setY(loc.getY() + ys);
loc.setZ(loc.getZ() + zs);
return dropItem(loc, item, function); return dropItem(loc, item, function);
} }
@ -520,9 +522,9 @@ public class CraftWorld extends CraftRegionAccessor implements World {
@Override @Override
public <T extends AbstractArrow> T spawnArrow(Location loc, Vector velocity, float speed, float spread, Class<T> clazz) { public <T extends AbstractArrow> T spawnArrow(Location loc, Vector velocity, float speed, float spread, Class<T> clazz) {
Validate.notNull(loc, "Can not spawn arrow with a null location"); Preconditions.checkArgument(loc != null, "Location cannot be null");
Validate.notNull(velocity, "Can not spawn arrow with a null velocity"); Preconditions.checkArgument(velocity != null, "Vector cannot be null");
Validate.notNull(clazz, "Can not spawn an arrow with no class"); Preconditions.checkArgument(clazz != null, "clazz Entity for the arrow cannot be null");
EntityArrow arrow; EntityArrow arrow;
if (TippedArrow.class.isAssignableFrom(clazz)) { if (TippedArrow.class.isAssignableFrom(clazz)) {
@ -544,17 +546,20 @@ public class CraftWorld extends CraftRegionAccessor implements World {
@Override @Override
public LightningStrike strikeLightning(Location loc) { public LightningStrike strikeLightning(Location loc) {
EntityLightning lightning = EntityTypes.LIGHTNING_BOLT.create(world); return strikeLightning0(loc, false);
lightning.moveTo(loc.getX(), loc.getY(), loc.getZ());
world.strikeLightning(lightning, LightningStrikeEvent.Cause.CUSTOM);
return (LightningStrike) lightning.getBukkitEntity();
} }
@Override @Override
public LightningStrike strikeLightningEffect(Location loc) { 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); EntityLightning lightning = EntityTypes.LIGHTNING_BOLT.create(world);
lightning.moveTo(loc.getX(), loc.getY(), loc.getZ()); lightning.moveTo(loc.getX(), loc.getY(), loc.getZ());
lightning.setVisualOnly(true); lightning.setVisualOnly(isVisual);
world.strikeLightning(lightning, LightningStrikeEvent.Cause.CUSTOM); world.strikeLightning(lightning, LightningStrikeEvent.Cause.CUSTOM);
return (LightningStrike) lightning.getBukkitEntity(); return (LightningStrike) lightning.getBukkitEntity();
} }
@ -822,8 +827,8 @@ public class CraftWorld extends CraftRegionAccessor implements World {
@Override @Override
public Collection<Entity> getNearbyEntities(Location location, double x, double y, double z, Predicate<Entity> filter) { public Collection<Entity> getNearbyEntities(Location location, double x, double y, double z, Predicate<Entity> filter) {
Validate.notNull(location, "Location is null!"); Preconditions.checkArgument(location != null, "Location cannot be null");
Validate.isTrue(this.equals(location.getWorld()), "Location is from different world!"); Preconditions.checkArgument(this.equals(location.getWorld()), "Location cannot be in a different world");
BoundingBox aabb = BoundingBox.of(location, x, y, z); BoundingBox aabb = BoundingBox.of(location, x, y, z);
return this.getNearbyEntities(aabb, filter); return this.getNearbyEntities(aabb, filter);
@ -836,7 +841,7 @@ public class CraftWorld extends CraftRegionAccessor implements World {
@Override @Override
public Collection<Entity> getNearbyEntities(BoundingBox boundingBox, Predicate<Entity> filter) { public Collection<Entity> getNearbyEntities(BoundingBox boundingBox, Predicate<Entity> 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()); AxisAlignedBB bb = new AxisAlignedBB(boundingBox.getMinX(), boundingBox.getMinY(), boundingBox.getMinZ(), boundingBox.getMaxX(), boundingBox.getMaxY(), boundingBox.getMaxZ());
List<net.minecraft.world.entity.Entity> entityList = getHandle().getEntities((net.minecraft.world.entity.Entity) null, bb, Predicates.alwaysTrue()); List<net.minecraft.world.entity.Entity> entityList = getHandle().getEntities((net.minecraft.world.entity.Entity) null, bb, Predicates.alwaysTrue());
@ -869,14 +874,14 @@ public class CraftWorld extends CraftRegionAccessor implements World {
@Override @Override
public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, double raySize, Predicate<Entity> filter) { public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, double raySize, Predicate<Entity> filter) {
Validate.notNull(start, "Start location is null!"); Preconditions.checkArgument(start != null, "Location start cannot be null");
Validate.isTrue(this.equals(start.getWorld()), "Start location is from different world!"); Preconditions.checkArgument(this.equals(start.getWorld()), "Location start cannot be in a different world");
start.checkFinite(); start.checkFinite();
Validate.notNull(direction, "Direction is null!"); Preconditions.checkArgument(direction != null, "Vector direction cannot be null");
direction.checkFinite(); 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) { if (maxDistance < 0.0D) {
return null; return null;
@ -921,15 +926,15 @@ public class CraftWorld extends CraftRegionAccessor implements World {
@Override @Override
public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode, boolean ignorePassableBlocks) { public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode, boolean ignorePassableBlocks) {
Validate.notNull(start, "Start location is null!"); Preconditions.checkArgument(start != null, "Location start cannot be null");
Validate.isTrue(this.equals(start.getWorld()), "Start location is from different world!"); Preconditions.checkArgument(this.equals(start.getWorld()), "Location start cannot be in a different world");
start.checkFinite(); start.checkFinite();
Validate.notNull(direction, "Direction is null!"); Preconditions.checkArgument(direction != null, "Vector direction cannot be null");
direction.checkFinite(); 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());
Validate.notNull(fluidCollisionMode, "Fluid collision mode is null!"); Preconditions.checkArgument(fluidCollisionMode != null, "FluidCollisionMode cannot be null");
if (maxDistance < 0.0D) { if (maxDistance < 0.0D) {
return null; return null;
@ -1114,10 +1119,11 @@ public class CraftWorld extends CraftRegionAccessor implements World {
@Override @Override
public <T> void playEffect(Location loc, Effect effect, T data, int radius) { public <T> void playEffect(Location loc, Effect effect, T data, int radius) {
if (data != 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 { } else {
// Special case: the axis is optional for ELECTRIC_SPARK // 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); int datavalue = CraftEffect.getDataValue(effect, data);
@ -1126,9 +1132,9 @@ public class CraftWorld extends CraftRegionAccessor implements World {
@Override @Override
public void playEffect(Location location, Effect effect, int data, int radius) { public void playEffect(Location location, Effect effect, int data, int radius) {
Validate.notNull(location, "Location cannot be null"); Preconditions.checkArgument(effect != null, "Effect cannot be null");
Validate.notNull(effect, "Effect cannot be null"); Preconditions.checkArgument(location != null, "Location cannot be null");
Validate.notNull(location.getWorld(), "World cannot be null"); Preconditions.checkArgument(location.getWorld() != null, "World of Location cannot be null");
int packetData = effect.getId(); int packetData = effect.getId();
PacketPlayOutWorldEvent packet = new PacketPlayOutWorldEvent(packetData, CraftLocation.toBlockPosition(location), data, false); PacketPlayOutWorldEvent packet = new PacketPlayOutWorldEvent(packetData, CraftLocation.toBlockPosition(location), data, false);
int distance; int distance;
@ -1147,15 +1153,15 @@ public class CraftWorld extends CraftRegionAccessor implements World {
@Override @Override
public FallingBlock spawnFallingBlock(Location location, MaterialData data) throws IllegalArgumentException { 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()); return spawnFallingBlock(location, data.getItemType(), data.getData());
} }
@Override @Override
public FallingBlock spawnFallingBlock(Location location, org.bukkit.Material material, byte data) throws IllegalArgumentException { public FallingBlock spawnFallingBlock(Location location, org.bukkit.Material material, byte data) throws IllegalArgumentException {
Validate.notNull(location, "Location cannot be null"); Preconditions.checkArgument(location != null, "Location cannot be null");
Validate.notNull(material, "Material cannot be null"); Preconditions.checkArgument(material != null, "Material cannot be null");
Validate.isTrue(material.isBlock(), "Material must be a block"); 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); EntityFallingBlock entity = EntityFallingBlock.fall(world, BlockPosition.containing(location.getX(), location.getY(), location.getZ()), CraftMagicNumbers.getBlock(material).defaultBlockState(), SpawnReason.CUSTOM);
return (FallingBlock) entity.getBukkitEntity(); return (FallingBlock) entity.getBukkitEntity();
@ -1163,8 +1169,8 @@ public class CraftWorld extends CraftRegionAccessor implements World {
@Override @Override
public FallingBlock spawnFallingBlock(Location location, BlockData data) throws IllegalArgumentException { public FallingBlock spawnFallingBlock(Location location, BlockData data) throws IllegalArgumentException {
Validate.notNull(location, "Location cannot be null"); Preconditions.checkArgument(location != null, "Location cannot be null");
Validate.notNull(data, "BlockData 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); EntityFallingBlock entity = EntityFallingBlock.fall(world, BlockPosition.containing(location.getX(), location.getY(), location.getZ()), ((CraftBlockData) data).getState(), SpawnReason.CUSTOM);
return (FallingBlock) entity.getBukkitEntity(); return (FallingBlock) entity.getBukkitEntity();
@ -1406,16 +1412,16 @@ public class CraftWorld extends CraftRegionAccessor implements World {
@Override @Override
public void setTicksPerSpawns(SpawnCategory spawnCategory, int ticksPerCategorySpawn) { public void setTicksPerSpawns(SpawnCategory spawnCategory, int ticksPerCategorySpawn) {
Validate.notNull(spawnCategory, "SpawnCategory cannot be null"); Preconditions.checkArgument(spawnCategory != null, "SpawnCategory cannot be null");
Validate.isTrue(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory." + spawnCategory + " are not supported."); Preconditions.checkArgument(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory.%s are not supported", spawnCategory);
world.ticksPerSpawnCategory.put(spawnCategory, (long) ticksPerCategorySpawn); world.ticksPerSpawnCategory.put(spawnCategory, (long) ticksPerCategorySpawn);
} }
@Override @Override
public long getTicksPerSpawns(SpawnCategory spawnCategory) { public long getTicksPerSpawns(SpawnCategory spawnCategory) {
Validate.notNull(spawnCategory, "SpawnCategory cannot be null"); Preconditions.checkArgument(spawnCategory != null, "SpawnCategory cannot be null");
Validate.isTrue(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory." + spawnCategory + " are not supported."); Preconditions.checkArgument(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory.%s are not supported", spawnCategory);
return world.ticksPerSpawnCategory.getLong(spawnCategory); return world.ticksPerSpawnCategory.getLong(spawnCategory);
} }
@ -1514,8 +1520,8 @@ public class CraftWorld extends CraftRegionAccessor implements World {
@Override @Override
public int getSpawnLimit(SpawnCategory spawnCategory) { public int getSpawnLimit(SpawnCategory spawnCategory) {
Validate.notNull(spawnCategory, "SpawnCategory cannot be null"); Preconditions.checkArgument(spawnCategory != null, "SpawnCategory cannot be null");
Validate.isTrue(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory." + spawnCategory + " are not supported."); Preconditions.checkArgument(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory.%s are not supported", spawnCategory);
int limit = spawnCategoryLimit.getOrDefault(spawnCategory, -1); int limit = spawnCategoryLimit.getOrDefault(spawnCategory, -1);
if (limit < 0) { if (limit < 0) {
@ -1526,8 +1532,8 @@ public class CraftWorld extends CraftRegionAccessor implements World {
@Override @Override
public void setSpawnLimit(SpawnCategory spawnCategory, int limit) { public void setSpawnLimit(SpawnCategory spawnCategory, int limit) {
Validate.notNull(spawnCategory, "SpawnCategory cannot be null"); Preconditions.checkArgument(spawnCategory != null, "SpawnCategory cannot be null");
Validate.isTrue(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory." + spawnCategory + " are not supported."); Preconditions.checkArgument(CraftSpawnCategory.isValidForLimits(spawnCategory), "SpawnCategory.%s are not supported", spawnCategory);
spawnCategoryLimit.put(spawnCategory, limit); spawnCategoryLimit.put(spawnCategory, limit);
} }
@ -1544,7 +1550,9 @@ public class CraftWorld extends CraftRegionAccessor implements World {
@Override @Override
public void playSound(Location loc, Sound sound, org.bukkit.SoundCategory category, float volume, float pitch) { 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 x = loc.getX();
double y = loc.getY(); double y = loc.getY();
@ -1555,7 +1563,10 @@ public class CraftWorld extends CraftRegionAccessor implements World {
@Override @Override
public void playSound(Location loc, String sound, org.bukkit.SoundCategory category, float volume, float pitch) { 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 x = loc.getX();
double y = loc.getY(); double y = loc.getY();
@ -1662,26 +1673,27 @@ public class CraftWorld extends CraftRegionAccessor implements World {
@Override @Override
public boolean isGameRule(String rule) { 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); return getGameRulesNMS().containsKey(rule);
} }
@Override @Override
public <T> T getGameRuleValue(GameRule<T> rule) { public <T> T getGameRuleValue(GameRule<T> 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()))); return convert(rule, getHandle().getGameRules().getRule(getGameRulesNMS().get(rule.getName())));
} }
@Override @Override
public <T> T getGameRuleDefault(GameRule<T> rule) { public <T> T getGameRuleDefault(GameRule<T> rule) {
Validate.notNull(rule, "GameRule cannot be null"); Preconditions.checkArgument(rule != null, "GameRule cannot be null");
return convert(rule, getGameRuleDefinitions().get(rule.getName()).createRule()); return convert(rule, getGameRuleDefinitions().get(rule.getName()).createRule());
} }
@Override @Override
public <T> boolean setGameRule(GameRule<T> rule, T newValue) { public <T> boolean setGameRule(GameRule<T> rule, T newValue) {
Validate.notNull(rule, "GameRule cannot be null"); Preconditions.checkArgument(rule != null, "GameRule cannot be null");
Validate.notNull(newValue, "GameRule value cannot be null"); Preconditions.checkArgument(newValue != null, "GameRule value cannot be null");
if (!isGameRule(rule.getName())) return false; if (!isGameRule(rule.getName())) return false;
@ -1781,8 +1793,8 @@ public class CraftWorld extends CraftRegionAccessor implements World {
@Override @Override
public <T> void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data, boolean force) { public <T> 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)) { if (data != null) {
throw new IllegalArgumentException("data should be " + particle.getDataType() + " got " + data.getClass()); Preconditions.checkArgument(particle.getDataType().isInstance(data), "data (%s) should be %s", data.getClass(), particle.getDataType());
} }
getHandle().sendParticles( getHandle().sendParticles(
null, // Sender null, // Sender
@ -1878,8 +1890,8 @@ public class CraftWorld extends CraftRegionAccessor implements World {
@Override @Override
public Raid locateNearestRaid(Location location, int radius) { public Raid locateNearestRaid(Location location, int radius) {
Validate.notNull(location, "Location cannot be null"); Preconditions.checkArgument(location != null, "Location cannot be null");
Validate.isTrue(radius >= 0, "Radius cannot be negative"); Preconditions.checkArgument(radius >= 0, "Radius value (%s) cannot be negative", radius);
PersistentRaid persistentRaid = world.getRaids(); PersistentRaid persistentRaid = world.getRaids();
net.minecraft.world.entity.raid.Raid raid = persistentRaid.getNearbyRaid(CraftLocation.toBlockPosition(location), radius * radius); net.minecraft.world.entity.raid.Raid raid = persistentRaid.getNearbyRaid(CraftLocation.toBlockPosition(location), radius * radius);

Datei anzeigen

@ -31,7 +31,6 @@ import net.minecraft.world.phys.MovingObjectPosition;
import net.minecraft.world.phys.MovingObjectPositionBlock; import net.minecraft.world.phys.MovingObjectPositionBlock;
import net.minecraft.world.phys.Vec3D; import net.minecraft.world.phys.Vec3D;
import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraft.world.phys.shapes.VoxelShape;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Chunk; import org.bukkit.Chunk;
import org.bukkit.FluidCollisionMode; import org.bukkit.FluidCollisionMode;
@ -392,10 +391,9 @@ public class CraftBlock implements Block {
if (o == this) { if (o == this) {
return true; return true;
} }
if (!(o instanceof CraftBlock)) { if (!(o instanceof CraftBlock other)) {
return false; return false;
} }
CraftBlock other = (CraftBlock) o;
return this.position.equals(other.position) && this.getWorld().equals(other.getWorld()); return this.position.equals(other.position) && this.getWorld().equals(other.getWorld());
} }
@ -593,15 +591,15 @@ public class CraftBlock implements Block {
@Override @Override
public RayTraceResult rayTrace(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode) { public RayTraceResult rayTrace(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode) {
Validate.notNull(start, "Start location is null!"); Preconditions.checkArgument(start != null, "Location start cannot be null");
Validate.isTrue(this.getWorld().equals(start.getWorld()), "Start location is from different world!"); Preconditions.checkArgument(this.getWorld().equals(start.getWorld()), "Location start cannot be a different world");
start.checkFinite(); start.checkFinite();
Validate.notNull(direction, "Direction is null!"); Preconditions.checkArgument(direction != null, "Vector direction cannot be null");
direction.checkFinite(); 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) { if (maxDistance < 0.0D) {
return null; return null;
} }
@ -634,7 +632,7 @@ public class CraftBlock implements Block {
@Override @Override
public boolean canPlace(BlockData data) { 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.block.state.IBlockData iblockdata = ((CraftBlockData) data).getState();
net.minecraft.world.level.World world = this.world.getMinecraftWorld(); net.minecraft.world.level.World world = this.world.getMinecraftWorld();

Datei anzeigen

@ -80,9 +80,7 @@ public class CraftBlockState implements BlockState {
} }
protected final void ensureNoWorldGeneration() { protected final void ensureNoWorldGeneration() {
if (isWorldGeneration()) { Preconditions.checkState(!isWorldGeneration(), "This operation is not supported during world generation!");
throw new IllegalStateException("This operation is not supported during world generation!");
}
} }
@Override @Override
@ -142,12 +140,8 @@ public class CraftBlockState implements BlockState {
if ((mat == null) || (mat.getData() == null)) { if ((mat == null) || (mat.getData() == null)) {
this.data = CraftMagicNumbers.getBlock(data); this.data = CraftMagicNumbers.getBlock(data);
} else { } else {
if ((data.getClass() == mat.getData()) || (data.getClass() == MaterialData.class)) { 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); this.data = CraftMagicNumbers.getBlock(data);
} else {
throw new IllegalArgumentException("Provided data is not of type "
+ mat.getData().getName() + ", found " + data.getClass().getName());
}
} }
} }
@ -322,8 +316,6 @@ public class CraftBlockState implements BlockState {
} }
protected void requirePlaced() { protected void requirePlaced() {
if (!isPlaced()) { Preconditions.checkState(isPlaced(), "The blockState must be placed to call this method");
throw new IllegalStateException("The blockState must be placed to call this method");
}
} }
} }

Datei anzeigen

@ -1,12 +1,10 @@
package org.bukkit.craftbukkit.block; package org.bukkit.craftbukkit.block;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import net.minecraft.core.BlockPosition;
import net.minecraft.world.level.block.EnumBlockMirror; import net.minecraft.world.level.block.EnumBlockMirror;
import net.minecraft.world.level.block.EnumBlockRotation; import net.minecraft.world.level.block.EnumBlockRotation;
import net.minecraft.world.level.block.entity.TileEntityStructure; import net.minecraft.world.level.block.entity.TileEntityStructure;
import net.minecraft.world.level.block.state.properties.BlockPropertyStructureMode; import net.minecraft.world.level.block.state.properties.BlockPropertyStructureMode;
import org.apache.commons.lang3.Validate;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.block.Structure; import org.bukkit.block.Structure;
import org.bukkit.block.structure.Mirror; import org.bukkit.block.structure.Mirror;
@ -32,7 +30,7 @@ public class CraftStructureBlock extends CraftBlockEntityState<TileEntityStructu
@Override @Override
public void setStructureName(String name) { public void setStructureName(String name) {
Preconditions.checkArgument(name != null, "Structure Name cannot be null"); Preconditions.checkArgument(name != null, "Structure name cannot be null");
getSnapshot().setStructureName(name); getSnapshot().setStructureName(name);
} }
@ -43,7 +41,8 @@ public class CraftStructureBlock extends CraftBlockEntityState<TileEntityStructu
@Override @Override
public void setAuthor(String author) { public void setAuthor(String author) {
Preconditions.checkArgument(author != null && !author.isEmpty(), "Author name cannot be null nor empty"); Preconditions.checkArgument(author != null, "Author name cannot be null");
Preconditions.checkArgument(!author.isBlank(), "Author name cannot be empty");
getSnapshot().author = author; getSnapshot().author = author;
} }
@ -60,9 +59,9 @@ public class CraftStructureBlock extends CraftBlockEntityState<TileEntityStructu
@Override @Override
public void setRelativePosition(BlockVector vector) { public void setRelativePosition(BlockVector vector) {
Validate.isTrue(isBetween(vector.getBlockX(), -MAX_SIZE, MAX_SIZE), "Structure Size (X) must be between -" + MAX_SIZE + " and " + MAX_SIZE); Preconditions.checkArgument(isBetween(vector.getBlockX(), -MAX_SIZE, MAX_SIZE), "Structure Size (X) must be between -%s and %s but got %s", MAX_SIZE, MAX_SIZE, vector.getBlockX());
Validate.isTrue(isBetween(vector.getBlockY(), -MAX_SIZE, MAX_SIZE), "Structure Size (Y) must be between -" + MAX_SIZE + " and " + MAX_SIZE); Preconditions.checkArgument(isBetween(vector.getBlockY(), -MAX_SIZE, MAX_SIZE), "Structure Size (Y) must be between -%s and %s but got %s", MAX_SIZE, MAX_SIZE, vector.getBlockY());
Validate.isTrue(isBetween(vector.getBlockZ(), -MAX_SIZE, MAX_SIZE), "Structure Size (Z) must be between -" + MAX_SIZE + " and " + MAX_SIZE); Preconditions.checkArgument(isBetween(vector.getBlockZ(), -MAX_SIZE, MAX_SIZE), "Structure Size (Z) must be between -%s and %s but got %s", MAX_SIZE, MAX_SIZE, vector.getBlockZ());
getSnapshot().structurePos = CraftBlockVector.toBlockPosition(vector); getSnapshot().structurePos = CraftBlockVector.toBlockPosition(vector);
} }
@ -73,14 +72,15 @@ public class CraftStructureBlock extends CraftBlockEntityState<TileEntityStructu
@Override @Override
public void setStructureSize(BlockVector vector) { public void setStructureSize(BlockVector vector) {
Validate.isTrue(isBetween(vector.getBlockX(), 0, MAX_SIZE), "Structure Size (X) must be between 0 and " + MAX_SIZE); Preconditions.checkArgument(isBetween(vector.getBlockX(), 0, MAX_SIZE), "Structure Size (X) must be between %s and %s but got %s", 0, MAX_SIZE, vector.getBlockX());
Validate.isTrue(isBetween(vector.getBlockY(), 0, MAX_SIZE), "Structure Size (Y) must be between 0 and " + MAX_SIZE); Preconditions.checkArgument(isBetween(vector.getBlockY(), 0, MAX_SIZE), "Structure Size (Y) must be between %s and %s but got %s", 0, MAX_SIZE, vector.getBlockY());
Validate.isTrue(isBetween(vector.getBlockZ(), 0, MAX_SIZE), "Structure Size (Z) must be between 0 and " + MAX_SIZE); Preconditions.checkArgument(isBetween(vector.getBlockZ(), 0, MAX_SIZE), "Structure Size (Z) must be between %s and %s but got %s", 0, MAX_SIZE, vector.getBlockZ());
getSnapshot().structureSize = CraftBlockVector.toBlockPosition(vector); getSnapshot().structureSize = CraftBlockVector.toBlockPosition(vector);
} }
@Override @Override
public void setMirror(Mirror mirror) { public void setMirror(Mirror mirror) {
Preconditions.checkArgument(mirror != null, "Mirror cannot be null");
getSnapshot().mirror = EnumBlockMirror.valueOf(mirror.name()); getSnapshot().mirror = EnumBlockMirror.valueOf(mirror.name());
} }
@ -91,6 +91,7 @@ public class CraftStructureBlock extends CraftBlockEntityState<TileEntityStructu
@Override @Override
public void setRotation(StructureRotation rotation) { public void setRotation(StructureRotation rotation) {
Preconditions.checkArgument(rotation != null, "StructureRotation cannot be null");
getSnapshot().rotation = EnumBlockRotation.valueOf(rotation.name()); getSnapshot().rotation = EnumBlockRotation.valueOf(rotation.name());
} }
@ -101,6 +102,7 @@ public class CraftStructureBlock extends CraftBlockEntityState<TileEntityStructu
@Override @Override
public void setUsageMode(UsageMode mode) { public void setUsageMode(UsageMode mode) {
Preconditions.checkArgument(mode != null, "UsageMode cannot be null");
getSnapshot().mode = BlockPropertyStructureMode.valueOf(mode.name()); getSnapshot().mode = BlockPropertyStructureMode.valueOf(mode.name());
} }
@ -141,7 +143,7 @@ public class CraftStructureBlock extends CraftBlockEntityState<TileEntityStructu
@Override @Override
public void setIntegrity(float integrity) { public void setIntegrity(float integrity) {
Validate.isTrue(isBetween(integrity, 0.0f, 1.0f), "Integrity must be between 0.0f and 1.0f"); Preconditions.checkArgument(isBetween(integrity, 0.0f, 1.0f), "Integrity must be between 0.0f and 1.0f but got %s", integrity);
getSnapshot().integrity = integrity; getSnapshot().integrity = integrity;
} }
@ -162,7 +164,7 @@ public class CraftStructureBlock extends CraftBlockEntityState<TileEntityStructu
@Override @Override
public void setMetadata(String metadata) { public void setMetadata(String metadata) {
Validate.notNull(metadata, "Structure metadata cannot be null"); Preconditions.checkArgument(metadata != null, "Structure metadata cannot be null");
if (getUsageMode() == UsageMode.DATA) { if (getUsageMode() == UsageMode.DATA) {
getSnapshot().metaData = metadata; getSnapshot().metaData = metadata;
} }

Datei anzeigen

@ -1,6 +1,7 @@
package org.bukkit.craftbukkit.command; package org.bukkit.craftbukkit.command;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.mojang.brigadier.ParseResults; import com.mojang.brigadier.ParseResults;
import com.mojang.brigadier.tree.CommandNode; import com.mojang.brigadier.tree.CommandNode;
import java.util.ArrayList; import java.util.ArrayList;
@ -11,7 +12,6 @@ import net.minecraft.commands.CommandListenerWrapper;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.server.dedicated.DedicatedServer;
import net.minecraft.world.entity.vehicle.EntityMinecartCommandBlock; import net.minecraft.world.entity.vehicle.EntityMinecartCommandBlock;
import org.apache.commons.lang.Validate;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.command.BlockCommandSender; import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -48,9 +48,9 @@ public final class VanillaCommandWrapper extends BukkitCommand {
@Override @Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args, Location location) throws IllegalArgumentException { public List<String> tabComplete(CommandSender sender, String alias, String[] args, Location location) throws IllegalArgumentException {
Validate.notNull(sender, "Sender cannot be null"); Preconditions.checkArgument(sender != null, "Sender cannot be null");
Validate.notNull(args, "Arguments cannot be null"); Preconditions.checkArgument(args != null, "Arguments cannot be null");
Validate.notNull(alias, "Alias cannot be null"); Preconditions.checkArgument(alias != null, "Alias cannot be null");
CommandListenerWrapper icommandlistener = getListener(sender); CommandListenerWrapper icommandlistener = getListener(sender);
ParseResults<CommandListenerWrapper> parsed = dispatcher.getDispatcher().parse(toDispatcher(args, getName()), icommandlistener); ParseResults<CommandListenerWrapper> parsed = dispatcher.getDispatcher().parse(toDispatcher(args, getName()), icommandlistener);

Datei anzeigen

@ -1,9 +1,9 @@
package org.bukkit.craftbukkit.entity; package org.bukkit.craftbukkit.entity;
import com.google.common.base.Preconditions;
import java.util.UUID; import java.util.UUID;
import net.minecraft.world.entity.ai.attributes.GenericAttributes; import net.minecraft.world.entity.ai.attributes.GenericAttributes;
import net.minecraft.world.entity.animal.horse.EntityHorseAbstract; import net.minecraft.world.entity.animal.horse.EntityHorseAbstract;
import org.apache.commons.lang.Validate;
import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.craftbukkit.inventory.CraftInventoryAbstractHorse; import org.bukkit.craftbukkit.inventory.CraftInventoryAbstractHorse;
import org.bukkit.entity.AbstractHorse; import org.bukkit.entity.AbstractHorse;
@ -34,8 +34,7 @@ public abstract class CraftAbstractHorse extends CraftAnimals implements Abstrac
@Override @Override
public void setDomestication(int value) { public void setDomestication(int value) {
Validate.isTrue(value >= 0, "Domestication cannot be less than zero"); Preconditions.checkArgument(value >= 0 && value <= this.getMaxDomestication(), "Domestication level (%s) need to be between %s and %s (max domestication)", value, 0, this.getMaxDomestication());
Validate.isTrue(value <= getMaxDomestication(), "Domestication cannot be greater than the max domestication");
getHandle().setTemper(value); getHandle().setTemper(value);
} }
@ -46,7 +45,7 @@ public abstract class CraftAbstractHorse extends CraftAnimals implements Abstrac
@Override @Override
public void setMaxDomestication(int value) { 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; getHandle().maxDomestication = value;
} }
@ -57,7 +56,7 @@ public abstract class CraftAbstractHorse extends CraftAnimals implements Abstrac
@Override @Override
public void setJumpStrength(double strength) { 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); getHandle().getAttribute(GenericAttributes.JUMP_STRENGTH).setBaseValue(strength);
} }

Datei anzeigen

@ -1,12 +1,12 @@
package org.bukkit.craftbukkit.entity; package org.bukkit.craftbukkit.entity;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import java.util.List; import java.util.List;
import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectList; import net.minecraft.world.effect.MobEffectList;
import net.minecraft.world.entity.EntityAreaEffectCloud; import net.minecraft.world.entity.EntityAreaEffectCloud;
import net.minecraft.world.entity.EntityLiving; import net.minecraft.world.entity.EntityLiving;
import org.apache.commons.lang.Validate;
import org.bukkit.Color; import org.bukkit.Color;
import org.bukkit.Particle; import org.bukkit.Particle;
import org.bukkit.craftbukkit.CraftParticle; import org.bukkit.craftbukkit.CraftParticle;
@ -205,7 +205,7 @@ public class CraftAreaEffectCloud extends CraftEntity implements AreaEffectCloud
@Override @Override
public void setBasePotionData(PotionData data) { 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)); getHandle().setPotionType(CraftPotionUtil.fromBukkit(data));
} }
@ -222,10 +222,10 @@ public class CraftAreaEffectCloud extends CraftEntity implements AreaEffectCloud
@Override @Override
public void setSource(ProjectileSource shooter) { public void setSource(ProjectileSource shooter) {
if (shooter instanceof CraftLivingEntity) { if (shooter instanceof CraftLivingEntity craftLivingEntity) {
getHandle().setOwner((EntityLiving) ((CraftLivingEntity) shooter).getHandle()); getHandle().setOwner(craftLivingEntity.getHandle());
} else { } else {
getHandle().setOwner((EntityLiving) null); getHandle().setOwner(null);
} }
} }
} }

Datei anzeigen

@ -3,11 +3,9 @@ package org.bukkit.craftbukkit.entity;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import net.minecraft.core.BlockPosition; import net.minecraft.core.BlockPosition;
import net.minecraft.world.entity.projectile.EntityArrow; import net.minecraft.world.entity.projectile.EntityArrow;
import org.apache.commons.lang.Validate;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.entity.AbstractArrow; import org.bukkit.entity.AbstractArrow;
import org.bukkit.entity.AbstractArrow.PickupStatus;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import org.bukkit.projectiles.ProjectileSource; import org.bukkit.projectiles.ProjectileSource;
@ -20,7 +18,7 @@ public class CraftArrow extends AbstractProjectile implements AbstractArrow {
@Override @Override
public void setKnockbackStrength(int knockbackStrength) { 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); getHandle().setKnockback(knockbackStrength);
} }
@ -36,7 +34,7 @@ public class CraftArrow extends AbstractProjectile implements AbstractArrow {
@Override @Override
public void setDamage(double damage) { 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); getHandle().setBaseDamage(damage);
} }
@ -47,7 +45,7 @@ public class CraftArrow extends AbstractProjectile implements AbstractArrow {
@Override @Override
public void setPierceLevel(int pierceLevel) { 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); getHandle().setPierceLevel((byte) pierceLevel);
} }
@ -99,7 +97,7 @@ public class CraftArrow extends AbstractProjectile implements AbstractArrow {
@Override @Override
public void setPickupStatus(PickupStatus status) { public void setPickupStatus(PickupStatus status) {
Preconditions.checkNotNull(status, "status"); Preconditions.checkArgument(status != null, "PickupStatus cannot be null");
getHandle().pickup = EntityArrow.PickupStatus.byOrdinal(status.ordinal()); getHandle().pickup = EntityArrow.PickupStatus.byOrdinal(status.ordinal());
} }

Datei anzeigen

@ -615,7 +615,7 @@ public abstract class CraftEntity implements org.bukkit.entity.Entity {
@Override @Override
public void setFreezeTicks(int ticks) { 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); getHandle().setTicksFrozen(ticks);
} }
@ -681,17 +681,12 @@ public abstract class CraftEntity implements org.bukkit.entity.Entity {
@Override @Override
public List<org.bukkit.entity.Entity> getPassengers() { public List<org.bukkit.entity.Entity> getPassengers() {
return Lists.newArrayList(Lists.transform(getHandle().passengers, new Function<Entity, org.bukkit.entity.Entity>() { return Lists.newArrayList(Lists.transform(getHandle().passengers, (Function<Entity, org.bukkit.entity.Entity>) input -> input.getBukkitEntity()));
@Override
public org.bukkit.entity.Entity apply(Entity input) {
return input.getBukkitEntity();
}
}));
} }
@Override @Override
public boolean addPassenger(org.bukkit.entity.Entity passenger) { 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."); Preconditions.checkArgument(!this.equals(passenger), "Entity cannot ride itself.");
return ((CraftEntity) passenger).getHandle().startRiding(getHandle(), true); return ((CraftEntity) passenger).getHandle().startRiding(getHandle(), true);
@ -699,7 +694,7 @@ public abstract class CraftEntity implements org.bukkit.entity.Entity {
@Override @Override
public boolean removePassenger(org.bukkit.entity.Entity passenger) { 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(); ((CraftEntity) passenger).getHandle().stopRiding();
return true; return true;
@ -752,9 +747,7 @@ public abstract class CraftEntity implements org.bukkit.entity.Entity {
@Override @Override
public void setTicksLived(int value) { public void setTicksLived(int value) {
if (value <= 0) { Preconditions.checkArgument(value > 0, "Age value (%s) must be positive", value);
throw new IllegalArgumentException("Age must be at least 1 tick");
}
getHandle().tickCount = value; getHandle().tickCount = value;
} }

Datei anzeigen

@ -1,7 +1,7 @@
package org.bukkit.craftbukkit.entity; package org.bukkit.craftbukkit.entity;
import com.google.common.base.Preconditions;
import net.minecraft.world.entity.projectile.EntityFireball; import net.minecraft.world.entity.projectile.EntityFireball;
import org.apache.commons.lang.Validate;
import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import org.bukkit.entity.Fireball; import org.bukkit.entity.Fireball;
@ -55,7 +55,7 @@ public class CraftFireball extends AbstractProjectile implements Fireball {
@Override @Override
public void setDirection(Vector direction) { 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()); getHandle().setDirection(direction.getX(), direction.getY(), direction.getZ());
update(); // SPIGOT-6579 update(); // SPIGOT-6579
} }

Datei anzeigen

@ -1,14 +1,12 @@
package org.bukkit.craftbukkit.entity; package org.bukkit.craftbukkit.entity;
import com.google.common.base.Preconditions;
import net.minecraft.core.BlockPosition; import net.minecraft.core.BlockPosition;
import net.minecraft.util.MathHelper;
import net.minecraft.world.entity.projectile.EntityFishingHook; import net.minecraft.world.entity.projectile.EntityFishingHook;
import org.apache.commons.lang.Validate;
import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import org.bukkit.entity.FishHook; import org.bukkit.entity.FishHook;
import org.bukkit.entity.FishHook.HookState;
public class CraftFishHook extends CraftProjectile implements FishHook { public class CraftFishHook extends CraftProjectile implements FishHook {
private double biteChance = -1; private double biteChance = -1;
@ -39,8 +37,8 @@ public class CraftFishHook extends CraftProjectile implements FishHook {
@Override @Override
public void setMinWaitTime(int minWaitTime) { 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(); 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; hook.minWaitTime = minWaitTime;
} }
@ -51,14 +49,14 @@ public class CraftFishHook extends CraftProjectile implements FishHook {
@Override @Override
public void setMaxWaitTime(int maxWaitTime) { 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(); 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; hook.maxWaitTime = maxWaitTime;
} }
@Override @Override
public void setWaitTime(int min, int max) { 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().minWaitTime = min;
getHandle().maxWaitTime = max; getHandle().maxWaitTime = max;
} }
@ -70,7 +68,7 @@ public class CraftFishHook extends CraftProjectile implements FishHook {
@Override @Override
public void setMinLureTime(int minLureTime) { 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; getHandle().minLureTime = minLureTime;
} }
@ -81,13 +79,13 @@ public class CraftFishHook extends CraftProjectile implements FishHook {
@Override @Override
public void setMaxLureTime(int maxLureTime) { 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; getHandle().maxLureTime = maxLureTime;
} }
@Override @Override
public void setLureTime(int min, int max) { 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().minLureTime = min;
getHandle().maxLureTime = max; getHandle().maxLureTime = max;
} }
@ -99,7 +97,7 @@ public class CraftFishHook extends CraftProjectile implements FishHook {
@Override @Override
public void setMinLureAngle(float minLureAngle) { 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; getHandle().minLureAngle = minLureAngle;
} }
@ -110,13 +108,13 @@ public class CraftFishHook extends CraftProjectile implements FishHook {
@Override @Override
public void setMaxLureAngle(float maxLureAngle) { 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; getHandle().maxLureAngle = maxLureAngle;
} }
@Override @Override
public void setLureAngle(float min, float max) { 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().minLureAngle = min;
getHandle().maxLureAngle = max; getHandle().maxLureAngle = max;
} }
@ -166,7 +164,7 @@ public class CraftFishHook extends CraftProjectile implements FishHook {
@Override @Override
public void setBiteChance(double chance) { 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; this.biteChance = chance;
} }

Datei anzeigen

@ -85,8 +85,8 @@ public class CraftFox extends CraftAnimals implements Fox {
@Override @Override
public void setFirstTrustedPlayer(AnimalTamer player) { public void setFirstTrustedPlayer(AnimalTamer player) {
if (player == null && getHandle().getEntityData().get(EntityFox.DATA_TRUSTED_ID_1).isPresent()) { if (player == null) {
throw new IllegalStateException("Must remove second trusted player first"); 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())); 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 @Override
public void setSecondTrustedPlayer(AnimalTamer player) { public void setSecondTrustedPlayer(AnimalTamer player) {
if (player != null && !getHandle().getEntityData().get(EntityFox.DATA_TRUSTED_ID_0).isPresent()) { if (player != null) {
throw new IllegalStateException("Must add first trusted player first"); 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())); getHandle().getEntityData().set(EntityFox.DATA_TRUSTED_ID_1, player == null ? Optional.empty() : Optional.of(player.getUniqueId()));

Datei anzeigen

@ -1,16 +1,13 @@
package org.bukkit.craftbukkit.entity; 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.EntityHorse;
import net.minecraft.world.entity.animal.horse.HorseColor; import net.minecraft.world.entity.animal.horse.HorseColor;
import net.minecraft.world.entity.animal.horse.HorseStyle; import net.minecraft.world.entity.animal.horse.HorseStyle;
import org.apache.commons.lang.Validate;
import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.craftbukkit.inventory.CraftInventoryHorse; import org.bukkit.craftbukkit.inventory.CraftInventoryHorse;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import org.bukkit.entity.Horse; 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; import org.bukkit.inventory.HorseInventory;
public class CraftHorse extends CraftAbstractHorse implements Horse { public class CraftHorse extends CraftAbstractHorse implements Horse {
@ -36,7 +33,7 @@ public class CraftHorse extends CraftAbstractHorse implements Horse {
@Override @Override
public void setColor(Color color) { 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()); getHandle().setVariantAndMarkings(HorseColor.byId(color.ordinal()), getHandle().getMarkings());
} }
@ -47,7 +44,7 @@ public class CraftHorse extends CraftAbstractHorse implements Horse {
@Override @Override
public void setStyle(Style style) { 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())); getHandle().setVariantAndMarkings(getHandle().getVariant(), HorseStyle.byId(style.ordinal()));
} }

Datei anzeigen

@ -247,9 +247,7 @@ public class CraftHumanEntity extends CraftLivingEntity implements HumanEntity {
@Override @Override
public void setGameMode(GameMode mode) { public void setGameMode(GameMode mode) {
if (mode == null) { Preconditions.checkArgument(mode != null, "GameMode cannot be null");
throw new IllegalArgumentException("Mode cannot be null");
}
this.mode = mode; this.mode = mode;
} }

Datei anzeigen

@ -5,7 +5,6 @@ import net.minecraft.core.EnumDirection;
import net.minecraft.world.entity.decoration.EntityHanging; import net.minecraft.world.entity.decoration.EntityHanging;
import net.minecraft.world.entity.decoration.EntityItemFrame; import net.minecraft.world.entity.decoration.EntityItemFrame;
import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.Blocks;
import org.apache.commons.lang.Validate;
import org.bukkit.Rotation; import org.bukkit.Rotation;
import org.bukkit.block.BlockFace; import org.bukkit.block.BlockFace;
import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.CraftServer;
@ -75,7 +74,7 @@ public class CraftItemFrame extends CraftHanging implements ItemFrame {
@Override @Override
public void setItemDropChance(float chance) { 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; getHandle().dropChance = chance;
} }
@ -110,7 +109,7 @@ public class CraftItemFrame extends CraftHanging implements ItemFrame {
@Override @Override
public void setRotation(Rotation rotation) { public void setRotation(Rotation rotation) {
Validate.notNull(rotation, "Rotation cannot be null"); Preconditions.checkArgument(rotation != null, "Rotation cannot be null");
getHandle().setRotation(toInteger(rotation)); getHandle().setRotation(toInteger(rotation));
} }

Datei anzeigen

@ -40,7 +40,6 @@ import net.minecraft.world.entity.projectile.EntityThrownExpBottle;
import net.minecraft.world.entity.projectile.EntityThrownTrident; import net.minecraft.world.entity.projectile.EntityThrownTrident;
import net.minecraft.world.entity.projectile.EntityTippedArrow; import net.minecraft.world.entity.projectile.EntityTippedArrow;
import net.minecraft.world.entity.projectile.EntityWitherSkull; import net.minecraft.world.entity.projectile.EntityWitherSkull;
import org.apache.commons.lang.Validate;
import org.bukkit.FluidCollisionMode; import org.bukkit.FluidCollisionMode;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
@ -113,9 +112,7 @@ public class CraftLivingEntity extends CraftEntity implements LivingEntity {
@Override @Override
public void setHealth(double health) { public void setHealth(double health) {
health = (float) health; health = (float) health;
if ((health < 0) || (health > getMaxHealth())) { Preconditions.checkArgument(health >= 0 && health <= this.getMaxHealth(), "Health value (%s) must be between 0 and %s", health, this.getMaxHealth());
throw new IllegalArgumentException("Health must be between 0 and " + getMaxHealth() + "(" + health + ")");
}
// during world generation, we don't want to run logic for dropping items and xp // during world generation, we don't want to run logic for dropping items and xp
if (getHandle().generation && health == 0) { if (getHandle().generation && health == 0) {
@ -149,7 +146,7 @@ public class CraftLivingEntity extends CraftEntity implements LivingEntity {
@Override @Override
public void setMaxHealth(double amount) { 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); 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()); 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) { if (velocity != null) {
((T) launch.getBukkitEntity()).setVelocity(velocity); ((T) launch.getBukkitEntity()).setVelocity(velocity);
@ -562,9 +559,7 @@ public class CraftLivingEntity extends CraftEntity implements LivingEntity {
@Override @Override
public Entity getLeashHolder() throws IllegalStateException { public Entity getLeashHolder() throws IllegalStateException {
if (!isLeashed()) { Preconditions.checkState(isLeashed(), "Entity not leashed");
throw new IllegalStateException("Entity not leashed");
}
return ((EntityInsentient) getHandle()).getLeashHolder().getBukkitEntity(); return ((EntityInsentient) getHandle()).getLeashHolder().getBukkitEntity();
} }

Datei anzeigen

@ -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.MapIcon;
import net.minecraft.world.level.saveddata.maps.WorldMap; import net.minecraft.world.level.saveddata.maps.WorldMap;
import net.minecraft.world.phys.Vec3D; import net.minecraft.world.phys.Vec3D;
import org.apache.commons.lang.Validate;
import org.bukkit.BanList; import org.bukkit.BanList;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.DyeColor; import org.bukkit.DyeColor;
@ -242,15 +241,13 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
@Override @Override
public void sendRawMessage(String message) { public void sendRawMessage(String message) {
if (getHandle().connection == null) return; this.sendRawMessage(null, message);
for (IChatBaseComponent component : CraftChatMessage.fromString(message)) {
getHandle().sendSystemMessage(component);
}
} }
@Override @Override
public void sendRawMessage(UUID sender, String message) { public void sendRawMessage(UUID sender, String message) {
Preconditions.checkArgument(message != null, "message cannot be null");
if (getHandle().connection == null) return; if (getHandle().connection == null) return;
for (IChatBaseComponent component : CraftChatMessage.fromString(message)) { for (IChatBaseComponent component : CraftChatMessage.fromString(message)) {
@ -382,6 +379,8 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
@Override @Override
public void setCompassTarget(Location loc) { public void setCompassTarget(Location loc) {
Preconditions.checkArgument(loc != null, "Location cannot be null");
if (getHandle().connection == null) return; if (getHandle().connection == null) return;
// Do not directly assign here, from the packethandler we'll assign it. // Do not directly assign here, from the packethandler we'll assign it.
@ -395,6 +394,8 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
@Override @Override
public void chat(String msg) { public void chat(String msg) {
Preconditions.checkArgument(msg != null, "msg cannot be null");
if (getHandle().connection == null) return; if (getHandle().connection == null) return;
getHandle().connection.chat(msg, PlayerChatMessage.system(msg), false); getHandle().connection.chat(msg, PlayerChatMessage.system(msg), false);
@ -402,109 +403,44 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
@Override @Override
public boolean performCommand(String command) { public boolean performCommand(String command) {
Preconditions.checkArgument(command != null, "command cannot be null");
return server.dispatchCommand(this, command); return server.dispatchCommand(this, command);
} }
@Override @Override
public void playNote(Location loc, byte instrument, byte note) { public void playNote(Location loc, byte instrument, byte note) {
if (getHandle().connection == null) return; playNote(loc, Instrument.getByType(instrument), new Note(note));
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()));
} }
@Override @Override
public void playNote(Location loc, Instrument instrument, Note note) { 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; if (getHandle().connection == null) return;
String instrumentName = null; String instrumentName = switch (instrument.ordinal()) {
switch (instrument.ordinal()) { case 0 -> "harp";
case 0: case 1 -> "basedrum";
instrumentName = "harp"; case 2 -> "snare";
break; case 3 -> "hat";
case 1: case 4 -> "bass";
instrumentName = "basedrum"; case 5 -> "flute";
break; case 6 -> "bell";
case 2: case 7 -> "guitar";
instrumentName = "snare"; case 8 -> "chime";
break; case 9 -> "xylophone";
case 3: case 10 -> "iron_xylophone";
instrumentName = "hat"; case 11 -> "cow_bell";
break; case 12 -> "didgeridoo";
case 4: case 13 -> "bit";
instrumentName = "bass"; case 14 -> "banjo";
break; case 15 -> "pling";
case 5: case 16 -> "xylophone";
instrumentName = "flute"; default -> null;
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;
}
float f = (float) Math.pow(2.0D, (note.getId() - 12.0D) / 12.0D); 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())); 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 @Override
public void playSound(Location loc, Sound sound, org.bukkit.SoundCategory category, float volume, float pitch) { 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()); playSound0(loc, BuiltInRegistries.SOUND_EVENT.wrapAsHolder(CraftSound.getSoundEffect(sound)), net.minecraft.sounds.SoundCategory.valueOf(category.name()), volume, pitch);
getHandle().connection.send(packet);
} }
@Override @Override
public void playSound(Location loc, String sound, org.bukkit.SoundCategory category, float volume, float pitch) { 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<SoundEffect> 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); getHandle().connection.send(packet);
} }
@ -547,17 +492,29 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
@Override @Override
public void playSound(org.bukkit.entity.Entity entity, Sound sound, org.bukkit.SoundCategory category, float volume, float pitch) { 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()); playSound0(entity, BuiltInRegistries.SOUND_EVENT.wrapAsHolder(CraftSound.getSoundEffect(sound)), net.minecraft.sounds.SoundCategory.valueOf(category.name()), volume, pitch);
getHandle().connection.send(packet);
} }
@Override @Override
public void playSound(org.bukkit.entity.Entity entity, String sound, org.bukkit.SoundCategory category, float volume, float pitch) { 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<SoundEffect> 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); getHandle().connection.send(packet);
} }
@ -599,6 +556,9 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
@Override @Override
public void playEffect(Location loc, Effect effect, int data) { 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; if (getHandle().connection == null) return;
int packetData = effect.getId(); int packetData = effect.getId();
@ -608,11 +568,13 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
@Override @Override
public <T> void playEffect(Location loc, Effect effect, T data) { public <T> void playEffect(Location loc, Effect effect, T data) {
Preconditions.checkArgument(effect != null, "Effect cannot be null");
if (data != 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 { } else {
// Special case: the axis is optional for ELECTRIC_SPARK // 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); int datavalue = CraftEffect.getDataValue(effect, data);
@ -725,19 +687,15 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
@Override @Override
public void sendSignChange(Location loc, String[] lines, DyeColor dyeColor, boolean hasGlowingText) { public void sendSignChange(Location loc, String[] lines, DyeColor dyeColor, boolean hasGlowingText) {
if (getHandle().connection == null) { Preconditions.checkArgument(loc != null, "Location cannot be null");
return; Preconditions.checkArgument(dyeColor != null, "DyeColor cannot be null");
}
if (lines == null) { if (lines == null) {
lines = new String[4]; 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"); if (getHandle().connection == null) return;
Validate.notNull(dyeColor, "DyeColor can not be null");
if (lines.length < 4) {
throw new IllegalArgumentException("Must have at least 4 lines");
}
IChatBaseComponent[] components = CraftSign.sanitizeLines(lines); IChatBaseComponent[] components = CraftSign.sanitizeLines(lines);
TileEntitySign sign = new TileEntitySign(CraftLocation.toBlockPosition(loc), Blocks.OAK_SIGN.defaultBlockState()); TileEntitySign sign = new TileEntitySign(CraftLocation.toBlockPosition(loc), Blocks.OAK_SIGN.defaultBlockState());
@ -758,8 +716,8 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
@Override @Override
public void sendEquipmentChange(LivingEntity entity, Map<EquipmentSlot, ItemStack> items) { public void sendEquipmentChange(LivingEntity entity, Map<EquipmentSlot, ItemStack> items) {
Preconditions.checkArgument(entity != null, "entity must not be null"); Preconditions.checkArgument(entity != null, "Entity cannot be null");
Preconditions.checkArgument(items != null, "items must not be null"); Preconditions.checkArgument(items != null, "items cannot be null");
if (getHandle().connection == null) { if (getHandle().connection == null) {
return; return;
@ -1232,12 +1190,9 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
@Override @Override
public void setGameMode(GameMode mode) { public void setGameMode(GameMode mode) {
Preconditions.checkArgument(mode != null, "GameMode cannot be null");
if (getHandle().connection == null) return; if (getHandle().connection == null) return;
if (mode == null) {
throw new IllegalArgumentException("Mode cannot be null");
}
getHandle().setGameMode(EnumGamemode.byId(mode.getValue())); getHandle().setGameMode(EnumGamemode.byId(mode.getValue()));
} }
@ -1334,14 +1289,14 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
@Override @Override
public void hideEntity(Plugin plugin, org.bukkit.entity.Entity entity) { public void hideEntity(Plugin plugin, org.bukkit.entity.Entity entity) {
Validate.notNull(plugin, "Plugin cannot be null"); Preconditions.checkArgument(plugin != null, "Plugin cannot be null");
Validate.isTrue(plugin.isEnabled(), "Plugin attempted to hide player while disabled"); Preconditions.checkArgument(plugin.isEnabled(), "Plugin (%s) cannot be disabled", plugin.getName());
hideEntity0(plugin, entity); hideEntity0(plugin, entity);
} }
private void hideEntity0(@Nullable Plugin plugin, org.bukkit.entity.Entity 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 (getHandle().connection == null) return;
if (equals(entity)) return; if (equals(entity)) return;
@ -1416,14 +1371,14 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
@Override @Override
public void showEntity(Plugin plugin, org.bukkit.entity.Entity entity) { 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 // Don't require that plugin be enabled. A plugin must be allowed to call
// showPlayer during its onDisable() method. // showPlayer during its onDisable() method.
showEntity0(plugin, entity); showEntity0(plugin, entity);
} }
private void showEntity0(@Nullable Plugin plugin, org.bukkit.entity.Entity 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 (getHandle().connection == null) return;
if (equals(entity)) return; if (equals(entity)) return;
@ -1661,10 +1616,10 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
@Override @Override
public void setResourcePack(String url, byte[] hash, String prompt, boolean force) { 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) { 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)); getHandle().sendTexturePack(url, BaseEncoding.base16().lowerCase().encode(hash), force, CraftChatMessage.fromStringOrNull(prompt, true));
} else { } else {
@ -1759,8 +1714,8 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
@Override @Override
public void setFlying(boolean value) { public void setFlying(boolean value) {
if (!getAllowFlight() && value) { if (!getAllowFlight()) {
throw new IllegalArgumentException("Cannot make player fly if getAllowFlight() is false"); Preconditions.checkArgument(!value, "Player is not allowed to fly (check #getAllowFlight())");
} }
getHandle().getAbilities().flying = value; getHandle().getAbilities().flying = value;
@ -1826,21 +1781,13 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
} }
private void validateSpeed(float value) { private void validateSpeed(float value) {
if (value < 0) { Preconditions.checkArgument(value <= 1f && value >= -1f, "Speed value (%s) need to be between -1f and 1f", value);
if (value < -1f) {
throw new IllegalArgumentException(value + " is too low");
}
} else {
if (value > 1f) {
throw new IllegalArgumentException(value + " is too high");
}
}
} }
@Override @Override
public void setMaxHealth(double amount) { public void setMaxHealth(double amount) {
super.setMaxHealth(amount); super.setMaxHealth(amount);
this.health = Math.min(this.health, health); this.health = Math.min(this.health, amount);
getHandle().resetSentInfo(); getHandle().resetSentInfo();
} }
@ -1857,21 +1804,16 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
@Override @Override
public void setScoreboard(Scoreboard scoreboard) { public void setScoreboard(Scoreboard scoreboard) {
Validate.notNull(scoreboard, "Scoreboard cannot be null"); Preconditions.checkArgument(scoreboard != null, "Scoreboard cannot be null");
PlayerConnection playerConnection = getHandle().connection; Preconditions.checkState(getHandle().connection != null, "Cannot set scoreboard yet (invalid player connection)");
if (playerConnection == null) { Preconditions.checkState(getHandle().connection.isDisconnected(), "Cannot set scoreboard for invalid CraftPlayer (player is disconnected)");
throw new IllegalStateException("Cannot set scoreboard yet");
}
if (playerConnection.isDisconnected()) {
throw new IllegalStateException("Cannot set scoreboard for invalid CraftPlayer");
}
this.server.getScoreboardManager().setPlayerBoard(this, scoreboard); this.server.getScoreboardManager().setPlayerBoard(this, scoreboard);
} }
@Override @Override
public void setHealthScale(double value) { 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; healthScale = value;
scaledHealth = true; scaledHealth = true;
updateScaledHealth(); updateScaledHealth();
@ -2044,8 +1986,8 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
@Override @Override
public <T> void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) { public <T> 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)) { if (data != null) {
throw new IllegalArgumentException("data should be " + particle.getDataType() + " got " + data.getClass()); 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); 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); getHandle().connection.send(packetplayoutworldparticles);
@ -2087,8 +2029,8 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
@Override @Override
public void openBook(ItemStack book) { public void openBook(ItemStack book) {
Validate.isTrue(book != null, "book == null"); Preconditions.checkArgument(book != null, "ItemStack cannot be null");
Validate.isTrue(book.getType() == Material.WRITTEN_BOOK, "Book must be Material.WRITTEN_BOOK"); Preconditions.checkArgument(book.getType() == Material.WRITTEN_BOOK, "ItemStack Material (%s) must be Material.WRITTEN_BOOK", book.getType());
ItemStack hand = getInventory().getItemInMainHand(); ItemStack hand = getInventory().getItemInMainHand();
getInventory().setItemInMainHand(book); getInventory().setItemInMainHand(book);

Datei anzeigen

@ -1,11 +1,11 @@
package org.bukkit.craftbukkit.entity; package org.bukkit.craftbukkit.entity;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import java.util.Collection; import java.util.Collection;
import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.entity.projectile.EntityPotion; import net.minecraft.world.entity.projectile.EntityPotion;
import net.minecraft.world.item.alchemy.PotionUtil; import net.minecraft.world.item.alchemy.PotionUtil;
import org.apache.commons.lang.Validate;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.craftbukkit.inventory.CraftItemStack; import org.bukkit.craftbukkit.inventory.CraftItemStack;
@ -36,11 +36,8 @@ public class CraftThrownPotion extends CraftThrowableProjectile implements Throw
@Override @Override
public void setItem(ItemStack item) { public void setItem(ItemStack item) {
// The ItemStack must not be null. Preconditions.checkArgument(item != null, "ItemStack cannot be null");
Validate.notNull(item, "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());
// 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() + ".");
getHandle().setItem(CraftItemStack.asNMSCopy(item)); getHandle().setItem(CraftItemStack.asNMSCopy(item));
} }

Datei anzeigen

@ -1,11 +1,11 @@
package org.bukkit.craftbukkit.entity; package org.bukkit.craftbukkit.entity;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import java.util.List; import java.util.List;
import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectList; import net.minecraft.world.effect.MobEffectList;
import net.minecraft.world.entity.projectile.EntityTippedArrow; import net.minecraft.world.entity.projectile.EntityTippedArrow;
import org.apache.commons.lang.Validate;
import org.bukkit.Color; import org.bukkit.Color;
import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.craftbukkit.potion.CraftPotionUtil; import org.bukkit.craftbukkit.potion.CraftPotionUtil;
@ -105,7 +105,7 @@ public class CraftTippedArrow extends CraftArrow implements Arrow {
@Override @Override
public void setBasePotionData(PotionData data) { 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)); getHandle().setPotionType(CraftPotionUtil.fromBukkit(data));
} }

Datei anzeigen

@ -10,7 +10,6 @@ import net.minecraft.world.entity.npc.EntityVillager;
import net.minecraft.world.entity.npc.VillagerProfession; import net.minecraft.world.entity.npc.VillagerProfession;
import net.minecraft.world.level.block.BlockBed; import net.minecraft.world.level.block.BlockBed;
import net.minecraft.world.level.block.state.IBlockData; import net.minecraft.world.level.block.state.IBlockData;
import org.apache.commons.lang.Validate;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.craftbukkit.util.CraftLocation; import org.bukkit.craftbukkit.util.CraftLocation;
@ -55,7 +54,7 @@ public class CraftVillager extends CraftAbstractVillager implements Villager {
@Override @Override
public void setProfession(Profession profession) { public void setProfession(Profession profession) {
Validate.notNull(profession); Preconditions.checkArgument(profession != null, "Profession cannot be null");
getHandle().setVillagerData(getHandle().getVillagerData().setProfession(CraftVillager.bukkitToNmsProfession(profession))); getHandle().setVillagerData(getHandle().getVillagerData().setProfession(CraftVillager.bukkitToNmsProfession(profession)));
} }
@ -66,7 +65,7 @@ public class CraftVillager extends CraftAbstractVillager implements Villager {
@Override @Override
public void setVillagerType(Type type) { 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())))); 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 @Override
public void setVillagerLevel(int level) { 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)); getHandle().setVillagerData(getHandle().getVillagerData().setLevel(level));
} }
@ -89,7 +88,7 @@ public class CraftVillager extends CraftAbstractVillager implements Villager {
@Override @Override
public void setVillagerExperience(int experience) { 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); getHandle().setVillagerXp(experience);
} }

Datei anzeigen

@ -2,12 +2,10 @@ package org.bukkit.craftbukkit.entity;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import java.util.Locale; import java.util.Locale;
import java.util.UUID;
import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.MinecraftKey; import net.minecraft.resources.MinecraftKey;
import net.minecraft.world.effect.MobEffects; import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.monster.EntityZombieVillager; import net.minecraft.world.entity.monster.EntityZombieVillager;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.CraftServer;
@ -44,7 +42,7 @@ public class CraftVillagerZombie extends CraftZombie implements ZombieVillager {
@Override @Override
public void setVillagerProfession(Villager.Profession profession) { 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))))); 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 @Override
public void setVillagerType(Villager.Type type) { 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())))); 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().conversionStarter = null;
getHandle().removeEffect(MobEffects.DAMAGE_BOOST, org.bukkit.event.entity.EntityPotionEffectEvent.Cause.CONVERSION); getHandle().removeEffect(MobEffects.DAMAGE_BOOST, org.bukkit.event.entity.EntityPotionEffectEvent.Cause.CONVERSION);
} else { } else {
getHandle().startConverting((UUID) null, time); getHandle().startConverting(null, time);
} }
} }

Datei anzeigen

@ -2,6 +2,7 @@ package org.bukkit.craftbukkit.event;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Functions; import com.google.common.base.Functions;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.mojang.datafixers.util.Either; import com.mojang.datafixers.util.Either;
import java.net.InetAddress; import java.net.InetAddress;
@ -1610,9 +1611,8 @@ public class CraftEventFactory {
PotionEffect bukkitOldEffect = (oldEffect == null) ? null : CraftPotionUtil.toBukkit(oldEffect); PotionEffect bukkitOldEffect = (oldEffect == null) ? null : CraftPotionUtil.toBukkit(oldEffect);
PotionEffect bukkitNewEffect = (newEffect == null) ? null : CraftPotionUtil.toBukkit(newEffect); PotionEffect bukkitNewEffect = (newEffect == null) ? null : CraftPotionUtil.toBukkit(newEffect);
if (bukkitOldEffect == null && bukkitNewEffect == null) { Preconditions.checkState(bukkitOldEffect != null, "Old and new potion is null");
throw new IllegalStateException("Old and new potion effect are both null"); Preconditions.checkState(bukkitNewEffect != null, "New potion effect is null");
}
EntityPotionEffectEvent event = new EntityPotionEffectEvent((LivingEntity) entity.getBukkitEntity(), bukkitOldEffect, bukkitNewEffect, cause, action, willOverride); EntityPotionEffectEvent event = new EntityPotionEffectEvent((LivingEntity) entity.getBukkitEntity(), bukkitOldEffect, bukkitNewEffect, cause, action, willOverride);
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.generator; package org.bukkit.craftbukkit.generator;
import com.google.common.base.Preconditions;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import net.minecraft.core.BlockPosition; import net.minecraft.core.BlockPosition;
import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.Blocks;
@ -38,9 +39,7 @@ public final class CraftChunkData implements ChunkGenerator.ChunkData {
public IChunkAccess getHandle() { public IChunkAccess getHandle() {
IChunkAccess access = weakChunk.get(); IChunkAccess access = weakChunk.get();
if (access == null) { Preconditions.checkState(access != null, "IChunkAccess no longer present, are you using it in a different tick?");
throw new IllegalStateException("IChunkAccess no longer present, are you using it in a different tick?");
}
return access; return access;
} }

Datei anzeigen

@ -68,9 +68,7 @@ public class CraftLimitedRegion extends CraftRegionAccessor implements LimitedRe
public GeneratorAccessSeed getHandle() { public GeneratorAccessSeed getHandle() {
GeneratorAccessSeed handle = weakAccess.get(); GeneratorAccessSeed handle = weakAccess.get();
if (handle == null) { Preconditions.checkState(handle != null, "GeneratorAccessSeed no longer present, are you using it in a different tick?");
throw new IllegalStateException("GeneratorAccessSeed no longer present, are you using it in a different tick?");
}
return handle; return handle;
} }

Datei anzeigen

@ -1,6 +1,6 @@
package org.bukkit.craftbukkit.help; package org.bukkit.craftbukkit.help;
import org.apache.commons.lang.Validate; import com.google.common.base.Preconditions;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.help.HelpMap; import org.bukkit.help.HelpMap;
@ -15,12 +15,13 @@ public class CommandAliasHelpTopic extends HelpTopic {
this.aliasFor = aliasFor.startsWith("/") ? aliasFor : "/" + aliasFor; this.aliasFor = aliasFor.startsWith("/") ? aliasFor : "/" + aliasFor;
this.helpMap = helpMap; this.helpMap = helpMap;
this.name = alias.startsWith("/") ? alias : "/" + alias; 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; this.shortText = ChatColor.YELLOW + "Alias for " + ChatColor.WHITE + this.aliasFor;
} }
@Override @Override
public String getFullText(CommandSender forWho) { public String getFullText(CommandSender forWho) {
Preconditions.checkArgument(forWho != null, "CommandServer forWho cannot be null");
StringBuilder sb = new StringBuilder(shortText); StringBuilder sb = new StringBuilder(shortText);
HelpTopic aliasForTopic = helpMap.getHelpTopic(aliasFor); HelpTopic aliasForTopic = helpMap.getHelpTopic(aliasFor);
if (aliasForTopic != null) { if (aliasForTopic != null) {
@ -32,6 +33,7 @@ public class CommandAliasHelpTopic extends HelpTopic {
@Override @Override
public boolean canSee(CommandSender commandSender) { public boolean canSee(CommandSender commandSender) {
Preconditions.checkArgument(commandSender != null, "CommandServer cannot be null");
if (amendedPermission == null) { if (amendedPermission == null) {
HelpTopic aliasForTopic = helpMap.getHelpTopic(aliasFor); HelpTopic aliasForTopic = helpMap.getHelpTopic(aliasFor);
if (aliasForTopic != null) { if (aliasForTopic != null) {

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.help; package org.bukkit.craftbukkit.help;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Predicates; import com.google.common.base.Predicates;
import com.google.common.collect.Collections2; import com.google.common.collect.Collections2;
@ -223,9 +224,7 @@ public class SimpleHelpMap implements HelpMap {
@Override @Override
public void registerHelpTopicFactory(Class commandClass, HelpTopicFactory factory) { public void registerHelpTopicFactory(Class commandClass, HelpTopicFactory factory) {
if (!Command.class.isAssignableFrom(commandClass) && !CommandExecutor.class.isAssignableFrom(commandClass)) { Preconditions.checkArgument(Command.class.isAssignableFrom(commandClass) && CommandExecutor.class.isAssignableFrom(commandClass), "commandClass (%s) must implement either Command or CommandExecutor", commandClass.getName());
throw new IllegalArgumentException("commandClass must implement either Command or CommandExecutor!");
}
topicFactoryMap.put(commandClass, factory); topicFactoryMap.put(commandClass, factory);
} }

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.inventory; package org.bukkit.craftbukkit.inventory;
import com.google.common.base.Preconditions;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.ListIterator; 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.TileEntityLectern;
import net.minecraft.world.level.block.entity.TileEntityShulkerBox; import net.minecraft.world.level.block.entity.TileEntityShulkerBox;
import net.minecraft.world.level.block.entity.TileEntitySmoker; import net.minecraft.world.level.block.entity.TileEntitySmoker;
import org.apache.commons.lang.Validate;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.craftbukkit.util.CraftLegacy; import org.bukkit.craftbukkit.util.CraftLegacy;
@ -84,9 +84,7 @@ public class CraftInventory implements Inventory {
@Override @Override
public void setContents(ItemStack[] items) { public void setContents(ItemStack[] items) {
if (getSize() < items.length) { Preconditions.checkArgument(getSize() < items.length, "Invalid inventory size (%s); expected %s or less", items.length, getSize());
throw new IllegalArgumentException("Invalid inventory size; expected " + getSize() + " or less");
}
for (int i = 0; i < getSize(); i++) { for (int i = 0; i < getSize(); i++) {
if (i >= items.length) { if (i >= items.length) {
@ -104,7 +102,7 @@ public class CraftInventory implements Inventory {
@Override @Override
public boolean contains(Material material) { public boolean contains(Material material) {
Validate.notNull(material, "Material cannot be null"); Preconditions.checkArgument(material != null, "Material cannot be null");
material = CraftLegacy.fromLegacy(material); material = CraftLegacy.fromLegacy(material);
for (ItemStack item : getStorageContents()) { for (ItemStack item : getStorageContents()) {
if (item != null && item.getType() == material) { if (item != null && item.getType() == material) {
@ -129,7 +127,7 @@ public class CraftInventory implements Inventory {
@Override @Override
public boolean contains(Material material, int amount) { 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); material = CraftLegacy.fromLegacy(material);
if (amount <= 0) { if (amount <= 0) {
return true; return true;
@ -178,9 +176,9 @@ public class CraftInventory implements Inventory {
@Override @Override
public HashMap<Integer, ItemStack> all(Material material) { public HashMap<Integer, ItemStack> all(Material material) {
Validate.notNull(material, "Material cannot be null"); Preconditions.checkArgument(material != null, "Material cannot be null");
material = CraftLegacy.fromLegacy(material); material = CraftLegacy.fromLegacy(material);
HashMap<Integer, ItemStack> slots = new HashMap<Integer, ItemStack>(); HashMap<Integer, ItemStack> slots = new HashMap<>();
ItemStack[] inventory = getStorageContents(); ItemStack[] inventory = getStorageContents();
for (int i = 0; i < inventory.length; i++) { for (int i = 0; i < inventory.length; i++) {
@ -194,7 +192,7 @@ public class CraftInventory implements Inventory {
@Override @Override
public HashMap<Integer, ItemStack> all(ItemStack item) { public HashMap<Integer, ItemStack> all(ItemStack item) {
HashMap<Integer, ItemStack> slots = new HashMap<Integer, ItemStack>(); HashMap<Integer, ItemStack> slots = new HashMap<>();
if (item != null) { if (item != null) {
ItemStack[] inventory = getStorageContents(); ItemStack[] inventory = getStorageContents();
for (int i = 0; i < inventory.length; i++) { for (int i = 0; i < inventory.length; i++) {
@ -208,7 +206,7 @@ public class CraftInventory implements Inventory {
@Override @Override
public int first(Material material) { public int first(Material material) {
Validate.notNull(material, "Material cannot be null"); Preconditions.checkArgument(material != null, "Material cannot be null");
material = CraftLegacy.fromLegacy(material); material = CraftLegacy.fromLegacy(material);
ItemStack[] inventory = getStorageContents(); ItemStack[] inventory = getStorageContents();
for (int i = 0; i < inventory.length; i++) { for (int i = 0; i < inventory.length; i++) {
@ -257,7 +255,7 @@ public class CraftInventory implements Inventory {
} }
public int firstPartial(Material material) { public int firstPartial(Material material) {
Validate.notNull(material, "Material cannot be null"); Preconditions.checkArgument(material != null, "Material cannot be null");
material = CraftLegacy.fromLegacy(material); material = CraftLegacy.fromLegacy(material);
ItemStack[] inventory = getStorageContents(); ItemStack[] inventory = getStorageContents();
for (int i = 0; i < inventory.length; i++) { for (int i = 0; i < inventory.length; i++) {
@ -286,8 +284,8 @@ public class CraftInventory implements Inventory {
@Override @Override
public HashMap<Integer, ItemStack> addItem(ItemStack... items) { public HashMap<Integer, ItemStack> addItem(ItemStack... items) {
Validate.noNullElements(items, "Item cannot be null"); Preconditions.checkArgument(items != null, "items cannot be null");
HashMap<Integer, ItemStack> leftover = new HashMap<Integer, ItemStack>(); HashMap<Integer, ItemStack> leftover = new HashMap<>();
/* TODO: some optimization /* TODO: some optimization
* - Create a 'firstPartial' with a 'fromIndex' * - Create a 'firstPartial' with a 'fromIndex'
@ -297,6 +295,7 @@ public class CraftInventory implements Inventory {
for (int i = 0; i < items.length; i++) { for (int i = 0; i < items.length; i++) {
ItemStack item = items[i]; ItemStack item = items[i];
Preconditions.checkArgument(item != null, "ItemStack cannot be null");
while (true) { while (true) {
// Do we already have a stack of it? // Do we already have a stack of it?
int firstPartial = firstPartial(item); int firstPartial = firstPartial(item);
@ -352,13 +351,14 @@ public class CraftInventory implements Inventory {
@Override @Override
public HashMap<Integer, ItemStack> removeItem(ItemStack... items) { public HashMap<Integer, ItemStack> removeItem(ItemStack... items) {
Validate.notNull(items, "Items cannot be null"); Preconditions.checkArgument(items != null, "items cannot be null");
HashMap<Integer, ItemStack> leftover = new HashMap<Integer, ItemStack>(); HashMap<Integer, ItemStack> leftover = new HashMap<Integer, ItemStack>();
// TODO: optimization // TODO: optimization
for (int i = 0; i < items.length; i++) { for (int i = 0; i < items.length; i++) {
ItemStack item = items[i]; ItemStack item = items[i];
Preconditions.checkArgument(item != null, "ItemStack cannot be null");
int toDelete = item.getAmount(); int toDelete = item.getAmount();
while (true) { while (true) {
@ -400,7 +400,7 @@ public class CraftInventory implements Inventory {
@Override @Override
public void remove(Material material) { public void remove(Material material) {
Validate.notNull(material, "Material cannot be null"); Preconditions.checkArgument(material != null, "Material cannot be null");
material = CraftLegacy.fromLegacy(material); material = CraftLegacy.fromLegacy(material);
ItemStack[] items = getStorageContents(); ItemStack[] items = getStorageContents();
for (int i = 0; i < items.length; i++) { for (int i = 0; i < items.length; i++) {

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.inventory; package org.bukkit.craftbukkit.inventory;
import com.google.common.base.Preconditions;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import net.minecraft.world.IInventory; import net.minecraft.world.IInventory;
@ -31,9 +32,7 @@ public class CraftInventoryCrafting extends CraftInventory implements CraftingIn
@Override @Override
public void setContents(ItemStack[] items) { public void setContents(ItemStack[] items) {
if (getSize() > items.length) { Preconditions.checkArgument(getSize() <= items.length, "Invalid inventory size (%s); expected %s or less", items.length, getSize());
throw new IllegalArgumentException("Invalid inventory size; expected " + getSize() + " or less");
}
setContents(items[0], Arrays.copyOfRange(items, 1, items.length)); setContents(items[0], Arrays.copyOfRange(items, 1, items.length));
} }
@ -97,9 +96,7 @@ public class CraftInventoryCrafting extends CraftInventory implements CraftingIn
@Override @Override
public void setMatrix(ItemStack[] contents) { public void setMatrix(ItemStack[] contents) {
if (getMatrixInventory().getContainerSize() > contents.length) { Preconditions.checkArgument(getMatrixInventory().getContainerSize() <= contents.length, "Invalid inventory size (%s); expected %s or less", contents.length, getMatrixInventory().getContainerSize());
throw new IllegalArgumentException("Invalid inventory size; expected " + getMatrixInventory().getContainerSize() + " or less");
}
for (int i = 0; i < getMatrixInventory().getContainerSize(); i++) { for (int i = 0; i < getMatrixInventory().getContainerSize(); i++) {
if (i < contents.length) { if (i < contents.length) {

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.inventory; package org.bukkit.craftbukkit.inventory;
import com.google.common.base.Preconditions;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@ -7,7 +8,6 @@ import net.minecraft.core.NonNullList;
import net.minecraft.world.IInventory; import net.minecraft.world.IInventory;
import net.minecraft.world.entity.player.EntityHuman; import net.minecraft.world.entity.player.EntityHuman;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import org.apache.commons.lang.Validate;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.craftbukkit.entity.CraftHumanEntity; import org.bukkit.craftbukkit.entity.CraftHumanEntity;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
@ -54,7 +54,7 @@ public class CraftInventoryCustom extends CraftInventory {
} }
public MinecraftInventory(InventoryHolder owner, int size, String title) { 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.items = NonNullList.withSize(size, ItemStack.EMPTY);
this.title = title; this.title = title;
this.viewers = new ArrayList<HumanEntity>(); this.viewers = new ArrayList<HumanEntity>();

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.inventory; package org.bukkit.craftbukkit.inventory;
import com.google.common.base.Preconditions;
import net.minecraft.world.ITileInventory; import net.minecraft.world.ITileInventory;
import net.minecraft.world.InventoryLargeChest; import net.minecraft.world.InventoryLargeChest;
import net.minecraft.world.level.block.BlockChest; import net.minecraft.world.level.block.BlockChest;
@ -47,9 +48,7 @@ public class CraftInventoryDoubleChest extends CraftInventory implements DoubleC
@Override @Override
public void setContents(ItemStack[] items) { public void setContents(ItemStack[] items) {
if (getInventory().getContainerSize() < items.length) { Preconditions.checkArgument(getInventory().getContainerSize() >= items.length, "Invalid inventory size (%s); expected %s or less", items.length, getInventory().getContainerSize());
throw new IllegalArgumentException("Invalid inventory size; expected " + getInventory().getContainerSize() + " or less");
}
ItemStack[] leftItems = new ItemStack[left.getSize()], rightItems = new ItemStack[right.getSize()]; ItemStack[] leftItems = new ItemStack[left.getSize()], rightItems = new ItemStack[right.getSize()];
System.arraycopy(items, 0, leftItems, 0, Math.min(left.getSize(), items.length)); System.arraycopy(items, 0, leftItems, 0, Math.min(left.getSize(), items.length));
left.setContents(leftItems); left.setContents(leftItems);

Datei anzeigen

@ -5,7 +5,6 @@ import net.minecraft.network.protocol.game.PacketPlayOutHeldItemSlot;
import net.minecraft.network.protocol.game.PacketPlayOutSetSlot; import net.minecraft.network.protocol.game.PacketPlayOutSetSlot;
import net.minecraft.server.level.EntityPlayer; import net.minecraft.server.level.EntityPlayer;
import net.minecraft.world.entity.player.PlayerInventory; import net.minecraft.world.entity.player.PlayerInventory;
import org.apache.commons.lang.Validate;
import org.bukkit.craftbukkit.entity.CraftPlayer; import org.bukkit.craftbukkit.entity.CraftPlayer;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.EntityEquipment;
@ -175,7 +174,7 @@ public class CraftInventoryPlayer extends CraftInventory implements org.bukkit.i
@Override @Override
public void setHeldItemSlot(int slot) { 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; this.getInventory().selected = slot;
((CraftPlayer) this.getHolder()).getHandle().connection.send(new PacketPlayOutHeldItemSlot(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) { if (items == null) {
items = new ItemStack[length]; 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++) { for (int i = 0; i < length; i++) {
if (i >= items.length) { if (i >= items.length) {

Datei anzeigen

@ -1,13 +1,12 @@
package org.bukkit.craftbukkit.inventory; package org.bukkit.craftbukkit.inventory;
import com.google.common.base.Preconditions;
import com.mojang.brigadier.StringReader; import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.commands.arguments.item.ArgumentParserItemStack; import net.minecraft.commands.arguments.item.ArgumentParserItemStack;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
import org.apache.commons.lang.Validate;
import org.bukkit.Color; import org.bukkit.Color;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.configuration.serialization.ConfigurationSerialization; import org.bukkit.configuration.serialization.ConfigurationSerialization;
@ -42,16 +41,15 @@ public final class CraftItemFactory implements ItemFactory {
if (type == null || meta == null) { if (type == null || meta == null) {
return false; 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); return ((CraftMetaItem) meta).applicableTo(type);
} }
@Override @Override
public ItemMeta getItemMeta(Material material) { public ItemMeta getItemMeta(Material material) {
Validate.notNull(material, "Material cannot be null"); Preconditions.checkArgument(material != null, "Material cannot be null");
return getItemMeta(material, null); return getItemMeta(material, null);
} }
@ -366,16 +364,15 @@ public final class CraftItemFactory implements ItemFactory {
if (meta1 == meta2) { if (meta1 == meta2) {
return true; 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 (meta1 != null) {
} Preconditions.checkArgument(meta1 instanceof CraftMetaItem, "First meta of %s does not belong to %s", meta1.getClass().getName(), CraftItemFactory.class.getName());
if (meta2 != null && !(meta2 instanceof CraftMetaItem)) { } else {
throw new IllegalArgumentException("Second meta " + meta2.getClass().getName() + " does not belong to " + CraftItemFactory.class.getName());
}
if (meta1 == null) {
return ((CraftMetaItem) meta2).isEmpty(); 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(); return ((CraftMetaItem) meta1).isEmpty();
} }
@ -401,16 +398,14 @@ public final class CraftItemFactory implements ItemFactory {
@Override @Override
public ItemMeta asMetaFor(ItemMeta meta, ItemStack stack) { 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()); return asMetaFor(meta, stack.getType());
} }
@Override @Override
public ItemMeta asMetaFor(ItemMeta meta, Material material) { public ItemMeta asMetaFor(ItemMeta meta, Material material) {
Validate.notNull(material, "Material cannot be null"); Preconditions.checkArgument(material != null, "Material cannot be null");
if (!(meta instanceof CraftMetaItem)) { Preconditions.checkArgument(meta instanceof CraftMetaItem, "ItemMeta of %s not created by %s", (meta != null ? meta.getClass().toString() : "null"), CraftItemFactory.class.getName());
throw new IllegalArgumentException("Meta of " + (meta != null ? meta.getClass().toString() : "null") + " not created by " + CraftItemFactory.class.getName());
}
return getItemMeta(material, (CraftMetaItem) meta); return getItemMeta(material, (CraftMetaItem) meta);
} }

Datei anzeigen

@ -1,13 +1,13 @@
package org.bukkit.craftbukkit.inventory; package org.bukkit.craftbukkit.inventory;
import static org.bukkit.craftbukkit.inventory.CraftMetaItem.*; import static org.bukkit.craftbukkit.inventory.CraftMetaItem.*;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import java.util.Map; import java.util.Map;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
import net.minecraft.world.item.enchantment.EnchantmentManager; import net.minecraft.world.item.enchantment.EnchantmentManager;
import org.apache.commons.lang.Validate;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.NamespacedKey; import org.bukkit.NamespacedKey;
import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.configuration.serialization.DelegateDeserialization;
@ -176,7 +176,7 @@ public final class CraftItemStack extends ItemStack {
@Override @Override
public void addUnsafeEnchantment(Enchantment ench, int level) { 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)) { if (!makeTag(handle)) {
return; return;
@ -221,7 +221,7 @@ public final class CraftItemStack extends ItemStack {
@Override @Override
public int getEnchantmentLevel(Enchantment ench) { public int getEnchantmentLevel(Enchantment ench) {
Validate.notNull(ench, "Cannot find null enchantment"); Preconditions.checkArgument(ench != null, "Enchantment cannot be null");
if (handle == null) { if (handle == null) {
return 0; return 0;
} }
@ -230,7 +230,7 @@ public final class CraftItemStack extends ItemStack {
@Override @Override
public int removeEnchantment(Enchantment ench) { 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; NBTTagList list = getEnchantmentList(handle), listCopy;
if (list == null) { if (list == null) {

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.inventory; package org.bukkit.craftbukkit.inventory;
import com.google.common.base.Preconditions;
import net.minecraft.network.chat.IChatBaseComponent; import net.minecraft.network.chat.IChatBaseComponent;
import net.minecraft.sounds.SoundEffect; import net.minecraft.sounds.SoundEffect;
import net.minecraft.sounds.SoundEffects; 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.IMerchant;
import net.minecraft.world.item.trading.MerchantRecipe; import net.minecraft.world.item.trading.MerchantRecipe;
import net.minecraft.world.item.trading.MerchantRecipeList; 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; import org.bukkit.craftbukkit.util.CraftChatMessage;
public class CraftMerchantCustom extends CraftMerchant { public class CraftMerchantCustom extends CraftMerchant {
@ -37,7 +36,7 @@ public class CraftMerchantCustom extends CraftMerchant {
protected CraftMerchant craftMerchant; protected CraftMerchant craftMerchant;
public MinecraftMerchant(String title) { 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]; this.title = CraftChatMessage.fromString(title)[0];
} }

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.inventory; package org.bukkit.craftbukkit.inventory;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
@ -114,9 +115,7 @@ public class CraftMetaBanner extends CraftMetaItem implements BannerMeta {
} }
for (Object obj : rawPatternList) { for (Object obj : rawPatternList) {
if (!(obj instanceof Pattern)) { Preconditions.checkArgument(obj instanceof Pattern, "Object (%s) in pattern list is not valid", obj.getClass());
throw new IllegalArgumentException("Object in pattern list is not valid. " + obj.getClass());
}
addPattern((Pattern) obj); addPattern((Pattern) obj);
} }
} }

Datei anzeigen

@ -1,13 +1,13 @@
package org.bukkit.craftbukkit.inventory; package org.bukkit.craftbukkit.inventory;
import com.google.common.base.Objects; import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import org.apache.commons.lang.Validate;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.configuration.serialization.DelegateDeserialization;
@ -274,11 +274,11 @@ public class CraftMetaBlockState extends CraftMetaItem implements BlockStateMeta
@Override @Override
public void setBlockState(BlockState blockState) { 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); Material stateMaterial = (material != Material.SHIELD) ? material : shieldToBannerHack(blockEntityTag);
Class<?> blockStateType = CraftBlockStates.getBlockStateType(stateMaterial); 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(); blockEntityTag = ((CraftBlockEntityState) blockState).getSnapshotNBT();
// Set shield base // Set shield base

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.inventory; package org.bukkit.craftbukkit.inventory;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
@ -12,7 +13,6 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagString; import net.minecraft.nbt.NBTTagString;
import net.minecraft.network.chat.IChatBaseComponent; import net.minecraft.network.chat.IChatBaseComponent;
import org.apache.commons.lang.Validate;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.configuration.serialization.DelegateDeserialization;
import org.bukkit.craftbukkit.inventory.CraftMetaItem.SerializableMeta; import org.bukkit.craftbukkit.inventory.CraftMetaItem.SerializableMeta;
@ -256,16 +256,14 @@ public class CraftMetaBook extends CraftMetaItem implements BookMeta {
@Override @Override
public String getPage(final int page) { 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 // assert: pages != null
return convertDataToPlainPage(pages.get(page - 1)); return convertDataToPlainPage(pages.get(page - 1));
} }
@Override @Override
public void setPage(final int page, final String text) { public void setPage(final int page, final String text) {
if (!isValidPage(page)) { Preconditions.checkArgument(isValidPage(page), "Invalid page number (%s/%s)", page, getPageCount());
throw new IllegalArgumentException("Invalid page number " + page + "/" + getPageCount());
}
// assert: pages != null // assert: pages != null
String newText = validatePage(text); String newText = validatePage(text);
@ -379,8 +377,7 @@ public class CraftMetaBook extends CraftMetaItem implements BookMeta {
if (!super.equalsCommon(meta)) { if (!super.equalsCommon(meta)) {
return false; return false;
} }
if (meta instanceof CraftMetaBook) { if (meta instanceof CraftMetaBook that) {
CraftMetaBook that = (CraftMetaBook) meta;
return (hasTitle() ? that.hasTitle() && this.title.equals(that.title) : !that.hasTitle()) return (hasTitle() ? that.hasTitle() && this.title.equals(that.title) : !that.hasTitle())
&& (hasAuthor() ? that.hasAuthor() && this.author.equals(that.author) : !that.hasAuthor()) && (hasAuthor() ? that.hasAuthor() && this.author.equals(that.author) : !that.hasAuthor())

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.inventory; package org.bukkit.craftbukkit.inventory;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.ImmutableMap.Builder;
import java.util.ArrayList; import java.util.ArrayList;
@ -8,7 +9,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagList;
import org.apache.commons.lang.Validate;
import org.bukkit.Color; import org.bukkit.Color;
import org.bukkit.FireworkEffect; import org.bukkit.FireworkEffect;
import org.bukkit.FireworkEffect.Type; import org.bukkit.FireworkEffect.Type;
@ -58,16 +58,14 @@ class CraftMetaFirework extends CraftMetaItem implements FireworkMeta {
CraftMetaFirework(CraftMetaItem meta) { CraftMetaFirework(CraftMetaItem meta) {
super(meta); super(meta);
if (!(meta instanceof CraftMetaFirework)) { if (!(meta instanceof CraftMetaFirework that)) {
return; return;
} }
CraftMetaFirework that = (CraftMetaFirework) meta;
this.power = that.power; this.power = that.power;
if (that.hasEffects()) { if (that.hasEffects()) {
this.effects = new ArrayList<FireworkEffect>(that.effects); this.effects = new ArrayList<>(that.effects);
} }
} }
@ -200,15 +198,12 @@ class CraftMetaFirework extends CraftMetaItem implements FireworkMeta {
List<FireworkEffect> effects = this.effects; List<FireworkEffect> effects = this.effects;
if (effects == null) { if (effects == null) {
effects = this.effects = new ArrayList<FireworkEffect>(); effects = this.effects = new ArrayList<>();
} }
for (Object obj : collection) { for (Object obj : collection) {
if (obj instanceof FireworkEffect) { Preconditions.checkArgument(obj instanceof FireworkEffect, "%s in %s is not a FireworkEffect", obj, collection);
effects.add((FireworkEffect) obj); effects.add((FireworkEffect) obj);
} else {
throw new IllegalArgumentException(obj + " in " + collection + " is not a FireworkEffect");
}
} }
} }
@ -276,8 +271,7 @@ class CraftMetaFirework extends CraftMetaItem implements FireworkMeta {
return false; return false;
} }
if (meta instanceof CraftMetaFirework) { if (meta instanceof CraftMetaFirework that) {
CraftMetaFirework that = (CraftMetaFirework) meta;
return (hasPower() ? that.hasPower() && this.power == that.power : !that.hasPower()) return (hasPower() ? that.hasPower() && this.power == that.power : !that.hasPower())
&& (hasEffects() ? that.hasEffects() && this.effects.equals(that.effects) : !that.hasEffects()); && (hasEffects() ? that.hasEffects() && this.effects.equals(that.effects) : !that.hasEffects());
@ -332,7 +326,7 @@ class CraftMetaFirework extends CraftMetaItem implements FireworkMeta {
@Override @Override
public void addEffect(FireworkEffect effect) { public void addEffect(FireworkEffect effect) {
Validate.notNull(effect, "Effect cannot be null"); Preconditions.checkArgument(effect != null, "FireworkEffect cannot be null");
if (this.effects == null) { if (this.effects == null) {
this.effects = new ArrayList<FireworkEffect>(); this.effects = new ArrayList<FireworkEffect>();
} }
@ -341,7 +335,7 @@ class CraftMetaFirework extends CraftMetaItem implements FireworkMeta {
@Override @Override
public void addEffects(FireworkEffect... effects) { public void addEffects(FireworkEffect... effects) {
Validate.notNull(effects, "Effects cannot be null"); Preconditions.checkArgument(effects != null, "effects cannot be null");
if (effects.length == 0) { if (effects.length == 0) {
return; return;
} }
@ -352,14 +346,14 @@ class CraftMetaFirework extends CraftMetaItem implements FireworkMeta {
} }
for (FireworkEffect effect : effects) { for (FireworkEffect effect : effects) {
Validate.notNull(effect, "Effect cannot be null"); Preconditions.checkArgument(effect != null, "effects cannot contain null FireworkEffect");
list.add(effect); list.add(effect);
} }
} }
@Override @Override
public void addEffects(Iterable<FireworkEffect> effects) { public void addEffects(Iterable<FireworkEffect> effects) {
Validate.notNull(effects, "Effects cannot be null"); Preconditions.checkArgument(effects != null, "effects cannot be null");
safelyAddEffects(effects); safelyAddEffects(effects);
} }
@ -394,8 +388,8 @@ class CraftMetaFirework extends CraftMetaItem implements FireworkMeta {
@Override @Override
public void setPower(int power) { public void setPower(int power) {
Validate.isTrue(power >= 0, "Power cannot be less than zero: ", power); Preconditions.checkArgument(power >= 0, "power cannot be less than zero: %s", power);
Validate.isTrue(power < 0x80, "Power cannot be more than 127: ", power); Preconditions.checkArgument(power < 0x80, "power cannot be more than 127: %s", power);
this.power = power; this.power = power;
} }
} }

Datei anzeigen

@ -46,7 +46,6 @@ import net.minecraft.network.chat.IChatBaseComponent;
import net.minecraft.world.entity.EnumItemSlot; import net.minecraft.world.entity.EnumItemSlot;
import net.minecraft.world.item.ItemBlock; import net.minecraft.world.item.ItemBlock;
import net.minecraft.world.level.block.state.IBlockData; import net.minecraft.world.level.block.state.IBlockData;
import org.apache.commons.lang.Validate;
import org.apache.commons.lang3.EnumUtils; import org.apache.commons.lang3.EnumUtils;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.attribute.Attribute; import org.bukkit.attribute.Attribute;
@ -180,7 +179,7 @@ class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta {
} }
public static ItemMeta deserialize(Map<String, Object> map) throws Throwable { public static ItemMeta deserialize(Map<String, Object> 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); String type = getString(map, TYPE_FIELD, false);
Constructor<? extends CraftMetaItem> constructor = constructorMap.get(type); Constructor<? extends CraftMetaItem> constructor = constructorMap.get(type);
@ -789,13 +788,13 @@ class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta {
@Override @Override
public boolean hasEnchant(Enchantment ench) { 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); return hasEnchants() && enchantments.containsKey(ench);
} }
@Override @Override
public int getEnchantLevel(Enchantment ench) { 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; Integer level = hasEnchants() ? enchantments.get(ench) : null;
if (level == null) { if (level == null) {
return 0; return 0;
@ -810,7 +809,7 @@ class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta {
@Override @Override
public boolean addEnchant(Enchantment ench, int level, boolean ignoreRestrictions) { 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) { if (enchantments == null) {
enchantments = new LinkedHashMap<Enchantment, Integer>(4); enchantments = new LinkedHashMap<Enchantment, Integer>(4);
} }
@ -824,7 +823,7 @@ class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta {
@Override @Override
public boolean removeEnchant(Enchantment ench) { 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; return hasEnchants() && enchantments.remove(ench) != null;
} }
@ -1330,9 +1329,7 @@ class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta {
for (Object object : addFrom) { for (Object object : addFrom) {
if (!(object instanceof String)) { if (!(object instanceof String)) {
if (object != null) { Preconditions.checkArgument(object == null, "%s cannot contain non-string %s", addFrom, object.getClass().getName());
throw new IllegalArgumentException(addFrom + " cannot contain non-string " + object.getClass().getName());
}
addTo.add(CraftChatMessage.toJSON(IChatBaseComponent.empty())); addTo.add(CraftChatMessage.toJSON(IChatBaseComponent.empty()));
} else { } else {

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.inventory; package org.bukkit.craftbukkit.inventory;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
@ -10,7 +11,6 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagList;
import org.apache.commons.lang.Validate;
import org.bukkit.Color; import org.bukkit.Color;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.configuration.serialization.DelegateDeserialization; import org.bukkit.configuration.serialization.DelegateDeserialization;
@ -51,14 +51,13 @@ class CraftMetaPotion extends CraftMetaItem implements PotionMeta {
CraftMetaPotion(CraftMetaItem meta) { CraftMetaPotion(CraftMetaItem meta) {
super(meta); super(meta);
if (!(meta instanceof CraftMetaPotion)) { if (!(meta instanceof CraftMetaPotion potionMeta)) {
return; return;
} }
CraftMetaPotion potionMeta = (CraftMetaPotion) meta;
this.type = potionMeta.type; this.type = potionMeta.type;
this.color = potionMeta.color; this.color = potionMeta.color;
if (potionMeta.hasCustomEffects()) { if (potionMeta.hasCustomEffects()) {
this.customEffects = new ArrayList<PotionEffect>(potionMeta.customEffects); this.customEffects = new ArrayList<>(potionMeta.customEffects);
} }
} }
@ -77,7 +76,7 @@ class CraftMetaPotion extends CraftMetaItem implements PotionMeta {
if (tag.contains(POTION_EFFECTS.NBT)) { if (tag.contains(POTION_EFFECTS.NBT)) {
NBTTagList list = tag.getList(POTION_EFFECTS.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND); NBTTagList list = tag.getList(POTION_EFFECTS.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND);
int length = list.size(); int length = list.size();
customEffects = new ArrayList<PotionEffect>(length); customEffects = new ArrayList<>(length);
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
NBTTagCompound effect = list.getCompound(i); NBTTagCompound effect = list.getCompound(i);
@ -112,9 +111,7 @@ class CraftMetaPotion extends CraftMetaItem implements PotionMeta {
} }
for (Object obj : rawEffectList) { for (Object obj : rawEffectList) {
if (!(obj instanceof PotionEffect)) { Preconditions.checkArgument(obj instanceof PotionEffect, "Object (%s) in effect list is not valid", obj.getClass());
throw new IllegalArgumentException("Object in effect list is not valid. " + obj.getClass());
}
addCustomEffect((PotionEffect) obj, true); addCustomEffect((PotionEffect) obj, true);
} }
} }
@ -165,14 +162,14 @@ class CraftMetaPotion extends CraftMetaItem implements PotionMeta {
CraftMetaPotion clone = (CraftMetaPotion) super.clone(); CraftMetaPotion clone = (CraftMetaPotion) super.clone();
clone.type = type; clone.type = type;
if (this.customEffects != null) { if (this.customEffects != null) {
clone.customEffects = new ArrayList<PotionEffect>(this.customEffects); clone.customEffects = new ArrayList<>(this.customEffects);
} }
return clone; return clone;
} }
@Override @Override
public void setBasePotionData(PotionData data) { public void setBasePotionData(PotionData data) {
Validate.notNull(data, "PotionData cannot be null"); Preconditions.checkArgument(data != null, "PotionData cannot be null");
this.type = data; this.type = data;
} }
@ -196,7 +193,7 @@ class CraftMetaPotion extends CraftMetaItem implements PotionMeta {
@Override @Override
public boolean addCustomEffect(PotionEffect effect, boolean overwrite) { 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()); int index = indexOfEffect(effect.getType());
if (index != -1) { if (index != -1) {
@ -212,7 +209,7 @@ class CraftMetaPotion extends CraftMetaItem implements PotionMeta {
} }
} else { } else {
if (customEffects == null) { if (customEffects == null) {
customEffects = new ArrayList<PotionEffect>(); customEffects = new ArrayList<>();
} }
customEffects.add(effect); customEffects.add(effect);
return true; return true;
@ -221,7 +218,7 @@ class CraftMetaPotion extends CraftMetaItem implements PotionMeta {
@Override @Override
public boolean removeCustomEffect(PotionEffectType type) { 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()) { if (!hasCustomEffects()) {
return false; return false;
@ -244,13 +241,13 @@ class CraftMetaPotion extends CraftMetaItem implements PotionMeta {
@Override @Override
public boolean hasCustomEffect(PotionEffectType type) { 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; return indexOfEffect(type) != -1;
} }
@Override @Override
public boolean setMainEffect(PotionEffectType type) { 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); int index = indexOfEffect(type);
if (index == -1 || index == 0) { if (index == -1 || index == 0) {
return false; return false;

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.inventory; package org.bukkit.craftbukkit.inventory;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.ImmutableMap.Builder;
import java.util.ArrayList; import java.util.ArrayList;
@ -8,11 +9,8 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagList;
import org.apache.commons.lang.Validate;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.configuration.serialization.DelegateDeserialization; 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.craftbukkit.util.CraftMagicNumbers;
import org.bukkit.inventory.meta.SuspiciousStewMeta; import org.bukkit.inventory.meta.SuspiciousStewMeta;
import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffect;
@ -29,12 +27,11 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious
CraftMetaSuspiciousStew(CraftMetaItem meta) { CraftMetaSuspiciousStew(CraftMetaItem meta) {
super(meta); super(meta);
if (!(meta instanceof CraftMetaSuspiciousStew)) { if (!(meta instanceof CraftMetaSuspiciousStew stewMeta)) {
return; return;
} }
CraftMetaSuspiciousStew stewMeta = ((CraftMetaSuspiciousStew) meta);
if (stewMeta.hasCustomEffects()) { if (stewMeta.hasCustomEffects()) {
this.customEffects = new ArrayList<PotionEffect>(stewMeta.customEffects); this.customEffects = new ArrayList<>(stewMeta.customEffects);
} }
} }
@ -43,7 +40,7 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious
if (tag.contains(EFFECTS.NBT)) { if (tag.contains(EFFECTS.NBT)) {
NBTTagList list = tag.getList(EFFECTS.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND); NBTTagList list = tag.getList(EFFECTS.NBT, CraftMagicNumbers.NBT.TAG_COMPOUND);
int length = list.size(); int length = list.size();
customEffects = new ArrayList<PotionEffect>(length); customEffects = new ArrayList<>(length);
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
NBTTagCompound effect = list.getCompound(i); NBTTagCompound effect = list.getCompound(i);
@ -66,9 +63,7 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious
} }
for (Object obj : rawEffectList) { for (Object obj : rawEffectList) {
if (!(obj instanceof PotionEffect)) { Preconditions.checkArgument(obj instanceof PotionEffect, "Object (%s) in effect list is not valid", obj.getClass());
throw new IllegalArgumentException("Object in effect list is not valid. " + obj.getClass());
}
addCustomEffect((PotionEffect) obj, true); addCustomEffect((PotionEffect) obj, true);
} }
} }
@ -108,7 +103,7 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious
public CraftMetaSuspiciousStew clone() { public CraftMetaSuspiciousStew clone() {
CraftMetaSuspiciousStew clone = ((CraftMetaSuspiciousStew) super.clone()); CraftMetaSuspiciousStew clone = ((CraftMetaSuspiciousStew) super.clone());
if (this.customEffects != null) { if (this.customEffects != null) {
clone.customEffects = new ArrayList<PotionEffect>(this.customEffects); clone.customEffects = new ArrayList<>(this.customEffects);
} }
return clone; return clone;
} }
@ -128,7 +123,7 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious
@Override @Override
public boolean addCustomEffect(PotionEffect effect, boolean overwrite) { 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()); int index = indexOfEffect(effect.getType());
if (index != -1) { if (index != -1) {
@ -144,7 +139,7 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious
} }
} else { } else {
if (customEffects == null) { if (customEffects == null) {
customEffects = new ArrayList<PotionEffect>(); customEffects = new ArrayList<>();
} }
customEffects.add(effect); customEffects.add(effect);
return true; return true;
@ -153,7 +148,7 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious
@Override @Override
public boolean removeCustomEffect(PotionEffectType type) { 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()) { if (!hasCustomEffects()) {
return false; return false;
@ -176,7 +171,7 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious
@Override @Override
public boolean hasCustomEffect(PotionEffectType type) { 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; return indexOfEffect(type) != -1;
} }
@ -215,9 +210,7 @@ public class CraftMetaSuspiciousStew extends CraftMetaItem implements Suspicious
if (!super.equalsCommon(meta)) { if (!super.equalsCommon(meta)) {
return false; return false;
} }
if (meta instanceof CraftMetaSuspiciousStew) { if (meta instanceof CraftMetaSuspiciousStew that) {
CraftMetaSuspiciousStew that = (CraftMetaSuspiciousStew) meta;
return (this.hasCustomEffects() ? that.hasCustomEffects() && this.customEffects.equals(that.customEffects) : !that.hasCustomEffects()); return (this.hasCustomEffects() ? that.hasCustomEffects() && this.customEffects.equals(that.customEffects) : !that.hasCustomEffects());
} }
return true; return true;

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.inventory; package org.bukkit.craftbukkit.inventory;
import com.google.common.base.Preconditions;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import net.minecraft.world.item.crafting.RecipeItemStack; import net.minecraft.world.item.crafting.RecipeItemStack;
@ -29,8 +30,8 @@ public interface CraftRecipe extends Recipe {
} }
stack.getItems(); stack.getItems();
if (requireNotEmpty && stack.itemStacks.length == 0) { if (requireNotEmpty) {
throw new IllegalArgumentException("Recipe requires at least one non-air choice!"); Preconditions.checkArgument(stack.itemStacks.length != 0, "Recipe requires at least one non-air choice");
} }
return stack; return stack;

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.inventory; package org.bukkit.craftbukkit.inventory;
import com.google.common.base.Preconditions;
import java.util.ListIterator; import java.util.ListIterator;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@ -53,9 +54,7 @@ public class InventoryIterator implements ListIterator<ItemStack> {
@Override @Override
public void set(ItemStack item) { public void set(ItemStack item) {
if (lastDirection == null) { Preconditions.checkState(lastDirection != null, "No current item!");
throw new IllegalStateException("No current item!");
}
int i = lastDirection ? nextIndex - 1 : nextIndex; int i = lastDirection ? nextIndex - 1 : nextIndex;
inventory.setItem(i, item); inventory.setItem(i, item);
} }

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.inventory; package org.bukkit.craftbukkit.inventory;
import com.google.common.base.Preconditions;
import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
@ -43,10 +44,7 @@ public class RecipeIterator implements Iterator<Recipe> {
@Override @Override
public void remove() { public void remove() {
if (current == null) { Preconditions.checkState(current != null, "next() not yet called");
throw new IllegalStateException("next() not yet called");
}
current.remove(); current.remove();
} }
} }

Datei anzeigen

@ -1,6 +1,6 @@
package org.bukkit.craftbukkit.inventory.tags; 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.craftbukkit.persistence.CraftPersistentDataContainer;
import org.bukkit.inventory.meta.tags.CustomItemTagContainer; import org.bukkit.inventory.meta.tags.CustomItemTagContainer;
import org.bukkit.inventory.meta.tags.ItemTagType; import org.bukkit.inventory.meta.tags.ItemTagType;
@ -29,11 +29,11 @@ public final class DeprecatedContainerTagType<Z> implements PersistentDataType<P
@Override @Override
public PersistentDataContainer toPrimitive(Z complex, PersistentDataAdapterContext context) { public PersistentDataContainer toPrimitive(Z complex, PersistentDataAdapterContext context) {
CustomItemTagContainer deprecated = this.deprecated.toPrimitive(complex, new DeprecatedItemAdapterContext(context)); CustomItemTagContainer deprecated = this.deprecated.toPrimitive(complex, new DeprecatedItemAdapterContext(context));
Validate.isInstanceOf(DeprecatedCustomTagContainer.class, deprecated, "Could not wrap deprecated API due to foreign CustomItemTagContainer implementation %s", deprecated.getClass().getSimpleName()); Preconditions.checkArgument(deprecated instanceof DeprecatedCustomTagContainer, "Could not wrap deprecated API due to foreign CustomItemTagContainer implementation %s", deprecated.getClass().getSimpleName());
DeprecatedCustomTagContainer tagContainer = (DeprecatedCustomTagContainer) deprecated; DeprecatedCustomTagContainer tagContainer = (DeprecatedCustomTagContainer) deprecated;
PersistentDataContainer wrapped = tagContainer.getWrapped(); PersistentDataContainer wrapped = tagContainer.getWrapped();
Validate.isInstanceOf(CraftPersistentDataContainer.class, wrapped, "Could not wrap deprecated API due to wrong deprecation wrapper %s", deprecated.getClass().getSimpleName()); Preconditions.checkArgument(wrapped instanceof CraftPersistentDataContainer, "Could not wrap deprecated API due to wrong deprecation wrapper %s", deprecated.getClass().getSimpleName());
CraftPersistentDataContainer craftTagContainer = (CraftPersistentDataContainer) wrapped; CraftPersistentDataContainer craftTagContainer = (CraftPersistentDataContainer) wrapped;
return new CraftPersistentDataContainer(craftTagContainer.getRaw(), craftTagContainer.getDataTagTypeRegistry()); return new CraftPersistentDataContainer(craftTagContainer.getRaw(), craftTagContainer.getDataTagTypeRegistry());
@ -41,7 +41,7 @@ public final class DeprecatedContainerTagType<Z> implements PersistentDataType<P
@Override @Override
public Z fromPrimitive(PersistentDataContainer primitive, PersistentDataAdapterContext context) { public Z fromPrimitive(PersistentDataContainer primitive, PersistentDataAdapterContext context) {
Validate.isInstanceOf(CraftPersistentDataContainer.class, primitive, "Could not wrap deprecated API due to foreign PersistentMetadataContainer implementation %s", primitive.getClass().getSimpleName()); Preconditions.checkArgument(primitive instanceof CraftPersistentDataContainer, "Could not wrap deprecated API due to foreign PersistentMetadataContainer implementation %s", primitive.getClass().getSimpleName());
return this.deprecated.fromPrimitive(new DeprecatedCustomTagContainer(primitive), new DeprecatedItemAdapterContext(context)); return this.deprecated.fromPrimitive(new DeprecatedCustomTagContainer(primitive), new DeprecatedItemAdapterContext(context));
} }

Datei anzeigen

@ -348,17 +348,13 @@ public final class CraftLegacy {
IBlockState state = states.getProperty(dataKey); IBlockState state = states.getProperty(dataKey);
if (state == null) { if (state == null) {
if (whitelistedStates.contains(dataKey)) { Preconditions.checkArgument(whitelistedStates.contains(dataKey), "No state for %s", dataKey);
continue; continue;
} }
throw new IllegalStateException("No state for " + dataKey);
}
Preconditions.checkState(!properties.getString(dataKey).isEmpty(), "Empty data string"); Preconditions.checkState(!properties.getString(dataKey).isEmpty(), "Empty data string");
Optional opt = state.getValue(properties.getString(dataKey)); Optional opt = state.getValue(properties.getString(dataKey));
if (!opt.isPresent()) { Preconditions.checkArgument(opt.isPresent(), "No state value %s for %s", properties.getString(dataKey), dataKey);
throw new IllegalStateException("No state value " + properties.getString(dataKey) + " for " + dataKey);
}
blockData = blockData.setValue(state, (Comparable) opt.get()); blockData = blockData.setValue(state, (Comparable) opt.get());
} }

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.map; package org.bukkit.craftbukkit.map;
import com.google.common.base.Preconditions;
import java.awt.Color; import java.awt.Color;
import java.awt.Image; import java.awt.Image;
import java.util.Arrays; import java.util.Arrays;
@ -102,9 +103,7 @@ public class CraftMapCanvas implements MapCanvas {
public void drawText(int x, int y, MapFont font, String text) { public void drawText(int x, int y, MapFont font, String text) {
int xStart = x; int xStart = x;
byte color = MapPalette.DARK_GRAY; byte color = MapPalette.DARK_GRAY;
if (!font.isValid(text)) { Preconditions.checkArgument(font.isValid(text), "text (%s) contains invalid characters", text);
throw new IllegalArgumentException("text contains invalid characters");
}
for (int i = 0; i < text.length(); ++i) { for (int i = 0; i < text.length(); ++i) {
char ch = text.charAt(i); char ch = text.charAt(i);
@ -114,7 +113,7 @@ public class CraftMapCanvas implements MapCanvas {
continue; continue;
} else if (ch == '\u00A7') { } else if (ch == '\u00A7') {
int j = text.indexOf(';', i); int j = text.indexOf(';', i);
if (j >= 0) { Preconditions.checkArgument(j >= 0, "text (%s) unterminated color string", text);
try { try {
color = Byte.parseByte(text.substring(i + 1, j)); color = Byte.parseByte(text.substring(i + 1, j));
i = j; i = j;
@ -122,8 +121,6 @@ public class CraftMapCanvas implements MapCanvas {
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
} }
} }
throw new IllegalArgumentException("Text contains unterminated color string");
}
CharacterSprite sprite = font.getChar(text.charAt(i)); CharacterSprite sprite = font.getChar(text.charAt(i));
for (int r = 0; r < font.getHeight(); ++r) { for (int r = 0; r < font.getHeight(); ++r) {

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.map; package org.bukkit.craftbukkit.map;
import com.google.common.base.Preconditions;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
@ -16,7 +17,6 @@ import org.bukkit.craftbukkit.CraftWorld;
import org.bukkit.craftbukkit.entity.CraftPlayer; import org.bukkit.craftbukkit.entity.CraftPlayer;
import org.bukkit.map.MapRenderer; import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView; import org.bukkit.map.MapView;
import org.bukkit.map.MapView.Scale;
public final class CraftMapView implements MapView { public final class CraftMapView implements MapView {
@ -33,15 +33,12 @@ public final class CraftMapView implements MapView {
@Override @Override
public int getId() { public int getId() {
String text = worldMap.id; String text = worldMap.id;
if (text.startsWith("map_")) { Preconditions.checkState(text.startsWith("map_"), "Map has a invalid ID");
try { try {
return Integer.parseInt(text.substring("map_".length())); return Integer.parseInt(text.substring("map_".length()));
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
throw new IllegalStateException("Map has non-numeric ID"); throw new IllegalStateException("Map has non-numeric ID");
} }
} else {
throw new IllegalStateException("Map has invalid ID");
}
} }
@Override @Override

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.metadata; package org.bukkit.craftbukkit.metadata;
import com.google.common.base.Preconditions;
import java.util.List; import java.util.List;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.block.Block; import org.bukkit.block.Block;
@ -42,11 +43,8 @@ public class BlockMetadataStore extends MetadataStoreBase<Block> implements Meta
*/ */
@Override @Override
public List<MetadataValue> getMetadata(Block block, String metadataKey) { public List<MetadataValue> getMetadata(Block block, String metadataKey) {
if (block.getWorld() == owningWorld) { Preconditions.checkArgument(block.getWorld() == this.owningWorld, "Block does not belong to world %s", owningWorld.getName());
return super.getMetadata(block, metadataKey); return super.getMetadata(block, metadataKey);
} else {
throw new IllegalArgumentException("Block does not belong to world " + owningWorld.getName());
}
} }
/** /**
@ -56,11 +54,8 @@ public class BlockMetadataStore extends MetadataStoreBase<Block> implements Meta
*/ */
@Override @Override
public boolean hasMetadata(Block block, String metadataKey) { public boolean hasMetadata(Block block, String metadataKey) {
if (block.getWorld() == owningWorld) { Preconditions.checkArgument(block.getWorld() == this.owningWorld, "Block does not belong to world %s", owningWorld.getName());
return super.hasMetadata(block, metadataKey); return super.hasMetadata(block, metadataKey);
} else {
throw new IllegalArgumentException("Block does not belong to world " + owningWorld.getName());
}
} }
/** /**
@ -70,11 +65,8 @@ public class BlockMetadataStore extends MetadataStoreBase<Block> implements Meta
*/ */
@Override @Override
public void removeMetadata(Block block, String metadataKey, Plugin owningPlugin) { public void removeMetadata(Block block, String metadataKey, Plugin owningPlugin) {
if (block.getWorld() == owningWorld) { Preconditions.checkArgument(block.getWorld() == this.owningWorld, "Block does not belong to world %s", owningWorld.getName());
super.removeMetadata(block, metadataKey, owningPlugin); super.removeMetadata(block, metadataKey, owningPlugin);
} else {
throw new IllegalArgumentException("Block does not belong to world " + owningWorld.getName());
}
} }
/** /**
@ -84,10 +76,7 @@ public class BlockMetadataStore extends MetadataStoreBase<Block> implements Meta
*/ */
@Override @Override
public void setMetadata(Block block, String metadataKey, MetadataValue newMetadataValue) { public void setMetadata(Block block, String metadataKey, MetadataValue newMetadataValue) {
if (block.getWorld() == owningWorld) { Preconditions.checkArgument(block.getWorld() == this.owningWorld, "Block does not belong to world %s", owningWorld.getName());
super.setMetadata(block, metadataKey, newMetadataValue); super.setMetadata(block, metadataKey, newMetadataValue);
} else {
throw new IllegalArgumentException("Block does not belong to world " + owningWorld.getName());
}
} }
} }

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.persistence; package org.bukkit.craftbukkit.persistence;
import com.google.common.base.Preconditions;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
@ -8,7 +9,6 @@ import java.util.Objects;
import java.util.Set; import java.util.Set;
import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import org.apache.commons.lang.Validate;
import org.bukkit.NamespacedKey; import org.bukkit.NamespacedKey;
import org.bukkit.craftbukkit.util.CraftNBTTagConfigSerializer; import org.bukkit.craftbukkit.util.CraftNBTTagConfigSerializer;
import org.bukkit.persistence.PersistentDataAdapterContext; import org.bukkit.persistence.PersistentDataAdapterContext;
@ -34,17 +34,17 @@ public class CraftPersistentDataContainer implements PersistentDataContainer {
@Override @Override
public <T, Z> void set(NamespacedKey key, PersistentDataType<T, Z> type, Z value) { public <T, Z> void set(NamespacedKey key, PersistentDataType<T, Z> type, Z value) {
Validate.notNull(key, "The provided key for the custom value was null"); Preconditions.checkArgument(key != null, "The NamespacedKey key cannot be null");
Validate.notNull(type, "The provided type for the custom value was null"); Preconditions.checkArgument(type != null, "The provided type cannot be null");
Validate.notNull(value, "The provided value for the custom value was null"); Preconditions.checkArgument(value != null, "The provided value cannot be null");
this.customDataTags.put(key.toString(), registry.wrap(type.getPrimitiveType(), type.toPrimitive(value, adapterContext))); this.customDataTags.put(key.toString(), registry.wrap(type.getPrimitiveType(), type.toPrimitive(value, adapterContext)));
} }
@Override @Override
public <T, Z> boolean has(NamespacedKey key, PersistentDataType<T, Z> type) { public <T, Z> boolean has(NamespacedKey key, PersistentDataType<T, Z> type) {
Validate.notNull(key, "The provided key for the custom value was null"); Preconditions.checkArgument(key != null, "The NamespacedKey key cannot be null");
Validate.notNull(type, "The provided type for the custom value was null"); Preconditions.checkArgument(type != null, "The provided type cannot be null");
NBTBase value = this.customDataTags.get(key.toString()); NBTBase value = this.customDataTags.get(key.toString());
if (value == null) { if (value == null) {
@ -56,8 +56,8 @@ public class CraftPersistentDataContainer implements PersistentDataContainer {
@Override @Override
public <T, Z> Z get(NamespacedKey key, PersistentDataType<T, Z> type) { public <T, Z> Z get(NamespacedKey key, PersistentDataType<T, Z> type) {
Validate.notNull(key, "The provided key for the custom value was null"); Preconditions.checkArgument(key != null, "The NamespacedKey key cannot be null");
Validate.notNull(type, "The provided type for the custom value was null"); Preconditions.checkArgument(type != null, "The provided type cannot be null");
NBTBase value = this.customDataTags.get(key.toString()); NBTBase value = this.customDataTags.get(key.toString());
if (value == null) { if (value == null) {
@ -89,7 +89,7 @@ public class CraftPersistentDataContainer implements PersistentDataContainer {
@Override @Override
public void remove(NamespacedKey key) { 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()); this.customDataTags.remove(key.toString());
} }

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.persistence; package org.bukkit.craftbukkit.persistence;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Primitives; import com.google.common.primitives.Primitives;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
@ -56,9 +57,7 @@ public final class CraftPersistentDataTypeRegistry {
* extractor function * extractor function
*/ */
T extract(NBTBase base) { T extract(NBTBase base) {
if (!nbtBaseType.isInstance(base)) { Preconditions.checkArgument(nbtBaseType.isInstance(base), "The provided NBTBase was of the type %s. Expected type %s", base.getClass().getSimpleName(), nbtBaseType.getSimpleName());
throw new IllegalArgumentException(String.format("The provided NBTBase was of the type %s. Expected type %s", base.getClass().getSimpleName(), nbtBaseType.getSimpleName()));
}
return this.extractor.apply(nbtBaseType.cast(base)); return this.extractor.apply(nbtBaseType.cast(base));
} }
@ -74,9 +73,7 @@ public final class CraftPersistentDataTypeRegistry {
* function * function
*/ */
Z build(Object value) { Z build(Object value) {
if (!primitiveType.isInstance(value)) { Preconditions.checkArgument(primitiveType.isInstance(value), "The provided value was of the type %s. Expected type %s", value.getClass().getSimpleName(), primitiveType.getSimpleName());
throw new IllegalArgumentException(String.format("The provided value was of the type %s. Expected type %s", value.getClass().getSimpleName(), primitiveType.getSimpleName()));
}
return this.builder.apply(primitiveType.cast(value)); return this.builder.apply(primitiveType.cast(value));
} }
@ -250,14 +247,10 @@ public final class CraftPersistentDataTypeRegistry {
*/ */
public <T> T extract(Class<T> type, NBTBase tag) throws ClassCastException, IllegalArgumentException { public <T> T extract(Class<T> type, NBTBase tag) throws ClassCastException, IllegalArgumentException {
TagAdapter adapter = this.adapters.computeIfAbsent(type, CREATE_ADAPTER); TagAdapter adapter = this.adapters.computeIfAbsent(type, CREATE_ADAPTER);
if (!adapter.isInstance(tag)) { Preconditions.checkArgument(adapter.isInstance(tag), "The found tag instance (%s) cannot store %s", tag.getClass().getSimpleName(), type.getSimpleName());
throw new IllegalArgumentException(String.format("`The found tag instance cannot store %s as it is a %s", type.getSimpleName(), tag.getClass().getSimpleName()));
}
Object foundValue = adapter.extract(tag); Object foundValue = adapter.extract(tag);
if (!type.isInstance(foundValue)) { Preconditions.checkArgument(type.isInstance(foundValue), "The found object is of the type %s. Expected type %s", foundValue.getClass().getSimpleName(), type.getSimpleName());
throw new IllegalArgumentException(String.format("The found object is of the type %s. Expected type %s", foundValue.getClass().getSimpleName(), type.getSimpleName()));
}
return type.cast(foundValue); return type.cast(foundValue);
} }
} }

Datei anzeigen

@ -263,9 +263,7 @@ public final class CraftPlayerProfile implements PlayerProfile {
if (map.containsKey("properties")) { if (map.containsKey("properties")) {
for (Object propertyData : (List<?>) map.get("properties")) { for (Object propertyData : (List<?>) map.get("properties")) {
if (!(propertyData instanceof Map)) { Preconditions.checkArgument(propertyData instanceof Map, "Propertu data (%s) is not a valid Map", propertyData);
throw new IllegalArgumentException("Property data (" + propertyData + ") is not a valid Map");
}
Property property = CraftProfileProperty.deserialize((Map<?, ?>) propertyData); Property property = CraftProfileProperty.deserialize((Map<?, ?>) propertyData);
profile.properties.put(property.getName(), property); profile.properties.put(property.getName(), property);
} }

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.projectiles; package org.bukkit.craftbukkit.projectiles;
import com.google.common.base.Preconditions;
import net.minecraft.core.EnumDirection; import net.minecraft.core.EnumDirection;
import net.minecraft.core.IPosition; import net.minecraft.core.IPosition;
import net.minecraft.core.SourceBlock; 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.entity.projectile.IProjectile;
import net.minecraft.world.level.block.BlockDispenser; import net.minecraft.world.level.block.BlockDispenser;
import net.minecraft.world.level.block.entity.TileEntityDispenser; import net.minecraft.world.level.block.entity.TileEntityDispenser;
import org.apache.commons.lang.Validate;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.craftbukkit.inventory.CraftItemStack; import org.bukkit.craftbukkit.inventory.CraftItemStack;
@ -63,7 +63,7 @@ public class CraftBlockProjectileSource implements BlockProjectileSource {
@Override @Override
public <T extends Projectile> T launchProjectile(Class<? extends T> projectile, Vector velocity) { public <T extends Projectile> T launchProjectile(Class<? extends T> 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() // Copied from BlockDispenser.dispense()
SourceBlock isourceblock = new SourceBlock((WorldServer) dispenserBlock.getLevel(), dispenserBlock.getBlockPos()); SourceBlock isourceblock = new SourceBlock((WorldServer) dispenserBlock.getLevel(), dispenserBlock.getBlockPos());
// Copied from DispenseBehaviorProjectile // Copied from DispenseBehaviorProjectile
@ -132,7 +132,7 @@ public class CraftBlockProjectileSource implements BlockProjectileSource {
((EntityFireball) launch).projectileSource = this; ((EntityFireball) launch).projectileSource = this;
} }
Validate.notNull(launch, "Projectile not supported"); Preconditions.checkArgument(launch != null, "Projectile not supported");
if (launch instanceof IProjectile) { if (launch instanceof IProjectile) {
if (launch instanceof EntityProjectile) { if (launch instanceof EntityProjectile) {

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.scheduler; package org.bukkit.craftbukkit.scheduler;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
@ -16,7 +17,6 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.IntUnaryOperator; import java.util.function.IntUnaryOperator;
import java.util.logging.Level; import java.util.logging.Level;
import org.apache.commons.lang.Validate;
import org.bukkit.plugin.IllegalPluginAccessException; import org.bukkit.plugin.IllegalPluginAccessException;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
@ -283,7 +283,7 @@ public class CraftScheduler implements BukkitScheduler {
@Override @Override
public void cancelTasks(final Plugin plugin) { 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( final CraftTask task = new CraftTask(
new Runnable() { new Runnable() {
@Override @Override
@ -459,16 +459,15 @@ public class CraftScheduler implements BukkitScheduler {
} }
private static void validate(final Plugin plugin, final Object task) { private static void validate(final Plugin plugin, final Object task) {
Validate.notNull(plugin, "Plugin cannot be null"); Preconditions.checkArgument(plugin != null, "Plugin cannot be null");
Validate.notNull(task, "Task cannot be null"); Preconditions.checkArgument(task instanceof Runnable || task instanceof Consumer || task instanceof Callable, "Task must be Runnable, Consumer, or Callable");
Validate.isTrue(task instanceof Runnable || task instanceof Consumer || task instanceof Callable, "Task must be Runnable, Consumer, or Callable");
if (!plugin.isEnabled()) { if (!plugin.isEnabled()) {
throw new IllegalPluginAccessException("Plugin attempted to register task while disabled"); throw new IllegalPluginAccessException("Plugin attempted to register task while disabled");
} }
} }
private int nextId() { 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; int id;
do { do {
id = ids.updateAndGet(INCREMENT_IDS); id = ids.updateAndGet(INCREMENT_IDS);

Datei anzeigen

@ -1,8 +1,8 @@
package org.bukkit.craftbukkit.scoreboard; package org.bukkit.craftbukkit.scoreboard;
import com.google.common.base.Preconditions;
import net.minecraft.world.scores.Scoreboard; import net.minecraft.world.scores.Scoreboard;
import net.minecraft.world.scores.ScoreboardObjective; import net.minecraft.world.scores.ScoreboardObjective;
import org.apache.commons.lang.Validate;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.craftbukkit.util.CraftChatMessage; import org.bukkit.craftbukkit.util.CraftChatMessage;
import org.bukkit.scoreboard.Criteria; import org.bukkit.scoreboard.Criteria;
@ -27,44 +27,44 @@ final class CraftObjective extends CraftScoreboardComponent implements Objective
@Override @Override
public String getName() throws IllegalStateException { public String getName() throws IllegalStateException {
CraftScoreboard scoreboard = checkState(); checkState();
return objective.getName(); return objective.getName();
} }
@Override @Override
public String getDisplayName() throws IllegalStateException { public String getDisplayName() throws IllegalStateException {
CraftScoreboard scoreboard = checkState(); checkState();
return CraftChatMessage.fromComponent(objective.getDisplayName()); return CraftChatMessage.fromComponent(objective.getDisplayName());
} }
@Override @Override
public void setDisplayName(String displayName) throws IllegalStateException, IllegalArgumentException { public void setDisplayName(String displayName) throws IllegalStateException, IllegalArgumentException {
Validate.notNull(displayName, "Display name cannot be null"); Preconditions.checkArgument(displayName != null, "Display name cannot be null");
Validate.isTrue(displayName.length() <= 128, "Display name '" + displayName + "' is longer than the limit of 128 characters"); Preconditions.checkArgument(displayName.length() <= 128, "Display name '" + displayName + "' is longer than the limit of 128 characters");
CraftScoreboard scoreboard = checkState(); checkState();
objective.setDisplayName(CraftChatMessage.fromString(displayName)[0]); // SPIGOT-4112: not nullable objective.setDisplayName(CraftChatMessage.fromString(displayName)[0]); // SPIGOT-4112: not nullable
} }
@Override @Override
public String getCriteria() throws IllegalStateException { public String getCriteria() throws IllegalStateException {
CraftScoreboard scoreboard = checkState(); checkState();
return criteria.bukkitName; return criteria.bukkitName;
} }
@Override @Override
public Criteria getTrackedCriteria() throws IllegalStateException { public Criteria getTrackedCriteria() throws IllegalStateException {
CraftScoreboard scoreboard = checkState(); checkState();
return criteria; return criteria;
} }
@Override @Override
public boolean isModifiable() throws IllegalStateException { public boolean isModifiable() throws IllegalStateException {
CraftScoreboard scoreboard = checkState(); checkState();
return !criteria.criteria.isReadOnly(); return !criteria.criteria.isReadOnly();
} }
@ -102,32 +102,32 @@ final class CraftObjective extends CraftScoreboardComponent implements Objective
@Override @Override
public void setRenderType(RenderType renderType) throws IllegalStateException { public void setRenderType(RenderType renderType) throws IllegalStateException {
Validate.notNull(renderType, "RenderType cannot be null"); Preconditions.checkArgument(renderType != null, "RenderType cannot be null");
CraftScoreboard scoreboard = checkState(); checkState();
this.objective.setRenderType(CraftScoreboardTranslations.fromBukkitRender(renderType)); this.objective.setRenderType(CraftScoreboardTranslations.fromBukkitRender(renderType));
} }
@Override @Override
public RenderType getRenderType() throws IllegalStateException { public RenderType getRenderType() throws IllegalStateException {
CraftScoreboard scoreboard = checkState(); checkState();
return CraftScoreboardTranslations.toBukkitRender(this.objective.getRenderType()); return CraftScoreboardTranslations.toBukkitRender(this.objective.getRenderType());
} }
@Override @Override
public Score getScore(OfflinePlayer player) throws IllegalArgumentException, IllegalStateException { public Score getScore(OfflinePlayer player) throws IllegalArgumentException, IllegalStateException {
Validate.notNull(player, "Player cannot be null"); Preconditions.checkArgument(player != null, "Player cannot be null");
CraftScoreboard scoreboard = checkState(); checkState();
return new CraftScore(this, player.getName()); return new CraftScore(this, player.getName());
} }
@Override @Override
public Score getScore(String entry) throws IllegalArgumentException, IllegalStateException { public Score getScore(String entry) throws IllegalArgumentException, IllegalStateException {
Validate.notNull(entry, "Entry cannot be null"); Preconditions.checkArgument(entry != null, "Entry cannot be null");
Validate.isTrue(entry.length() <= Short.MAX_VALUE, "Score '" + entry + "' is longer than the limit of 32767 characters"); Preconditions.checkArgument(entry.length() <= Short.MAX_VALUE, "Score '" + entry + "' is longer than the limit of 32767 characters");
CraftScoreboard scoreboard = checkState(); checkState();
return new CraftScore(this, entry); return new CraftScore(this, entry);
} }
@ -141,9 +141,7 @@ final class CraftObjective extends CraftScoreboardComponent implements Objective
@Override @Override
CraftScoreboard checkState() throws IllegalStateException { CraftScoreboard checkState() throws IllegalStateException {
if (getScoreboard().board.getObjective(objective.getName()) == null) { Preconditions.checkState(getScoreboard().board.getObjective(objective.getName()) != null, "Unregistered scoreboard component");
throw new IllegalStateException("Unregistered scoreboard component");
}
return getScoreboard(); return getScoreboard();
} }

Datei anzeigen

@ -1,13 +1,12 @@
package org.bukkit.craftbukkit.scoreboard; package org.bukkit.craftbukkit.scoreboard;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import java.util.Collection;
import net.minecraft.world.scores.Scoreboard; import net.minecraft.world.scores.Scoreboard;
import net.minecraft.world.scores.ScoreboardObjective; import net.minecraft.world.scores.ScoreboardObjective;
import net.minecraft.world.scores.ScoreboardTeam; import net.minecraft.world.scores.ScoreboardTeam;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.craftbukkit.util.CraftChatMessage; import org.bukkit.craftbukkit.util.CraftChatMessage;
@ -47,13 +46,13 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard {
@Override @Override
public CraftObjective registerNewObjective(String name, Criteria criteria, String displayName, RenderType renderType) throws IllegalArgumentException { public CraftObjective registerNewObjective(String name, Criteria criteria, String displayName, RenderType renderType) throws IllegalArgumentException {
Validate.notNull(name, "Objective name cannot be null"); Preconditions.checkArgument(name != null, "Objective name cannot be null");
Validate.notNull(criteria, "Criteria cannot be null"); Preconditions.checkArgument(criteria != null, "Criteria cannot be null");
Validate.notNull(displayName, "Display name cannot be null"); Preconditions.checkArgument(displayName != null, "Display name cannot be null");
Validate.notNull(renderType, "RenderType cannot be null"); Preconditions.checkArgument(renderType != null, "RenderType cannot be null");
Validate.isTrue(name.length() <= Short.MAX_VALUE, "The name '" + name + "' is longer than the limit of 32767 characters"); Preconditions.checkArgument(name.length() <= Short.MAX_VALUE, "The name '%s' is longer than the limit of 32767 characters (%s)", name, name.length());
Validate.isTrue(displayName.length() <= 128, "The display name '" + displayName + "' is longer than the limit of 128 characters"); Preconditions.checkArgument(displayName.length() <= 128, "The display name '%s' is longer than the limit of 128 characters (%s)", displayName, displayName.length());
Validate.isTrue(board.getObjective(name) == null, "An objective of name '" + name + "' already exists"); 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)); ScoreboardObjective objective = board.addObjective(name, ((CraftCriteria) criteria).criteria, CraftChatMessage.fromStringOrNull(displayName), CraftScoreboardTranslations.fromBukkitRender(renderType));
return new CraftObjective(this, objective); return new CraftObjective(this, objective);
@ -61,17 +60,17 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard {
@Override @Override
public Objective getObjective(String name) throws IllegalArgumentException { 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); ScoreboardObjective nms = board.getObjective(name);
return nms == null ? null : new CraftObjective(this, nms); return nms == null ? null : new CraftObjective(this, nms);
} }
@Override @Override
public ImmutableSet<Objective> getObjectivesByCriteria(String criteria) throws IllegalArgumentException { public ImmutableSet<Objective> getObjectivesByCriteria(String criteria) throws IllegalArgumentException {
Validate.notNull(criteria, "Criteria cannot be null"); Preconditions.checkArgument(criteria != null, "Criteria name cannot be null");
ImmutableSet.Builder<Objective> objectives = ImmutableSet.builder(); ImmutableSet.Builder<Objective> objectives = ImmutableSet.builder();
for (ScoreboardObjective netObjective : (Collection<ScoreboardObjective>) this.board.getObjectives()) { for (ScoreboardObjective netObjective : this.board.getObjectives()) {
CraftObjective objective = new CraftObjective(this, netObjective); CraftObjective objective = new CraftObjective(this, netObjective);
if (objective.getCriteria().equals(criteria)) { if (objective.getCriteria().equals(criteria)) {
objectives.add(objective); objectives.add(objective);
@ -82,7 +81,7 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard {
@Override @Override
public ImmutableSet<Objective> getObjectivesByCriteria(Criteria criteria) throws IllegalArgumentException { public ImmutableSet<Objective> getObjectivesByCriteria(Criteria criteria) throws IllegalArgumentException {
Validate.notNull(criteria, "Criteria cannot be null"); Preconditions.checkArgument(criteria != null, "Criteria cannot be null");
ImmutableSet.Builder<Objective> objectives = ImmutableSet.builder(); ImmutableSet.Builder<Objective> objectives = ImmutableSet.builder();
for (ScoreboardObjective netObjective : board.getObjectives()) { for (ScoreboardObjective netObjective : board.getObjectives()) {
@ -97,18 +96,12 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard {
@Override @Override
public ImmutableSet<Objective> getObjectives() { public ImmutableSet<Objective> getObjectives() {
return ImmutableSet.copyOf(Iterables.transform((Collection<ScoreboardObjective>) this.board.getObjectives(), new Function<ScoreboardObjective, Objective>() { return ImmutableSet.copyOf(Iterables.transform(this.board.getObjectives(), (Function<ScoreboardObjective, Objective>) input -> new CraftObjective(CraftScoreboard.this, input)));
@Override
public Objective apply(ScoreboardObjective input) {
return new CraftObjective(CraftScoreboard.this, input);
}
}));
} }
@Override @Override
public Objective getObjective(DisplaySlot slot) throws IllegalArgumentException { 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)); ScoreboardObjective objective = board.getDisplayObjective(CraftScoreboardTranslations.fromBukkitSlot(slot));
if (objective == null) { if (objective == null) {
return null; return null;
@ -118,17 +111,17 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard {
@Override @Override
public ImmutableSet<Score> getScores(OfflinePlayer player) throws IllegalArgumentException { public ImmutableSet<Score> getScores(OfflinePlayer player) throws IllegalArgumentException {
Validate.notNull(player, "OfflinePlayer cannot be null"); Preconditions.checkArgument(player != null, "OfflinePlayer cannot be null");
return getScores(player.getName()); return getScores(player.getName());
} }
@Override @Override
public ImmutableSet<Score> getScores(String entry) throws IllegalArgumentException { public ImmutableSet<Score> getScores(String entry) throws IllegalArgumentException {
Validate.notNull(entry, "Entry cannot be null"); Preconditions.checkArgument(entry != null, "Entry cannot be null");
ImmutableSet.Builder<Score> scores = ImmutableSet.builder(); ImmutableSet.Builder<Score> scores = ImmutableSet.builder();
for (ScoreboardObjective objective : (Collection<ScoreboardObjective>) this.board.getObjectives()) { for (ScoreboardObjective objective : this.board.getObjectives()) {
scores.add(new CraftScore(new CraftObjective(this, objective), entry)); scores.add(new CraftScore(new CraftObjective(this, objective), entry));
} }
return scores.build(); return scores.build();
@ -136,23 +129,23 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard {
@Override @Override
public void resetScores(OfflinePlayer player) throws IllegalArgumentException { 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()); resetScores(player.getName());
} }
@Override @Override
public void resetScores(String entry) throws IllegalArgumentException { 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<ScoreboardObjective>) this.board.getObjectives()) { for (ScoreboardObjective objective : this.board.getObjectives()) {
board.resetPlayerScore(entry, objective); board.resetPlayerScore(entry, objective);
} }
} }
@Override @Override
public Team getPlayerTeam(OfflinePlayer player) throws IllegalArgumentException { 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()); ScoreboardTeam team = board.getPlayersTeam(player.getName());
return team == null ? null : new CraftTeam(this, team); return team == null ? null : new CraftTeam(this, team);
@ -160,7 +153,7 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard {
@Override @Override
public Team getEntryTeam(String entry) throws IllegalArgumentException { 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); ScoreboardTeam team = board.getPlayersTeam(entry);
return team == null ? null : new CraftTeam(this, team); return team == null ? null : new CraftTeam(this, team);
@ -168,7 +161,7 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard {
@Override @Override
public Team getTeam(String teamName) throws IllegalArgumentException { 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); ScoreboardTeam team = board.getPlayerTeam(teamName);
return team == null ? null : new CraftTeam(this, team); return team == null ? null : new CraftTeam(this, team);
@ -176,20 +169,14 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard {
@Override @Override
public ImmutableSet<Team> getTeams() { public ImmutableSet<Team> getTeams() {
return ImmutableSet.copyOf(Iterables.transform((Collection<ScoreboardTeam>) this.board.getPlayerTeams(), new Function<ScoreboardTeam, Team>() { return ImmutableSet.copyOf(Iterables.transform(this.board.getPlayerTeams(), (Function<ScoreboardTeam, Team>) input -> new CraftTeam(CraftScoreboard.this, input)));
@Override
public Team apply(ScoreboardTeam input) {
return new CraftTeam(CraftScoreboard.this, input);
}
}));
} }
@Override @Override
public Team registerNewTeam(String name) throws IllegalArgumentException { public Team registerNewTeam(String name) throws IllegalArgumentException {
Validate.notNull(name, "Team name cannot be null"); Preconditions.checkArgument(name != null, "Team name cannot be null");
Validate.isTrue(name.length() <= Short.MAX_VALUE, "Team name '" + name + "' is longer than the limit of 32767 characters"); Preconditions.checkArgument(name.length() <= Short.MAX_VALUE, "Team name '%s' is longer than the limit of 32767 characters (%s)", name, name.length());
Validate.isTrue(board.getPlayerTeam(name) == null, "Team name '" + name + "' is already in use"); Preconditions.checkArgument(board.getPlayerTeam(name) == null, "Team name '%s' is already in use", name);
return new CraftTeam(this, board.addPlayerTeam(name)); return new CraftTeam(this, board.addPlayerTeam(name));
} }
@ -214,7 +201,7 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard {
@Override @Override
public void clearSlot(DisplaySlot slot) throws IllegalArgumentException { 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); board.setDisplayObjective(CraftScoreboardTranslations.fromBukkitSlot(slot), null);
} }

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.scoreboard; package org.bukkit.craftbukkit.scoreboard;
import com.google.common.base.Preconditions;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; 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.ScoreboardScore;
import net.minecraft.world.scores.ScoreboardTeam; import net.minecraft.world.scores.ScoreboardTeam;
import net.minecraft.world.scores.criteria.IScoreboardCriteria; import net.minecraft.world.scores.criteria.IScoreboardCriteria;
import org.apache.commons.lang.Validate;
import org.bukkit.craftbukkit.entity.CraftPlayer; import org.bukkit.craftbukkit.entity.CraftPlayer;
import org.bukkit.craftbukkit.util.WeakCollection; import org.bukkit.craftbukkit.util.WeakCollection;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -54,7 +54,7 @@ public final class CraftScoreboardManager implements ScoreboardManager {
// CraftBukkit method // CraftBukkit method
public void setPlayerBoard(CraftPlayer player, org.bukkit.scoreboard.Scoreboard bukkitScoreboard) throws IllegalArgumentException { 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; CraftScoreboard scoreboard = (CraftScoreboard) bukkitScoreboard;
net.minecraft.world.scores.Scoreboard oldboard = getPlayerBoard(player).getHandle(); net.minecraft.world.scores.Scoreboard oldboard = getPlayerBoard(player).getHandle();

Datei anzeigen

@ -1,19 +1,17 @@
package org.bukkit.craftbukkit.scoreboard; package org.bukkit.craftbukkit.scoreboard;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import java.util.Set; import java.util.Set;
import net.minecraft.world.scores.ScoreboardTeam; import net.minecraft.world.scores.ScoreboardTeam;
import net.minecraft.world.scores.ScoreboardTeamBase; import net.minecraft.world.scores.ScoreboardTeamBase;
import net.minecraft.world.scores.ScoreboardTeamBase.EnumNameTagVisibility; import net.minecraft.world.scores.ScoreboardTeamBase.EnumNameTagVisibility;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.craftbukkit.util.CraftChatMessage; import org.bukkit.craftbukkit.util.CraftChatMessage;
import org.bukkit.scoreboard.NameTagVisibility; import org.bukkit.scoreboard.NameTagVisibility;
import org.bukkit.scoreboard.Team; import org.bukkit.scoreboard.Team;
import org.bukkit.scoreboard.Team.Option;
import org.bukkit.scoreboard.Team.OptionStatus;
final class CraftTeam extends CraftScoreboardComponent implements Team { final class CraftTeam extends CraftScoreboardComponent implements Team {
private final ScoreboardTeam team; private final ScoreboardTeam team;
@ -25,119 +23,121 @@ final class CraftTeam extends CraftScoreboardComponent implements Team {
@Override @Override
public String getName() throws IllegalStateException { public String getName() throws IllegalStateException {
CraftScoreboard scoreboard = checkState(); checkState();
return team.getName(); return team.getName();
} }
@Override @Override
public String getDisplayName() throws IllegalStateException { public String getDisplayName() throws IllegalStateException {
CraftScoreboard scoreboard = checkState(); checkState();
return CraftChatMessage.fromComponent(team.getDisplayName()); return CraftChatMessage.fromComponent(team.getDisplayName());
} }
@Override @Override
public void setDisplayName(String displayName) throws IllegalStateException { public void setDisplayName(String displayName) throws IllegalStateException {
Validate.notNull(displayName, "Display name cannot be null"); Preconditions.checkArgument(displayName != null, "Display name cannot be null");
Validate.isTrue(ChatColor.stripColor(displayName).length() <= 128, "Display name '" + displayName + "' is longer than the limit of 128 characters"); int lengthStripedDisplayName = ChatColor.stripColor(displayName).length();
CraftScoreboard scoreboard = checkState(); 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 team.setDisplayName(CraftChatMessage.fromString(displayName)[0]); // SPIGOT-4112: not nullable
} }
@Override @Override
public String getPrefix() throws IllegalStateException { public String getPrefix() throws IllegalStateException {
CraftScoreboard scoreboard = checkState(); checkState();
return CraftChatMessage.fromComponent(team.getPlayerPrefix()); return CraftChatMessage.fromComponent(team.getPlayerPrefix());
} }
@Override @Override
public void setPrefix(String prefix) throws IllegalStateException, IllegalArgumentException { public void setPrefix(String prefix) throws IllegalStateException, IllegalArgumentException {
Validate.notNull(prefix, "Prefix cannot be null"); Preconditions.checkArgument(prefix != null, "Prefix cannot be null");
Validate.isTrue(ChatColor.stripColor(prefix).length() <= 64, "Prefix '" + prefix + "' is longer than the limit of 64 characters"); int lengthStripedPrefix = ChatColor.stripColor(prefix).length();
CraftScoreboard scoreboard = checkState(); Preconditions.checkArgument(lengthStripedPrefix <= 64, "Prefix '%s' is longer than the limit of 64 characters (%s)", prefix, lengthStripedPrefix);
checkState();
team.setPlayerPrefix(CraftChatMessage.fromStringOrNull(prefix)); team.setPlayerPrefix(CraftChatMessage.fromStringOrNull(prefix));
} }
@Override @Override
public String getSuffix() throws IllegalStateException { public String getSuffix() throws IllegalStateException {
CraftScoreboard scoreboard = checkState(); checkState();
return CraftChatMessage.fromComponent(team.getPlayerSuffix()); return CraftChatMessage.fromComponent(team.getPlayerSuffix());
} }
@Override @Override
public void setSuffix(String suffix) throws IllegalStateException, IllegalArgumentException { public void setSuffix(String suffix) throws IllegalStateException, IllegalArgumentException {
Validate.notNull(suffix, "Suffix cannot be null"); Preconditions.checkArgument(suffix != null, "Suffix cannot be null");
Validate.isTrue(ChatColor.stripColor(suffix).length() <= 64, "Suffix '" + suffix + "' is longer than the limit of 64 characters"); int lengthStripedSuffix = ChatColor.stripColor(suffix).length();
CraftScoreboard scoreboard = checkState(); Preconditions.checkArgument(lengthStripedSuffix <= 64, "Suffix '%s' is longer than the limit of 64 characters (%s)", suffix, lengthStripedSuffix);
team.setPlayerSuffix(CraftChatMessage.fromStringOrNull(suffix)); team.setPlayerSuffix(CraftChatMessage.fromStringOrNull(suffix));
} }
@Override @Override
public ChatColor getColor() throws IllegalStateException { public ChatColor getColor() throws IllegalStateException {
CraftScoreboard scoreboard = checkState(); checkState();
return CraftChatMessage.getColor(team.getColor()); return CraftChatMessage.getColor(team.getColor());
} }
@Override @Override
public void setColor(ChatColor color) { public void setColor(ChatColor color) {
Validate.notNull(color, "Color cannot be null"); Preconditions.checkArgument(color != null, "Color cannot be null");
CraftScoreboard scoreboard = checkState(); checkState();
team.setColor(CraftChatMessage.getColor(color)); team.setColor(CraftChatMessage.getColor(color));
} }
@Override @Override
public boolean allowFriendlyFire() throws IllegalStateException { public boolean allowFriendlyFire() throws IllegalStateException {
CraftScoreboard scoreboard = checkState(); checkState();
return team.isAllowFriendlyFire(); return team.isAllowFriendlyFire();
} }
@Override @Override
public void setAllowFriendlyFire(boolean enabled) throws IllegalStateException { public void setAllowFriendlyFire(boolean enabled) throws IllegalStateException {
CraftScoreboard scoreboard = checkState(); checkState();
team.setAllowFriendlyFire(enabled); team.setAllowFriendlyFire(enabled);
} }
@Override @Override
public boolean canSeeFriendlyInvisibles() throws IllegalStateException { public boolean canSeeFriendlyInvisibles() throws IllegalStateException {
CraftScoreboard scoreboard = checkState(); checkState();
return team.canSeeFriendlyInvisibles(); return team.canSeeFriendlyInvisibles();
} }
@Override @Override
public void setCanSeeFriendlyInvisibles(boolean enabled) throws IllegalStateException { public void setCanSeeFriendlyInvisibles(boolean enabled) throws IllegalStateException {
CraftScoreboard scoreboard = checkState(); checkState();
team.setSeeFriendlyInvisibles(enabled); team.setSeeFriendlyInvisibles(enabled);
} }
@Override @Override
public NameTagVisibility getNameTagVisibility() throws IllegalArgumentException { public NameTagVisibility getNameTagVisibility() throws IllegalArgumentException {
CraftScoreboard scoreboard = checkState(); checkState();
return notchToBukkit(team.getNameTagVisibility()); return notchToBukkit(team.getNameTagVisibility());
} }
@Override @Override
public void setNameTagVisibility(NameTagVisibility visibility) throws IllegalArgumentException { public void setNameTagVisibility(NameTagVisibility visibility) throws IllegalArgumentException {
CraftScoreboard scoreboard = checkState(); checkState();
team.setNameTagVisibility(bukkitToNotch(visibility)); team.setNameTagVisibility(bukkitToNotch(visibility));
} }
@Override @Override
public Set<OfflinePlayer> getPlayers() throws IllegalStateException { public Set<OfflinePlayer> getPlayers() throws IllegalStateException {
CraftScoreboard scoreboard = checkState(); checkState();
ImmutableSet.Builder<OfflinePlayer> players = ImmutableSet.builder(); ImmutableSet.Builder<OfflinePlayer> players = ImmutableSet.builder();
for (String playerName : team.getPlayers()) { for (String playerName : team.getPlayers()) {
@ -148,7 +148,7 @@ final class CraftTeam extends CraftScoreboardComponent implements Team {
@Override @Override
public Set<String> getEntries() throws IllegalStateException { public Set<String> getEntries() throws IllegalStateException {
CraftScoreboard scoreboard = checkState(); checkState();
ImmutableSet.Builder<String> entries = ImmutableSet.builder(); ImmutableSet.Builder<String> entries = ImmutableSet.builder();
for (String playerName : team.getPlayers()) { for (String playerName : team.getPlayers()) {
@ -159,20 +159,20 @@ final class CraftTeam extends CraftScoreboardComponent implements Team {
@Override @Override
public int getSize() throws IllegalStateException { public int getSize() throws IllegalStateException {
CraftScoreboard scoreboard = checkState(); checkState();
return team.getPlayers().size(); return team.getPlayers().size();
} }
@Override @Override
public void addPlayer(OfflinePlayer player) throws IllegalStateException, IllegalArgumentException { 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()); addEntry(player.getName());
} }
@Override @Override
public void addEntry(String entry) throws IllegalStateException, IllegalArgumentException { 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(); CraftScoreboard scoreboard = checkState();
scoreboard.board.addPlayerToTeam(entry, team); scoreboard.board.addPlayerToTeam(entry, team);
@ -180,13 +180,13 @@ final class CraftTeam extends CraftScoreboardComponent implements Team {
@Override @Override
public boolean removePlayer(OfflinePlayer player) throws IllegalStateException, IllegalArgumentException { 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()); return removeEntry(player.getName());
} }
@Override @Override
public boolean removeEntry(String entry) throws IllegalStateException, IllegalArgumentException { 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(); CraftScoreboard scoreboard = checkState();
if (!team.getPlayers().contains(entry)) { if (!team.getPlayers().contains(entry)) {
@ -199,15 +199,14 @@ final class CraftTeam extends CraftScoreboardComponent implements Team {
@Override @Override
public boolean hasPlayer(OfflinePlayer player) throws IllegalArgumentException, IllegalStateException { 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()); return hasEntry(player.getName());
} }
@Override @Override
public boolean hasEntry(String entry) throws IllegalArgumentException, IllegalStateException { public boolean hasEntry(String entry) throws IllegalArgumentException, IllegalStateException {
Validate.notNull("Entry cannot be null"); Preconditions.checkArgument(entry != null, "Entry cannot be null");
checkState();
CraftScoreboard scoreboard = checkState();
return team.getPlayers().contains(entry); return team.getPlayers().contains(entry);
} }
@ -286,9 +285,7 @@ final class CraftTeam extends CraftScoreboardComponent implements Team {
@Override @Override
CraftScoreboard checkState() throws IllegalStateException { CraftScoreboard checkState() throws IllegalStateException {
if (getScoreboard().board.getPlayerTeam(team.getName()) == null) { Preconditions.checkState(getScoreboard().board.getPlayerTeam(team.getName()) != null, "Unregistered scoreboard component");
throw new IllegalStateException("Unregistered scoreboard component");
}
return getScoreboard(); return getScoreboard();
} }

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.structure; package org.bukkit.craftbukkit.structure;
import com.google.common.base.Preconditions;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; 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.DefinedStructure;
import net.minecraft.world.level.levelgen.structure.templatesystem.DefinedStructureInfo; import net.minecraft.world.level.levelgen.structure.templatesystem.DefinedStructureInfo;
import net.minecraft.world.level.levelgen.structure.templatesystem.DefinedStructureProcessorRotation; import net.minecraft.world.level.levelgen.structure.templatesystem.DefinedStructureProcessorRotation;
import org.apache.commons.lang3.Validate;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.RegionAccessor; import org.bukkit.RegionAccessor;
@ -42,9 +42,10 @@ public class CraftStructure implements Structure {
@Override @Override
public void place(Location location, boolean includeEntities, StructureRotation structureRotation, Mirror mirror, int palette, float integrity, Random random) { 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(); location.checkFinite();
World world = location.getWorld(); 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()); BlockVector blockVector = new BlockVector(location.getBlockX(), location.getBlockY(), location.getBlockZ());
place(world, blockVector, includeEntities, structureRotation, mirror, palette, integrity, random); place(world, blockVector, includeEntities, structureRotation, mirror, palette, integrity, random);
@ -52,12 +53,11 @@ public class CraftStructure implements Structure {
@Override @Override
public void place(RegionAccessor regionAccessor, BlockVector location, boolean includeEntities, StructureRotation structureRotation, Mirror mirror, int palette, float integrity, Random random) { 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(); location.checkFinite();
if (integrity < 0F || integrity > 1F) { Preconditions.checkArgument(integrity >= 0F && integrity <= 1F, "Integrity value (%S) must be between 0 and 1 inclusive", integrity);
throw new IllegalArgumentException("Integrity must be between 0 and 1 inclusive. Was \"" + integrity + "\"");
}
RandomSource randomSource = new RandomSourceWrapper(random); RandomSource randomSource = new RandomSourceWrapper(random);
DefinedStructureInfo definedstructureinfo = new DefinedStructureInfo() DefinedStructureInfo definedstructureinfo = new DefinedStructureInfo()
@ -74,10 +74,10 @@ public class CraftStructure implements Structure {
@Override @Override
public void fill(Location corner1, Location corner2, boolean includeEntities) { public void fill(Location corner1, Location corner2, boolean includeEntities) {
Validate.notNull(corner1, "corner1 cannot be null"); Preconditions.checkArgument(corner1 != null, "Location corner1 cannot be null");
Validate.notNull(corner2, "corner2 cannot be null"); Preconditions.checkArgument(corner2 != null, "Location corner2 cannot be null");
World world = corner1.getWorld(); 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())); 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())); 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 @Override
public void fill(Location origin, BlockVector size, boolean includeEntities) { 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(); World world = origin.getWorld();
Validate.notNull(world, "origin#getWorld() cannot be null"); Preconditions.checkArgument(world != null, "World of Location origin cannot be null");
Validate.notNull(size, "size cannot be null"); Preconditions.checkArgument(size != null, "BlockVector size cannot be null");
if (size.getBlockX() < 1 || size.getBlockY() < 1 || size.getBlockZ() < 1) { 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());
throw new IllegalArgumentException("Size must be at least 1x1x1 but was " + size.getBlockX() + "x" + size.getBlockY() + "x" + size.getBlockZ());
}
structure.fillFromWorld(((CraftWorld) world).getHandle(), CraftLocation.toBlockPosition(origin), CraftBlockVector.toBlockPosition(size), includeEntities, Blocks.STRUCTURE_VOID); structure.fillFromWorld(((CraftWorld) world).getHandle(), CraftLocation.toBlockPosition(origin), CraftBlockVector.toBlockPosition(size), includeEntities, Blocks.STRUCTURE_VOID);
} }

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.structure; package org.bukkit.craftbukkit.structure;
import com.google.common.base.Preconditions;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@ -17,7 +18,6 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.resources.MinecraftKey; import net.minecraft.resources.MinecraftKey;
import net.minecraft.world.level.levelgen.structure.templatesystem.DefinedStructure; import net.minecraft.world.level.levelgen.structure.templatesystem.DefinedStructure;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
import org.apache.commons.lang3.Validate;
import org.bukkit.NamespacedKey; import org.bukkit.NamespacedKey;
import org.bukkit.craftbukkit.util.CraftNamespacedKey; import org.bukkit.craftbukkit.util.CraftNamespacedKey;
import org.bukkit.structure.Structure; import org.bukkit.structure.Structure;
@ -35,16 +35,14 @@ public class CraftStructureManager implements StructureManager {
public Map<NamespacedKey, Structure> getStructures() { public Map<NamespacedKey, Structure> getStructures() {
Map<NamespacedKey, Structure> cachedStructures = new HashMap<>(); Map<NamespacedKey, Structure> cachedStructures = new HashMap<>();
for (Map.Entry<MinecraftKey, Optional<DefinedStructure>> entry : structureManager.structureRepository.entrySet()) { for (Map.Entry<MinecraftKey, Optional<DefinedStructure>> entry : structureManager.structureRepository.entrySet()) {
entry.getValue().ifPresent(definedStructure -> { entry.getValue().ifPresent(definedStructure -> cachedStructures.put(CraftNamespacedKey.fromMinecraft(entry.getKey()), new CraftStructure(definedStructure)));
cachedStructures.put(CraftNamespacedKey.fromMinecraft(entry.getKey()), new CraftStructure(definedStructure));
});
} }
return Collections.unmodifiableMap(cachedStructures); return Collections.unmodifiableMap(cachedStructures);
} }
@Override @Override
public Structure getStructure(NamespacedKey structureKey) { public Structure getStructure(NamespacedKey structureKey) {
Validate.notNull(structureKey, "structureKey cannot be null"); Preconditions.checkArgument(structureKey != null, "NamespacedKey structureKey cannot be null");
final Optional<DefinedStructure> definedStructure = structureManager.structureRepository.get(CraftNamespacedKey.toMinecraft(structureKey)); final Optional<DefinedStructure> definedStructure = structureManager.structureRepository.get(CraftNamespacedKey.toMinecraft(structureKey));
if (definedStructure == null) { if (definedStructure == null) {
@ -83,7 +81,8 @@ public class CraftStructureManager implements StructureManager {
@Override @Override
public void saveStructure(NamespacedKey structureKey, Structure structure) throws IOException { 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); File structureFile = getStructureFile(structureKey);
Files.createDirectories(structureFile.toPath().getParent()); Files.createDirectories(structureFile.toPath().getParent());
@ -92,7 +91,8 @@ public class CraftStructureManager implements StructureManager {
@Override @Override
public Structure registerStructure(NamespacedKey structureKey, Structure structure) { 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); MinecraftKey minecraftKey = createAndValidateMinecraftStructureKey(structureKey);
final Optional<DefinedStructure> optionalDefinedStructure = Optional.of(((CraftStructure) structure).getHandle()); final Optional<DefinedStructure> optionalDefinedStructure = Optional.of(((CraftStructure) structure).getHandle());
@ -102,6 +102,7 @@ public class CraftStructureManager implements StructureManager {
@Override @Override
public Structure unregisterStructure(NamespacedKey structureKey) { public Structure unregisterStructure(NamespacedKey structureKey) {
Preconditions.checkArgument(structureKey != null, "NamespacedKey structureKey cannot be null");
MinecraftKey minecraftKey = createAndValidateMinecraftStructureKey(structureKey); MinecraftKey minecraftKey = createAndValidateMinecraftStructureKey(structureKey);
final Optional<DefinedStructure> previousStructure = structureManager.structureRepository.remove(minecraftKey); final Optional<DefinedStructure> previousStructure = structureManager.structureRepository.remove(minecraftKey);
@ -132,7 +133,7 @@ public class CraftStructureManager implements StructureManager {
@Override @Override
public Structure loadStructure(File file) throws IOException { 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); FileInputStream fileinputstream = new FileInputStream(file);
return loadStructure(fileinputstream); return loadStructure(fileinputstream);
@ -140,15 +141,15 @@ public class CraftStructureManager implements StructureManager {
@Override @Override
public Structure loadStructure(InputStream inputStream) throws IOException { 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)); return new CraftStructure(structureManager.readStructure(inputStream));
} }
@Override @Override
public void saveStructure(File file, Structure structure) throws IOException { public void saveStructure(File file, Structure structure) throws IOException {
Validate.notNull(file, "file cannot be null"); Preconditions.checkArgument(file != null, "file cannot be null");
Validate.notNull(structure, "structure cannot be null"); Preconditions.checkArgument(structure != null, "structure cannot be null");
FileOutputStream fileoutputstream = new FileOutputStream(file); FileOutputStream fileoutputstream = new FileOutputStream(file);
saveStructure(fileoutputstream, structure); saveStructure(fileoutputstream, structure);
@ -156,8 +157,8 @@ public class CraftStructureManager implements StructureManager {
@Override @Override
public void saveStructure(OutputStream outputStream, Structure structure) throws IOException { public void saveStructure(OutputStream outputStream, Structure structure) throws IOException {
Validate.notNull(outputStream, "outputStream cannot be null"); Preconditions.checkArgument(outputStream != null, "outputStream cannot be null");
Validate.notNull(structure, "structure cannot be null"); Preconditions.checkArgument(structure != null, "structure cannot be null");
NBTTagCompound nbttagcompound = ((CraftStructure) structure).getHandle().save(new NBTTagCompound()); NBTTagCompound nbttagcompound = ((CraftStructure) structure).getHandle().save(new NBTTagCompound());
NBTCompressedStreamTools.writeCompressed(nbttagcompound, outputStream); NBTCompressedStreamTools.writeCompressed(nbttagcompound, outputStream);
@ -169,17 +170,16 @@ public class CraftStructureManager implements StructureManager {
} }
private MinecraftKey createAndValidateMinecraftStructureKey(NamespacedKey structureKey) { 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); MinecraftKey minecraftkey = CraftNamespacedKey.toMinecraft(structureKey);
if (minecraftkey.getPath().contains("//")) { Preconditions.checkArgument(!minecraftkey.getPath().contains("//"), "Resource key for Structures can not contain \"//\"");
throw new IllegalArgumentException("Resource key for Structures can not contain \"//\"");
}
return minecraftkey; return minecraftkey;
} }
@Override @Override
public Structure copy(Structure structure) { public Structure copy(Structure structure) {
Preconditions.checkArgument(structure != null, "Structure cannot be null");
return new CraftStructure(structureManager.readStructure(((CraftStructure) structure).getHandle().save(new NBTTagCompound()))); return new CraftStructure(structureManager.readStructure(((CraftStructure) structure).getHandle().save(new NBTTagCompound())));
} }
} }

Datei anzeigen

@ -268,9 +268,7 @@ public final class CraftMagicNumbers implements UnsafeValues {
@Override @Override
public Advancement loadAdvancement(NamespacedKey key, String advancement) { public Advancement loadAdvancement(NamespacedKey key, String advancement) {
if (Bukkit.getAdvancement(key) != null) { Preconditions.checkArgument(Bukkit.getAdvancement(key) == null, "Advancement %s already exists", key);
throw new IllegalArgumentException("Advancement " + key + " already exists.");
}
MinecraftKey minecraftkey = CraftNamespacedKey.toMinecraft(key); MinecraftKey minecraftkey = CraftNamespacedKey.toMinecraft(key);
JsonElement jsonelement = AdvancementDataWorld.GSON.fromJson(advancement, JsonElement.class); JsonElement jsonelement = AdvancementDataWorld.GSON.fromJson(advancement, JsonElement.class);

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.util; package org.bukkit.craftbukkit.util;
import com.google.common.base.Preconditions;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
@ -16,9 +17,7 @@ public class LazyPlayerSet extends LazyHashSet<Player> {
@Override @Override
HashSet<Player> makeReference() { HashSet<Player> makeReference() {
if (reference != null) { Preconditions.checkState(reference == null, "Reference already created!");
throw new IllegalStateException("Reference already created!");
}
List<EntityPlayer> players = server.getPlayerList().players; List<EntityPlayer> players = server.getPlayerList().players;
HashSet<Player> reference = new HashSet<Player>(players.size()); HashSet<Player> reference = new HashSet<Player>(players.size());
for (EntityPlayer player : players) { for (EntityPlayer player : players) {

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.util; package org.bukkit.craftbukkit.util;
import com.google.common.base.Preconditions;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
@ -273,9 +274,7 @@ public class UnsafeList<E> extends AbstractList<E> implements List<E>, RandomAcc
@Override @Override
public void remove() { public void remove() {
if (lastRet < 0) { Preconditions.checkState(lastRet >= 0, "");
throw new IllegalStateException();
}
if (modCount != expectedModCount) { if (modCount != expectedModCount) {
throw new ConcurrentModificationException(); throw new ConcurrentModificationException();

Datei anzeigen

@ -1,5 +1,6 @@
package org.bukkit.craftbukkit.util; package org.bukkit.craftbukkit.util;
import com.google.common.base.Preconditions;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
public abstract class Waitable<T> implements Runnable { public abstract class Waitable<T> implements Runnable {
@ -15,9 +16,7 @@ public abstract class Waitable<T> implements Runnable {
@Override @Override
public final void run() { public final void run() {
synchronized (this) { synchronized (this) {
if (status != Status.WAITING) { Preconditions.checkState(status == Status.WAITING, "Invalid state %s", status);
throw new IllegalStateException("Invalid state " + status);
}
status = Status.RUNNING; status = Status.RUNNING;
} }
try { try {

Datei anzeigen

@ -1,23 +1,23 @@
package org.bukkit.craftbukkit.util; package org.bukkit.craftbukkit.util;
import com.google.common.base.Preconditions;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import org.apache.commons.lang.Validate;
public final class WeakCollection<T> implements Collection<T> { public final class WeakCollection<T> implements Collection<T> {
static final Object NO_VALUE = new Object(); static final Object NO_VALUE = new Object();
private final Collection<WeakReference<T>> collection; private final Collection<WeakReference<T>> collection;
public WeakCollection() { public WeakCollection() {
collection = new ArrayList<WeakReference<T>>(); collection = new ArrayList<>();
} }
@Override @Override
public boolean add(T value) { 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<T>(value)); return collection.add(new WeakReference<T>(value));
} }
@ -26,7 +26,7 @@ public final class WeakCollection<T> implements Collection<T> {
Collection<WeakReference<T>> values = this.collection; Collection<WeakReference<T>> values = this.collection;
boolean ret = false; boolean ret = false;
for (T value : collection) { for (T value : collection) {
Validate.notNull(value, "Cannot add null value"); Preconditions.checkArgument(value != null, "Cannot add null value");
ret |= values.add(new WeakReference<T>(value)); ret |= values.add(new WeakReference<T>(value));
} }
return ret; return ret;
@ -103,9 +103,7 @@ public final class WeakCollection<T> implements Collection<T> {
@Override @Override
public void remove() throws IllegalStateException { public void remove() throws IllegalStateException {
if (value != NO_VALUE) { Preconditions.checkState(value == NO_VALUE, "No last element");
throw new IllegalStateException("No last element");
}
value = null; value = null;
it.remove(); it.remove();