From afe660b57f2730c11e5e6eec0a5c9506c0a09c84 Mon Sep 17 00:00:00 2001 From: Major- Date: Mon, 15 Sep 2014 18:36:46 +0100 Subject: [PATCH] Use Guava's Preconditions where possible. --- src/org/apollo/fs/Index.java | 6 +- src/org/apollo/fs/IndexedFileSystem.java | 57 ++++++++----------- .../apollo/game/message/impl/WalkMessage.java | 6 +- src/org/apollo/game/model/Appearance.java | 13 +++-- src/org/apollo/game/model/Item.java | 5 +- src/org/apollo/game/model/Position.java | 5 +- .../game/model/def/EquipmentDefinition.java | 11 ++-- .../apollo/game/model/def/ItemDefinition.java | 21 ++----- .../apollo/game/model/def/NpcDefinition.java | 18 ++---- .../game/model/def/ObjectDefinition.java | 6 +- src/org/apollo/game/model/entity/Player.java | 5 +- src/org/apollo/game/model/inv/Inventory.java | 14 ++--- .../game/model/setting/PrivacyState.java | 7 +-- .../game/model/setting/PrivilegeLevel.java | 6 +- .../game/model/setting/ScreenBrightness.java | 6 +- .../game/model/setting/ServerStatus.java | 6 +- .../apollo/game/scheduling/ScheduledTask.java | 8 +-- .../apollo/game/sync/seg/MovementSegment.java | 6 +- .../io/player/PlayerLoaderResponse.java | 32 ++++++----- src/org/apollo/net/ApolloHandler.java | 11 ++-- .../net/codec/game/GamePacketDecoder.java | 6 +- .../net/codec/game/GamePacketEncoder.java | 2 +- .../net/codec/game/GamePacketReader.java | 45 ++++++--------- src/org/apollo/net/meta/PacketMetaData.java | 30 +++++----- .../apollo/net/meta/PacketMetaDataGroup.java | 44 +++++++------- src/org/apollo/net/release/Release.java | 12 ++-- src/org/apollo/net/session/LoginSession.java | 25 ++++---- src/org/apollo/tools/EquipmentUpdater.java | 10 ++-- src/org/apollo/tools/NoteUpdater.java | 6 +- src/org/apollo/util/MobRepository.java | 13 ++--- src/org/apollo/util/NameUtil.java | 24 ++++---- src/org/apollo/util/StatefulFrameDecoder.java | 10 ++-- .../util/plugin/DependencyException.java | 4 +- src/org/apollo/util/xml/XmlParser.java | 6 +- 34 files changed, 224 insertions(+), 262 deletions(-) diff --git a/src/org/apollo/fs/Index.java b/src/org/apollo/fs/Index.java index 3716ef0b..c112c616 100644 --- a/src/org/apollo/fs/Index.java +++ b/src/org/apollo/fs/Index.java @@ -1,5 +1,7 @@ package org.apollo.fs; +import com.google.common.base.Preconditions; + /** * An {@link Index} points to a file in the {@code main_file_cache.dat} file. * @@ -15,9 +17,7 @@ public final class Index { * @throws IllegalArgumentException If the buffer length is invalid. */ public static Index decode(byte[] buffer) { - if (buffer.length != FileSystemConstants.INDEX_SIZE) { - throw new IllegalArgumentException("Incorrect buffer length."); - } + Preconditions.checkArgument(buffer.length == FileSystemConstants.INDEX_SIZE, "Incorrect buffer length."); int size = (buffer[0] & 0xFF) << 16 | (buffer[1] & 0xFF) << 8 | buffer[2] & 0xFF; int block = (buffer[3] & 0xFF) << 16 | (buffer[4] & 0xFF) << 8 | buffer[5] & 0xFF; diff --git a/src/org/apollo/fs/IndexedFileSystem.java b/src/org/apollo/fs/IndexedFileSystem.java index cb107ebc..40b3bef1 100644 --- a/src/org/apollo/fs/IndexedFileSystem.java +++ b/src/org/apollo/fs/IndexedFileSystem.java @@ -9,6 +9,8 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.zip.CRC32; +import com.google.common.base.Preconditions; + /** * A file system based on top of the operating system's file system. It consists of a data file and index files. Index * files point to blocks in the data file, which contains the actual data. @@ -97,7 +99,8 @@ public final class IndexedFileSystem implements Closeable { * Gets the CRC table. * * @return The CRC table. - * @throws IOException If an I/O error occurs. + * @throws IOException If there is an error accessing files to create the table. + * @throws IllegalStateException If this file system is not read-only. */ public ByteBuffer getCrcTable() throws IOException { if (readOnly) { @@ -111,7 +114,6 @@ public final class IndexedFileSystem implements Closeable { int hash = 1234; int[] crcs = new int[archives]; - // calculate the CRCs CRC32 crc32 = new CRC32(); for (int i = 1; i < crcs.length; i++) { crc32.reset(); @@ -124,8 +126,7 @@ public final class IndexedFileSystem implements Closeable { crcs[i] = (int) crc32.getValue(); } - // hash the CRCs and place them in the buffer - ByteBuffer buffer = ByteBuffer.allocate(crcs.length * 4 + 4); + ByteBuffer buffer = ByteBuffer.allocate((crcs.length + 1) * Integer.BYTES); for (int crc : crcs) { hash = (hash << 1) + crc; buffer.putInt(crc); @@ -139,22 +140,21 @@ public final class IndexedFileSystem implements Closeable { return crcTable.duplicate(); } } - throw new IOException("Cannot get CRC table from a writable file system."); + throw new IllegalStateException("Cannot get CRC table from a writable file system."); } /** * Gets a file. * - * @param descriptor The {@link FileDescriptor} which points to the file. - * @return A {@link ByteBuffer} which contains the contents of the file. - * @throws IOException If an I/O error occurs. + * @param descriptor The {@link FileDescriptor} pointing to the file. + * @return A {@link ByteBuffer} containing the contents of the file. + * @throws IOException If there is an error decoding the file. */ public ByteBuffer getFile(FileDescriptor descriptor) throws IOException { Index index = getIndex(descriptor); ByteBuffer buffer = ByteBuffer.allocate(index.getSize()); - // calculate some initial values - long ptr = index.getBlock() * FileSystemConstants.BLOCK_SIZE; + long position = index.getBlock() * FileSystemConstants.BLOCK_SIZE; int read = 0; int size = index.getSize(); int blocks = size / FileSystemConstants.CHUNK_SIZE; @@ -163,44 +163,37 @@ public final class IndexedFileSystem implements Closeable { } for (int i = 0; i < blocks; i++) { - // read header byte[] header = new byte[FileSystemConstants.HEADER_SIZE]; synchronized (data) { - data.seek(ptr); + data.seek(position); data.readFully(header); } - // increment pointers - ptr += FileSystemConstants.HEADER_SIZE; + position += FileSystemConstants.HEADER_SIZE; - // parse header int nextFile = (header[0] & 0xFF) << 8 | header[1] & 0xFF; int curChunk = (header[2] & 0xFF) << 8 | header[3] & 0xFF; int nextBlock = (header[4] & 0xFF) << 16 | (header[5] & 0xFF) << 8 | header[6] & 0xFF; int nextType = header[7] & 0xFF; - // check expected chunk id is correct if (i != curChunk) { throw new IOException("Chunk id mismatch."); } - // calculate how much we can read int chunkSize = size - read; if (chunkSize > FileSystemConstants.CHUNK_SIZE) { chunkSize = FileSystemConstants.CHUNK_SIZE; } - // read the next chunk and put it in the buffer byte[] chunk = new byte[chunkSize]; synchronized (data) { - data.seek(ptr); + data.seek(position); data.readFully(chunk); } buffer.put(chunk); - // increment pointers read += chunkSize; - ptr = (long) nextBlock * (long) FileSystemConstants.BLOCK_SIZE; + position = (long) nextBlock * (long) FileSystemConstants.BLOCK_SIZE; // if we still have more data to read, check the validity of the header if (size > read) { @@ -235,12 +228,12 @@ public final class IndexedFileSystem implements Closeable { * * @param type The type. * @return The number of files. - * @throws IOException If an I/O error occurs. + * @throws IOException If there is an error getting the length of the specified index file. + * @throws IndexOutOfBoundsException If {@code type} is less than 0, or greater than or equal to the amount of + * indices. */ private int getFileCount(int type) throws IOException { - if (type < 0 || type >= indices.length) { - throw new IndexOutOfBoundsException("File type out of bounds."); - } + Preconditions.checkElementIndex(type, indices.length, "File type out of bounds."); RandomAccessFile indexFile = indices[type]; synchronized (indexFile) { @@ -253,20 +246,20 @@ public final class IndexedFileSystem implements Closeable { * * @param descriptor The {@link FileDescriptor} which points to the file. * @return The {@link Index}. - * @throws IOException If an I/O error occurs. + * @throws IOException If there is an error reading from the index file. + * @throws IndexOutOfBoundsException If the descriptor type is less than 0, or greater than or equal to the amount + * of indices. */ private Index getIndex(FileDescriptor descriptor) throws IOException { int index = descriptor.getType(); - if (index < 0 || index >= indices.length) { - throw new IndexOutOfBoundsException("File descriptor type out of bounds."); - } + Preconditions.checkElementIndex(index, indices.length, "File descriptor type out of bounds."); byte[] buffer = new byte[FileSystemConstants.INDEX_SIZE]; RandomAccessFile indexFile = indices[index]; synchronized (indexFile) { - long ptr = descriptor.getFile() * FileSystemConstants.INDEX_SIZE; - if (ptr >= 0 && indexFile.length() >= ptr + FileSystemConstants.INDEX_SIZE) { - indexFile.seek(ptr); + long position = descriptor.getFile() * FileSystemConstants.INDEX_SIZE; + if (position >= 0 && indexFile.length() >= position + FileSystemConstants.INDEX_SIZE) { + indexFile.seek(position); indexFile.readFully(buffer); } else { throw new FileNotFoundException("Could not find find index."); diff --git a/src/org/apollo/game/message/impl/WalkMessage.java b/src/org/apollo/game/message/impl/WalkMessage.java index faf6cd76..fde16843 100644 --- a/src/org/apollo/game/message/impl/WalkMessage.java +++ b/src/org/apollo/game/message/impl/WalkMessage.java @@ -3,6 +3,8 @@ package org.apollo.game.message.impl; import org.apollo.game.message.Message; import org.apollo.game.model.Position; +import com.google.common.base.Preconditions; + /** * A {@link Message} sent by the client to request that the player walks somewhere. * @@ -27,9 +29,7 @@ public final class WalkMessage extends Message { * @param run The run flag. */ public WalkMessage(Position[] steps, boolean run) { - if (steps.length < 0) { - throw new IllegalArgumentException("Number of steps must not be negative."); - } + Preconditions.checkArgument(steps.length >= 0, "Number of steps cannot be negative."); this.steps = steps; this.run = run; } diff --git a/src/org/apollo/game/model/Appearance.java b/src/org/apollo/game/model/Appearance.java index 4cb3c9ad..9a15b0ec 100644 --- a/src/org/apollo/game/model/Appearance.java +++ b/src/org/apollo/game/model/Appearance.java @@ -2,6 +2,8 @@ package org.apollo.game.model; import org.apollo.game.model.setting.Gender; +import com.google.common.base.Preconditions; + /** * Represents the appearance of a player. * @@ -12,8 +14,8 @@ public final class Appearance { /** * The default appearance. */ - public static final Appearance DEFAULT_APPEARANCE = new Appearance(Gender.MALE, new int[] { 0, 10, 18, 26, 33, 36, - 42 }, new int[5]); + public static final Appearance DEFAULT_APPEARANCE = new Appearance(Gender.MALE, new int[] { 0, 10, 18, 26, 33, 36, 42 }, + new int[5]); /** * The array of clothing/skin colors. @@ -40,11 +42,10 @@ public final class Appearance { public Appearance(Gender gender, int[] style, int[] colors) { if (gender == null || style == null || colors == null) { throw new NullPointerException("No arguments can be null."); - } else if (style.length != 7) { - throw new IllegalArgumentException("The style array must have 7 elements."); - } else if (colors.length != 5) { - throw new IllegalArgumentException("The colors array must have 5 elements."); } + Preconditions.checkArgument(style.length == 7, "Style array must have 7 exactly elements."); + Preconditions.checkArgument(colors.length == 5, "Colors array must have exactly 5 elements."); + this.gender = gender; this.style = style; this.colors = colors; diff --git a/src/org/apollo/game/model/Item.java b/src/org/apollo/game/model/Item.java index c1526d15..221ab368 100644 --- a/src/org/apollo/game/model/Item.java +++ b/src/org/apollo/game/model/Item.java @@ -3,6 +3,7 @@ package org.apollo.game.model; import org.apollo.game.model.def.ItemDefinition; import com.google.common.base.MoreObjects; +import com.google.common.base.Preconditions; /** * Represents a single item. @@ -43,9 +44,7 @@ public final class Item { * @throws IllegalArgumentException If the amount is negative. */ public Item(int id, int amount) { - if (amount < 0) { - throw new IllegalArgumentException("Negative amount."); - } + Preconditions.checkArgument(amount >= 0, "Amount cannot be negative."); this.id = id; this.amount = amount; this.definition = ItemDefinition.lookup(id); diff --git a/src/org/apollo/game/model/Position.java b/src/org/apollo/game/model/Position.java index 60824ac1..747143fc 100644 --- a/src/org/apollo/game/model/Position.java +++ b/src/org/apollo/game/model/Position.java @@ -1,6 +1,7 @@ package org.apollo.game.model; import com.google.common.base.MoreObjects; +import com.google.common.base.Preconditions; /** * Represents a position in the world. @@ -52,9 +53,7 @@ public final class Position { * @param height The height. */ public Position(int x, int y, int height) { - if (height < 0 || height >= HEIGHT_LEVELS) { - throw new IllegalArgumentException("Height level out of bounds."); - } + Preconditions.checkArgument(height >= 0 && height < HEIGHT_LEVELS, "Height level out of bounds."); this.x = x; this.y = y; this.height = height; diff --git a/src/org/apollo/game/model/def/EquipmentDefinition.java b/src/org/apollo/game/model/def/EquipmentDefinition.java index 92e08966..3e0246a7 100644 --- a/src/org/apollo/game/model/def/EquipmentDefinition.java +++ b/src/org/apollo/game/model/def/EquipmentDefinition.java @@ -6,6 +6,8 @@ import java.util.Map; import org.apollo.game.model.Item; import org.apollo.game.model.entity.Skill; +import com.google.common.base.Preconditions; + /** * Represents a type of {@link Item} which may be equipped. * @@ -44,10 +46,7 @@ public final class EquipmentDefinition { * @throws IndexOutOfBoundsException If the id is out of bounds. */ public static EquipmentDefinition lookup(int id) { - if (id < 0 || id >= ItemDefinition.count()) { - throw new IndexOutOfBoundsException(EquipmentDefinition.class.getName() + " lookup index " + id - + " out of bounds."); - } + Preconditions.checkElementIndex(id, ItemDefinition.count(), "Id out of bounds."); return definitions.get(id); } @@ -132,9 +131,7 @@ public final class EquipmentDefinition { * @return The level. */ public int getLevel(int skill) { - if (skill < Skill.ATTACK || skill > Skill.MAGIC) { - throw new IllegalArgumentException("Skill id out of bounds."); - } + Preconditions.checkArgument(skill >= Skill.ATTACK && skill <= Skill.MAGIC, "Skill id out of bounds."); return levels[skill]; } diff --git a/src/org/apollo/game/model/def/ItemDefinition.java b/src/org/apollo/game/model/def/ItemDefinition.java index c0254477..7e175a25 100644 --- a/src/org/apollo/game/model/def/ItemDefinition.java +++ b/src/org/apollo/game/model/def/ItemDefinition.java @@ -2,6 +2,7 @@ package org.apollo.game.model.def; import org.apollo.game.model.Item; +import com.google.common.base.Preconditions; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; @@ -87,9 +88,7 @@ public final class ItemDefinition { * @throws IndexOutOfBoundsException If the id is out of bounds. */ public static ItemDefinition lookup(int id) { - if (id < 0 || id >= definitions.length) { - throw new IndexOutOfBoundsException(ItemDefinition.class.getName() + " lookup index " + id + " out of bounds."); - } + Preconditions.checkElementIndex(id, definitions.length, "Id out of bounds."); return definitions[id]; } @@ -188,9 +187,7 @@ public final class ItemDefinition { * @throws IndexOutOfBoundsException If the id is out of bounds. */ public String getGroundAction(int id) { - if (id < 0 || id >= groundActions.length) { - throw new IndexOutOfBoundsException("Ground action id is out of bounds."); - } + Preconditions.checkElementIndex(id, groundActions.length, "Ground action id is out of bounds."); return groundActions[id]; } @@ -211,9 +208,7 @@ public final class ItemDefinition { * @throws IndexOutOfBoundsException If the id is out of bounds. */ public String getInventoryAction(int id) { - if (id < 0 || id >= inventoryActions.length) { - throw new IndexOutOfBoundsException("Inventory action id is out of bounds."); - } + Preconditions.checkElementIndex(id, inventoryActions.length, "Inventory action id is out of bounds."); return inventoryActions[id]; } @@ -306,9 +301,7 @@ public final class ItemDefinition { * @throws IndexOutOfBoundsException If the id is out of bounds. */ public void setGroundAction(int id, String action) { - if (id < 0 || id >= groundActions.length) { - throw new IndexOutOfBoundsException("Ground action id is out of bounds."); - } + Preconditions.checkElementIndex(id, groundActions.length, "Ground action id is out of bounds."); groundActions[id] = action; } @@ -320,9 +313,7 @@ public final class ItemDefinition { * @throws IndexOutOfBoundsException If the id is out of bounds. */ public void setInventoryAction(int id, String action) { - if (id < 0 || id >= inventoryActions.length) { - throw new IndexOutOfBoundsException("Inventory action id is out of bounds."); - } + Preconditions.checkElementIndex(id, inventoryActions.length, "Inventory action id is out of bounds."); inventoryActions[id] = action; } diff --git a/src/org/apollo/game/model/def/NpcDefinition.java b/src/org/apollo/game/model/def/NpcDefinition.java index 6cdc4f07..3ddd77b4 100644 --- a/src/org/apollo/game/model/def/NpcDefinition.java +++ b/src/org/apollo/game/model/def/NpcDefinition.java @@ -2,6 +2,8 @@ package org.apollo.game.model.def; import org.apollo.game.model.entity.Npc; +import com.google.common.base.Preconditions; + /** * Represents a type of {@link Npc}. * @@ -56,9 +58,7 @@ public final class NpcDefinition { * @throws IndexOutOfBoundsException If the id is out of bounds. */ public static NpcDefinition lookup(int id) { - if (id < 0 || id >= definitions.length) { - throw new IndexOutOfBoundsException(NpcDefinition.class.getName() + " lookup index " + id + " out of bounds."); - } + Preconditions.checkElementIndex(id, definitions.length, "Id out of bounds."); return definitions[id]; } @@ -141,9 +141,7 @@ public final class NpcDefinition { * @throws IndexOutOfBoundsException If the slot is out of bounds. */ public String getInteraction(int slot) { - if (slot < 0 || slot >= interactions.length) { - throw new IndexOutOfBoundsException("Npc interaction id is out of bounds."); - } + Preconditions.checkElementIndex(slot, interactions.length, "Npc interaction id is out of bounds."); return interactions[slot]; } @@ -236,9 +234,7 @@ public final class NpcDefinition { * @throws IndexOutOfBoundsException If the slot is out of bounds. */ public boolean hasInteraction(int slot) { - if (slot < 0 || slot >= interactions.length) { - throw new IndexOutOfBoundsException("Npc interaction id is out of bounds."); - } + Preconditions.checkElementIndex(slot, interactions.length, "Npc interaction id is out of bounds."); return interactions[slot] != null; } @@ -313,9 +309,7 @@ public final class NpcDefinition { * @throws IndexOutOfBoundsException If the slot is out of bounds. */ public void setInteraction(int slot, String interaction) { - if (slot < 0 || slot >= interactions.length) { - throw new IndexOutOfBoundsException("Npc interaction id is out of bounds."); - } + Preconditions.checkElementIndex(slot, interactions.length, "Npc interaction id is out of bounds."); interactions[slot] = interaction; } diff --git a/src/org/apollo/game/model/def/ObjectDefinition.java b/src/org/apollo/game/model/def/ObjectDefinition.java index 4821453b..98e1aa02 100644 --- a/src/org/apollo/game/model/def/ObjectDefinition.java +++ b/src/org/apollo/game/model/def/ObjectDefinition.java @@ -2,6 +2,8 @@ package org.apollo.game.model.def; import org.apollo.game.model.entity.GameObject; +import com.google.common.base.Preconditions; + /** * Represents a type of {@link GameObject}. * @@ -56,9 +58,7 @@ public final class ObjectDefinition { * @throws IndexOutOfBoundsException If the id is out of bounds. */ public static ObjectDefinition lookup(int id) { - if (id < 0 || id > definitions.length) { - throw new IndexOutOfBoundsException(ObjectDefinition.class.getName() + " lookup index " + id + " out of bounds."); - } + Preconditions.checkElementIndex(id, definitions.length, "Id out of bounds."); return definitions[id]; } diff --git a/src/org/apollo/game/model/entity/Player.java b/src/org/apollo/game/model/entity/Player.java index 8078eafa..a479221c 100644 --- a/src/org/apollo/game/model/entity/Player.java +++ b/src/org/apollo/game/model/entity/Player.java @@ -41,6 +41,7 @@ import org.apollo.security.PlayerCredentials; import org.apollo.util.Point; import com.google.common.base.MoreObjects; +import com.google.common.base.Preconditions; /** * A {@link Player} is a {@link Mob} that a user is controlling. @@ -687,9 +688,7 @@ public final class Player extends Mob { */ public void sendQuestInterface(List text) { int size = text.size(), lines = InterfaceConstants.QUEST_TEXT.length; - if (size > lines) { - throw new IllegalArgumentException("List contains too much text to display on this interface."); - } + Preconditions.checkArgument(size <= lines, "List contains too much text to display on this interface."); for (int pos = 0; pos < lines; pos++) { send(new SetWidgetTextMessage(InterfaceConstants.QUEST_TEXT[pos], pos < size ? text.get(pos) : "")); diff --git a/src/org/apollo/game/model/inv/Inventory.java b/src/org/apollo/game/model/inv/Inventory.java index cb075f24..e487b177 100644 --- a/src/org/apollo/game/model/inv/Inventory.java +++ b/src/org/apollo/game/model/inv/Inventory.java @@ -6,6 +6,8 @@ import java.util.List; import org.apollo.game.model.Item; import org.apollo.game.model.def.ItemDefinition; +import com.google.common.base.Preconditions; + /** * Represents an inventory - a collection of {@link Item}s. * @@ -87,11 +89,9 @@ public final class Inventory implements Cloneable { * @throws NullPointerException If the mode is {@code null}. */ public Inventory(int capacity, StackMode mode) { - if (capacity < 0) { - throw new IllegalArgumentException("Capacity cannot be negative."); - } else if (mode == null) { - throw new NullPointerException("Stacking mode cannot be null."); - } + Preconditions.checkArgument(capacity >= 0, "Capacity cannot be negative."); + Preconditions.checkNotNull(mode, "Stacking mode cannot be null."); + items = new Item[this.capacity = capacity]; this.mode = mode; } @@ -212,9 +212,7 @@ public final class Inventory implements Cloneable { * @throws IndexOutOfBoundsException If the slot is out of bounds. */ private void checkBounds(int slot) { - if (slot < 0 || slot >= capacity) { - throw new IndexOutOfBoundsException("Slot out of bounds."); - } + Preconditions.checkElementIndex(slot, capacity, "Slot out of bounds."); } /** diff --git a/src/org/apollo/game/model/setting/PrivacyState.java b/src/org/apollo/game/model/setting/PrivacyState.java index e706f872..0a62b1fc 100644 --- a/src/org/apollo/game/model/setting/PrivacyState.java +++ b/src/org/apollo/game/model/setting/PrivacyState.java @@ -1,5 +1,7 @@ package org.apollo.game.model.setting; +import com.google.common.base.Preconditions; + /** * An enumeration representing the different privacy states for public, private and trade chat. This enumeration relies * on the ordering of the elements within, which should be as follows: {@code ON}, {@code HIDE}, {@code FRIENDS}, @@ -49,10 +51,7 @@ public enum PrivacyState { if (!chat && value != 0) { value++; } - if (value < 0 || value >= values.length) { - throw new IllegalArgumentException("Invalid privacy option integer value specified: " + value + "."); - } - + Preconditions.checkElementIndex(value, values.length, "Invalid privacy option integer value specified: " + value + "."); return values[value]; } diff --git a/src/org/apollo/game/model/setting/PrivilegeLevel.java b/src/org/apollo/game/model/setting/PrivilegeLevel.java index b03a9d0c..e5738f7c 100644 --- a/src/org/apollo/game/model/setting/PrivilegeLevel.java +++ b/src/org/apollo/game/model/setting/PrivilegeLevel.java @@ -1,5 +1,7 @@ package org.apollo.game.model.setting; +import com.google.common.base.Preconditions; + /** * An enumeration with the different privilege levels a player can have. This enumeration relies on the ordering of the * elements within, which should be as follows: {@code STANDARD}, {@code MODERATOR}, {@code ADMINISTRATOR}. @@ -32,9 +34,7 @@ public enum PrivilegeLevel { */ public static PrivilegeLevel valueOf(int value) { PrivilegeLevel[] values = values(); - if (value < 0 || value >= values.length) { - throw new IndexOutOfBoundsException("Invalid privilege level integer value supplied " + value + "."); - } + Preconditions.checkElementIndex(value, values.length, "Invalid privilege level integer value supplied " + value + "."); return values[value]; } diff --git a/src/org/apollo/game/model/setting/ScreenBrightness.java b/src/org/apollo/game/model/setting/ScreenBrightness.java index 6918bd02..9ae6cd9c 100644 --- a/src/org/apollo/game/model/setting/ScreenBrightness.java +++ b/src/org/apollo/game/model/setting/ScreenBrightness.java @@ -1,5 +1,7 @@ package org.apollo.game.model.setting; +import com.google.common.base.Preconditions; + /** * An enumeration representing the brightness of a player's screen. This enumeration relies on the ordering of the * elements within, which should be as follows: {@code DARK}, {@code NORMAL}, {@code BRIGHT}, {@code VERY_BRIGHT}. @@ -37,9 +39,7 @@ public enum ScreenBrightness { */ public static ScreenBrightness valueOf(int value) { ScreenBrightness[] values = values(); - if (value < 0 || value >= values.length) { - throw new IllegalArgumentException("Invalid screen brightness integer value specified " + value + "."); - } + Preconditions.checkElementIndex(value, values.length, "Invalid screen brightness integer value specified " + value + "."); return values[value]; } diff --git a/src/org/apollo/game/model/setting/ServerStatus.java b/src/org/apollo/game/model/setting/ServerStatus.java index c2761fe6..05bc3d8e 100644 --- a/src/org/apollo/game/model/setting/ServerStatus.java +++ b/src/org/apollo/game/model/setting/ServerStatus.java @@ -1,5 +1,7 @@ package org.apollo.game.model.setting; +import com.google.common.base.Preconditions; + /** * Represents the status of the friend server. This enumeration relies on the ordering of the elements within, which * should be as follows: {@code OFFLINE}, {@code CONNECTING}, {@code ONLINE}. @@ -41,9 +43,7 @@ public enum ServerStatus { */ public static ServerStatus valueOf(int value) { ServerStatus[] values = values(); - if (value < 0 || value >= values.length) { - throw new IndexOutOfBoundsException("Invalid server status integer value supplied " + value + "."); - } + Preconditions.checkElementIndex(value, values.length, "Invalid server status integer value supplied " + value + "."); return values[value]; } diff --git a/src/org/apollo/game/scheduling/ScheduledTask.java b/src/org/apollo/game/scheduling/ScheduledTask.java index 1791684b..32ec6421 100644 --- a/src/org/apollo/game/scheduling/ScheduledTask.java +++ b/src/org/apollo/game/scheduling/ScheduledTask.java @@ -1,5 +1,7 @@ package org.apollo.game.scheduling; +import com.google.common.base.Preconditions; + /** * A game-related task that is scheduled to run in the future. * @@ -63,12 +65,10 @@ public abstract class ScheduledTask { * Sets the delay. * * @param delay The delay. - * @throws IllegalArgumentException If the delay is less than or equal to zero. + * @throws IllegalArgumentException If the delay is less than zero. */ public final void setDelay(int delay) { - if (delay < 0) { - throw new IllegalArgumentException("Delay cannot be less than 0."); - } + Preconditions.checkArgument(delay >= 0, "Delay cannot be less than 0."); this.delay = delay; } diff --git a/src/org/apollo/game/sync/seg/MovementSegment.java b/src/org/apollo/game/sync/seg/MovementSegment.java index 50e60e7f..2ee71ba8 100644 --- a/src/org/apollo/game/sync/seg/MovementSegment.java +++ b/src/org/apollo/game/sync/seg/MovementSegment.java @@ -3,6 +3,8 @@ package org.apollo.game.sync.seg; import org.apollo.game.model.Direction; import org.apollo.game.sync.block.SynchronizationBlockSet; +import com.google.common.base.Preconditions; + /** * A {@link SynchronizationSegment} where a mob is moved (or doesn't move!). * @@ -24,9 +26,7 @@ public final class MovementSegment extends SynchronizationSegment { */ public MovementSegment(SynchronizationBlockSet blockSet, Direction[] directions) { super(blockSet); - if (directions.length < 0 || directions.length > 2) { - throw new IllegalArgumentException("Directions length must be between 0 and 2 inclusive."); - } + Preconditions.checkArgument(directions.length >= 0 && directions.length < 3, "Directions length must be between 0 and 2 inclusive."); this.directions = directions; } diff --git a/src/org/apollo/io/player/PlayerLoaderResponse.java b/src/org/apollo/io/player/PlayerLoaderResponse.java index 77a8244c..47527d11 100644 --- a/src/org/apollo/io/player/PlayerLoaderResponse.java +++ b/src/org/apollo/io/player/PlayerLoaderResponse.java @@ -1,8 +1,12 @@ package org.apollo.io.player; +import java.util.Optional; + import org.apollo.game.model.entity.Player; import org.apollo.net.codec.login.LoginConstants; +import com.google.common.base.Preconditions; + /** * A response for the {@link PlayerLoader#loadPlayer(org.apollo.security.PlayerCredentials)} call. * @@ -13,7 +17,7 @@ public final class PlayerLoaderResponse { /** * The player. */ - private final Player player; + private final Optional player; /** * The status code. @@ -24,37 +28,37 @@ public final class PlayerLoaderResponse { * Creates a {@link PlayerLoaderResponse} with only a status code. * * @param status The status code. - * @throws IllegalArgumentException If the status code needs a {@link Player}. + * @throws IllegalArgumentException If the status code is {@link LoginConstants#STATUS_OK} or + * {@link LoginConstants#STATUS_RECONNECTION_OK}. */ public PlayerLoaderResponse(int status) { - if (status == LoginConstants.STATUS_OK || status == LoginConstants.STATUS_RECONNECTION_OK) { - throw new IllegalArgumentException("Player required for this status code."); - } + Preconditions.checkArgument(status != LoginConstants.STATUS_OK && status != LoginConstants.STATUS_RECONNECTION_OK, + "Player required for this status code."); this.status = status; - player = null; + player = Optional.empty(); } /** - * Creates a {@link PlayerLoaderResponse} with a status code and player. + * Creates a {@link PlayerLoaderResponse} with a status code and {@link Player}. * * @param status The status code. * @param player The player. - * @throws IllegalArgumentException If the status code does not need {@link Player}. + * @throws IllegalArgumentException If the status code does not need a player. + * @throws NullPointerException If the specified player is null. */ public PlayerLoaderResponse(int status, Player player) { - if (status != LoginConstants.STATUS_OK && status != LoginConstants.STATUS_RECONNECTION_OK) { - throw new IllegalArgumentException("Player not required for this status code."); - } + Preconditions.checkArgument(status == LoginConstants.STATUS_OK || status == LoginConstants.STATUS_RECONNECTION_OK, + "Player not required for this status code."); this.status = status; - this.player = player; + this.player = Optional.of(player); } /** * Gets the player. * - * @return The player, or {@code null} if there is no player in this response. + * @return The player, wrapped in an {@link Optional}. */ - public Player getPlayer() { + public Optional getPlayer() { return player; } diff --git a/src/org/apollo/net/ApolloHandler.java b/src/org/apollo/net/ApolloHandler.java index e6a88655..ad51eb83 100644 --- a/src/org/apollo/net/ApolloHandler.java +++ b/src/org/apollo/net/ApolloHandler.java @@ -64,12 +64,13 @@ public final class ApolloHandler extends ChannelInboundHandlerAdapter { } @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) { + public void channelRead(ChannelHandlerContext ctx, Object message) { if (ctx.attr(NetworkConstants.SESSION_KEY).get() == null) { - if (msg instanceof HttpRequest || msg instanceof JagGrabRequest) { - new UpdateSession(ctx.channel(), serverContext).messageReceived(msg); + if (message instanceof HttpRequest || message instanceof JagGrabRequest) { + new UpdateSession(ctx.channel(), serverContext).messageReceived(message); } else { - HandshakeMessage handshakeMessage = (HandshakeMessage) msg; + HandshakeMessage handshakeMessage = (HandshakeMessage) message; + switch (handshakeMessage.getServiceId()) { case HandshakeConstants.SERVICE_GAME: ctx.attr(NetworkConstants.SESSION_KEY).set(new LoginSession(ctx, serverContext)); @@ -82,7 +83,7 @@ public final class ApolloHandler extends ChannelInboundHandlerAdapter { } } } else { - ctx.attr(NetworkConstants.SESSION_KEY).get().messageReceived(msg); + ctx.attr(NetworkConstants.SESSION_KEY).get().messageReceived(message); } } diff --git a/src/org/apollo/net/codec/game/GamePacketDecoder.java b/src/org/apollo/net/codec/game/GamePacketDecoder.java index bfbded3f..5434ce1e 100644 --- a/src/org/apollo/net/codec/game/GamePacketDecoder.java +++ b/src/org/apollo/net/codec/game/GamePacketDecoder.java @@ -14,6 +14,8 @@ import org.apollo.net.meta.PacketType; import org.apollo.net.release.Release; import org.apollo.util.StatefulFrameDecoder; +import com.google.common.base.Preconditions; + /** * A {@link StatefulFrameDecoder} that decodes {@link GamePacket}s. * @@ -102,9 +104,7 @@ public final class GamePacketDecoder extends StatefulFrameDecoder } } else if (type == PacketType.VARIABLE_SHORT) { headerLength += 2; - if (payloadLength >= 65536) { + if (payloadLength >= 65_536) { throw new Exception("Payload too long for variable short packet."); } } diff --git a/src/org/apollo/net/codec/game/GamePacketReader.java b/src/org/apollo/net/codec/game/GamePacketReader.java index e75dce8e..810dde21 100644 --- a/src/org/apollo/net/codec/game/GamePacketReader.java +++ b/src/org/apollo/net/codec/game/GamePacketReader.java @@ -4,6 +4,8 @@ import io.netty.buffer.ByteBuf; import org.apollo.util.BufferUtil; +import com.google.common.base.Preconditions; + /** * A utility class for reading {@link GamePacket}s. * @@ -41,9 +43,7 @@ public final class GamePacketReader { * @throws IllegalStateException If the reader is not in bit access mode. */ private void checkBitAccess() { - if (mode != AccessMode.BIT_ACCESS) { - throw new IllegalStateException("For bit-based calls to work, the mode must be bit access."); - } + Preconditions.checkState(mode == AccessMode.BIT_ACCESS, "For bit-based calls to work, the mode must be bit access."); } /** @@ -52,9 +52,7 @@ public final class GamePacketReader { * @throws IllegalStateException If the reader is not in byte access mode. */ private void checkByteAccess() { - if (mode != AccessMode.BYTE_ACCESS) { - throw new IllegalStateException("For byte-based calls to work, the mode must be byte access."); - } + Preconditions.checkState(mode == AccessMode.BYTE_ACCESS, "For byte-based calls to work, the mode must be byte access."); } /** @@ -142,33 +140,30 @@ public final class GamePacketReader { } /** - * Gets {@code numBits} from the buffer. + * Gets the specified amount of bits from the buffer. * - * @param numBits The number of bits. + * @param amount The amount of bits. * @return The value. * @throws IllegalStateException If the reader is not in bit access mode. * @throws IllegalArgumentException If the number of bits is not between 1 and 31 inclusive. */ - public int getBits(int numBits) { - if (numBits < 0 || numBits > 32) { - throw new IllegalArgumentException("Number of bits must be between 1 and 32 inclusive."); - } - + public int getBits(int amount) { + Preconditions.checkArgument(amount >= 0 && amount <= 32, "Number of bits must be between 1 and 32 inclusive."); checkBitAccess(); int bytePos = bitIndex >> 3; int bitOffset = 8 - (bitIndex & 7); int value = 0; - bitIndex += numBits; + bitIndex += amount; - for (; numBits > bitOffset; bitOffset = 8) { - value += (buffer.getByte(bytePos++) & DataConstants.BIT_MASK[bitOffset]) << numBits - bitOffset; - numBits -= bitOffset; + for (; amount > bitOffset; bitOffset = 8) { + value += (buffer.getByte(bytePos++) & DataConstants.BIT_MASK[bitOffset]) << amount - bitOffset; + amount -= bitOffset; } - if (numBits == bitOffset) { + if (amount == bitOffset) { value += buffer.getByte(bytePos) & DataConstants.BIT_MASK[bitOffset]; } else { - value += buffer.getByte(bytePos) >> bitOffset - numBits & DataConstants.BIT_MASK[numBits]; + value += buffer.getByte(bytePos) >> bitOffset - amount & DataConstants.BIT_MASK[amount]; } return value; } @@ -363,9 +358,7 @@ public final class GamePacketReader { */ public long getUnsigned(DataType type, DataOrder order, DataTransformation transformation) { long longValue = get(type, order, transformation); - if (type == DataType.LONG) { - throw new IllegalArgumentException("Due to java restrictions, longs must be read as signed types."); - } + Preconditions.checkArgument(type != DataType.LONG, "Longs must be read as a signed type."); return longValue & 0xFFFFFFFFFFFFFFFFL; } @@ -403,9 +396,7 @@ public final class GamePacketReader { * @throws IllegalStateException If the builder is already in bit access mode. */ public void switchToBitAccess() { - if (mode == AccessMode.BIT_ACCESS) { - throw new IllegalStateException("Already in bit access mode."); - } + Preconditions.checkState(mode != AccessMode.BIT_ACCESS, "Already in bit access mode."); mode = AccessMode.BIT_ACCESS; bitIndex = buffer.readerIndex() * 8; } @@ -416,9 +407,7 @@ public final class GamePacketReader { * @throws IllegalStateException If the builder is already in byte access mode. */ public void switchToByteAccess() { - if (mode == AccessMode.BYTE_ACCESS) { - throw new IllegalStateException("Already in byte access mode."); - } + Preconditions.checkState(mode != AccessMode.BYTE_ACCESS, "Already in byte access mode."); mode = AccessMode.BYTE_ACCESS; buffer.readerIndex((bitIndex + 7) / 8); } diff --git a/src/org/apollo/net/meta/PacketMetaData.java b/src/org/apollo/net/meta/PacketMetaData.java index 0742ec46..07af6605 100644 --- a/src/org/apollo/net/meta/PacketMetaData.java +++ b/src/org/apollo/net/meta/PacketMetaData.java @@ -1,39 +1,39 @@ package org.apollo.net.meta; +import com.google.common.base.Preconditions; + /** - * A class which contains meta data for a single type of packet. + * A class containing meta data for a single type of packet. * * @author Graham */ public final class PacketMetaData { /** - * Creates a {@link PacketMetaData} object for a fixed-length packet. + * Creates packet meta data for a fixed-length packet. * * @param length The length of the packet. - * @return The {@link PacketMetaData} object. - * @throws IllegalArgumentException If length is less than 0. + * @return The packet meta data. + * @throws IllegalArgumentException If {@code length} is less than 0. */ public static PacketMetaData createFixed(int length) { - if (length < 0) { - throw new IllegalArgumentException("Packet length cannot be less than 0."); - } + Preconditions.checkArgument(length >= 0, "Packet length cannot be less than 0."); return new PacketMetaData(PacketType.FIXED, length); } /** - * Creates a {@link PacketMetaData} object for a variable byte length packet. + * Creates a packet meta data object for a variable byte length packet. * - * @return The {@link PacketMetaData} object. + * @return The packet meta data object. */ public static PacketMetaData createVariableByte() { return new PacketMetaData(PacketType.VARIABLE_BYTE, 0); } /** - * Creates a {@link PacketMetaData} object for a variable short length packet. + * Creates a packet meta data object for a variable short length packet. * - * @return The {@link PacketMetaData} object. + * @return The packet meta data object. */ public static PacketMetaData createVariableShort() { return new PacketMetaData(PacketType.VARIABLE_SHORT, 0); @@ -50,8 +50,8 @@ public final class PacketMetaData { private final PacketType type; /** - * Creates the packet meta data object. This should not be called directy. Use the {@link #createFixed(int)}, - * {@link #createVariableByte()} and {@link #createVariableShort()} methods instead! + * Creates the packet meta data object. This should not be called directly. Use the {@link #createFixed}, + * {@link #createVariableByte}, and {@link #createVariableShort} methods instead! * * @param type The type of packet. * @param length The length of the packet. @@ -68,9 +68,7 @@ public final class PacketMetaData { * @throws IllegalStateException If the packet is not a fixed-size packet. */ public int getLength() { - if (type != PacketType.FIXED) { - throw new IllegalStateException("Can only get the length of a fixed length packet."); - } + Preconditions.checkState(type == PacketType.FIXED, "Can only get the length of a fixed length packet."); return length; } diff --git a/src/org/apollo/net/meta/PacketMetaDataGroup.java b/src/org/apollo/net/meta/PacketMetaDataGroup.java index ab83ce64..8b2a0da9 100644 --- a/src/org/apollo/net/meta/PacketMetaDataGroup.java +++ b/src/org/apollo/net/meta/PacketMetaDataGroup.java @@ -1,49 +1,49 @@ package org.apollo.net.meta; +import com.google.common.base.Preconditions; + /** - * A class which contains a group of {@link PacketMetaData} objects. + * A class containing a group of {@link PacketMetaData} objects. * * @author Graham */ public final class PacketMetaDataGroup { /** - * Creates a {@link PacketMetaDataGroup} from the packet length array. + * Creates a packet meta data group from the packet length array. * - * @param lengthArray The packet length array. - * @return The {@link PacketMetaDataGroup} object. - * @throws IllegalArgumentException If the array length is not 256 or if there is an element in the array with a + * @param lengths The packet lengths. + * @return The packet meta data group. + * @throws IllegalArgumentException If the array length is not 256, or if there is an element in the array with a * value below -3. */ - public static PacketMetaDataGroup createFromArray(int[] lengthArray) { - if (lengthArray.length != 256) { - throw new IllegalArgumentException("Array length must be 256."); - } - PacketMetaDataGroup grp = new PacketMetaDataGroup(); - for (int i = 0; i < lengthArray.length; i++) { - int length = lengthArray[i]; + public static PacketMetaDataGroup createFromArray(int[] lengths) { + Preconditions.checkArgument(lengths.length == 256, "Array length must be 256."); + PacketMetaDataGroup group = new PacketMetaDataGroup(); + + for (int index = 0; index < lengths.length; index++) { + int length = lengths[index]; + Preconditions.checkArgument(length >= -2, "No packet length can have a value less than -3."); PacketMetaData metaData = null; - if (length < -3) { - throw new IllegalArgumentException("No packet length can have a value less than -3."); - } else if (length == -2) { + if (length == -2) { metaData = PacketMetaData.createVariableShort(); } else if (length == -1) { metaData = PacketMetaData.createVariableByte(); } else { metaData = PacketMetaData.createFixed(length); } - grp.packets[i] = metaData; + group.packets[index] = metaData; } - return grp; + return group; } /** - * The array of {@link PacketMetaData} objects. + * The array of packet meta data objects. */ private final PacketMetaData[] packets = new PacketMetaData[256]; /** - * This constructor should not be called directly. Use the {@link #createFromArray(int[])} method instead. + * This constructor should not be called directly. Use the {@link #createFromArray} method instead. */ private PacketMetaDataGroup() { @@ -54,12 +54,10 @@ public final class PacketMetaDataGroup { * * @param opcode The opcode of the packet. * @return The {@link PacketMetaData}, or {@code null} if the packet does not exist. - * @throws IllegalArgumentException If the opcode is not in the range 0 to 255. + * @throws IllegalArgumentException If the opcode is less than 0, or greater than 255. */ public PacketMetaData getMetaData(int opcode) { - if (opcode < 0 || opcode >= packets.length) { - throw new IllegalArgumentException("Opcode is out of bounds."); - } + Preconditions.checkElementIndex(opcode, packets.length, "Opcode out of bounds."); return packets[opcode]; } diff --git a/src/org/apollo/net/release/Release.java b/src/org/apollo/net/release/Release.java index ef0e1c4b..05063bf1 100644 --- a/src/org/apollo/net/release/Release.java +++ b/src/org/apollo/net/release/Release.java @@ -7,6 +7,8 @@ import org.apollo.game.message.Message; import org.apollo.net.meta.PacketMetaData; import org.apollo.net.meta.PacketMetaDataGroup; +import com.google.common.base.Preconditions; + /** * A {@link Release} is a distinct client version, e.g. {@code 317}. * @@ -60,11 +62,10 @@ public abstract class Release { * * @param opcode The opcode. * @return The message decoder. + * @throws IndexOutOfBoundsException If the opcode is less than 0, or greater than 255. */ public final MessageDecoder getMessageDecoder(int opcode) { - if (opcode < 0 || opcode >= decoders.length) { - throw new IndexOutOfBoundsException("Opcode is out of bounds."); - } + Preconditions.checkElementIndex(opcode, decoders.length, "Opcode out of bounds."); return decoders[opcode]; } @@ -103,11 +104,10 @@ public abstract class Release { * * @param opcode The opcode, between 0 and 255 inclusive. * @param decoder The message decoder. + * @throws IndexOutOfBoundsException If the opcode is less than 0, or greater than 255. */ public final void register(int opcode, MessageDecoder decoder) { - if (opcode < 0 || opcode >= decoders.length) { - throw new IndexOutOfBoundsException("Opcode is out of bounds."); - } + Preconditions.checkElementIndex(opcode, decoders.length, "Opcode out of bounds."); decoders[opcode] = decoder; } diff --git a/src/org/apollo/net/session/LoginSession.java b/src/org/apollo/net/session/LoginSession.java index 8f1ee099..1d0712aa 100644 --- a/src/org/apollo/net/session/LoginSession.java +++ b/src/org/apollo/net/session/LoginSession.java @@ -5,6 +5,8 @@ import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; +import java.util.Optional; + import org.apollo.ServerContext; import org.apollo.game.GameService; import org.apollo.game.model.World.RegistrationStatus; @@ -86,19 +88,21 @@ public final class LoginSession extends Session { GameService gameService = serverContext.getService(GameService.class); Channel channel = getChannel(); - int status = response.getStatus(); - Player player = response.getPlayer(); - int rights = player == null ? 0 : player.getPrivilegeLevel().toInteger(); - boolean log = false; + Optional responsePlayer = response.getPlayer(); + int status = response.getStatus(), rights = 0; + boolean flagged = false; + + if (responsePlayer.isPresent()) { + Player player = responsePlayer.get(); + rights = player.getPrivilegeLevel().toInteger(); - if (player != null) { GameSession session = new GameSession(channel, serverContext, player); player.setSession(session, false /* TODO */); RegistrationStatus registrationStatus = gameService.registerPlayer(player); if (registrationStatus != RegistrationStatus.OK) { - player = null; + responsePlayer = Optional.empty(); rights = 0; if (registrationStatus == RegistrationStatus.ALREADY_ONLINE) { status = LoginConstants.STATUS_ACCOUNT_ONLINE; @@ -108,16 +112,15 @@ public final class LoginSession extends Session { } } - ChannelFuture future = channel.writeAndFlush(new LoginResponse(status, rights, log)); + ChannelFuture future = channel.writeAndFlush(new LoginResponse(status, rights, flagged)); destroy(); - if (player != null) { + if (responsePlayer.isPresent()) { IsaacRandomPair randomPair = request.getRandomPair(); Release release = serverContext.getRelease(); channel.pipeline().addFirst("eventEncoder", new GameMessageEncoder(release)); - channel.pipeline().addBefore("eventEncoder", "gameEncoder", - new GamePacketEncoder(randomPair.getEncodingRandom())); + channel.pipeline().addBefore("eventEncoder", "gameEncoder", new GamePacketEncoder(randomPair.getEncodingRandom())); channel.pipeline().addBefore("handler", "gameDecoder", new GamePacketDecoder(randomPair.getDecodingRandom(), serverContext.getRelease())); @@ -126,7 +129,7 @@ public final class LoginSession extends Session { channel.pipeline().remove("loginDecoder"); channel.pipeline().remove("loginEncoder"); - channelContext.attr(NetworkConstants.SESSION_KEY).set(player.getSession()); + channelContext.attr(NetworkConstants.SESSION_KEY).set(responsePlayer.get().getSession()); } else { future.addListener(ChannelFutureListener.CLOSE); } diff --git a/src/org/apollo/tools/EquipmentUpdater.java b/src/org/apollo/tools/EquipmentUpdater.java index 2d1156af..a39b15cd 100644 --- a/src/org/apollo/tools/EquipmentUpdater.java +++ b/src/org/apollo/tools/EquipmentUpdater.java @@ -9,6 +9,8 @@ import org.apollo.fs.IndexedFileSystem; import org.apollo.fs.decoder.ItemDefinitionDecoder; import org.apollo.game.model.def.ItemDefinition; +import com.google.common.base.Preconditions; + /** * A tool for updating the equipment data. * @@ -1164,13 +1166,11 @@ public final class EquipmentUpdater { * @throws Exception If an error occurs. */ public static void main(String[] args) throws Exception { - if (args.length != 1) { - throw new IllegalArgumentException("Usage:\njava -cp ... org.apollo.tools.EquipmentUpdater [release]."); - } + Preconditions.checkArgument(args.length == 1, "Usage:\njava -cp ... org.apollo.tools.EquipmentUpdater [release]."); String release = args[0]; - try (DataOutputStream os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("data/equipment-" - + release + ".dat"))); + try (DataOutputStream os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("data/equipment-" + release + + ".dat"))); IndexedFileSystem fs = new IndexedFileSystem(Paths.get("data/fs/", release), true)) { ItemDefinitionDecoder decoder = new ItemDefinitionDecoder(fs); ItemDefinition[] definitions = decoder.decode(); diff --git a/src/org/apollo/tools/NoteUpdater.java b/src/org/apollo/tools/NoteUpdater.java index c5fb7c2e..af24986f 100644 --- a/src/org/apollo/tools/NoteUpdater.java +++ b/src/org/apollo/tools/NoteUpdater.java @@ -11,6 +11,8 @@ import org.apollo.fs.IndexedFileSystem; import org.apollo.fs.decoder.ItemDefinitionDecoder; import org.apollo.game.model.def.ItemDefinition; +import com.google.common.base.Preconditions; + /** * A tool for updating the note data. * @@ -25,9 +27,7 @@ public final class NoteUpdater { * @throws Exception If an error occurs. */ public static void main(String[] args) throws Exception { - if (args.length != 1) { - throw new IllegalArgumentException("Usage:\njava -cp ... org.apollo.tools.NoteUpdater [release]."); - } + Preconditions.checkArgument(args.length == 1, "Usage:\njava -cp ... org.apollo.tools.NoteUpdater [release]."); String release = args[0]; try (DataOutputStream os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("data/note-" diff --git a/src/org/apollo/util/MobRepository.java b/src/org/apollo/util/MobRepository.java index 6d272a0a..b4f4ba92 100644 --- a/src/org/apollo/util/MobRepository.java +++ b/src/org/apollo/util/MobRepository.java @@ -5,6 +5,8 @@ import java.util.NoSuchElementException; import org.apollo.game.model.entity.Mob; +import com.google.common.base.Preconditions; + /** * A {@link MobRepository} is a repository of {@link Mob}s that are currently active in the game world. * @@ -65,9 +67,7 @@ public final class MobRepository implements Iterable { @SuppressWarnings("unchecked") @Override public void remove() { - if (previousIndex == -1) { - throw new IllegalStateException("Cannot remove as the repository is empty."); - } + Preconditions.checkState(previousIndex != -1, "Cannot remove as the repository is empty."); MobRepository.this.remove((T) mobs[previousIndex]); previousIndex = -1; } @@ -183,13 +183,12 @@ public final class MobRepository implements Iterable { * * @param index The index of the mob * @return The mob instance + * @throws IndexOutOfBoundsException If the specified index is less than 0, or greater than or equal to the capacity + * of this repository. */ @SuppressWarnings("unchecked") public T get(int index) { - if (index < 0 || index >= mobs.length) { - throw new IndexOutOfBoundsException("Mob index is out of bounds."); - } - + Preconditions.checkElementIndex(index, mobs.length, "Mob index is out of bounds."); return (T) mobs[index]; } diff --git a/src/org/apollo/util/NameUtil.java b/src/org/apollo/util/NameUtil.java index 40d0e7c0..df1990b0 100644 --- a/src/org/apollo/util/NameUtil.java +++ b/src/org/apollo/util/NameUtil.java @@ -1,5 +1,7 @@ package org.apollo.util; +import com.google.common.base.Preconditions; + /** * A class which contains name-related utility methods. * @@ -10,10 +12,10 @@ public final class NameUtil { /** * An array of valid characters in a player name encoded as a long. */ - private static final char[] NAME_CHARS = { '_', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', - 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+', '=', ':', ';', '.', '>', '<', ',', - '"', '[', ']', '|', '?', '/', '`' }; + private static final char[] NAME_CHARS = { '_', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '!', '@', + '#', '$', '%', '^', '&', '*', '(', ')', '-', '+', '=', ':', ';', '.', '>', '<', ',', '"', '[', ']', '|', '?', '/', + '`' }; /** * Converts a long to a player name. @@ -39,13 +41,12 @@ public final class NameUtil { * @return The long. */ public static long encodeBase37(String name) { - if (name.length() > 12) { - throw new IllegalArgumentException("Name too long."); - } - long l = 0L; - for (int i = 0; i < name.length(); i++) { - char c = name.charAt(i); - l *= 37L; + Preconditions.checkArgument(name.length() <= 12, "Name too long."); + + long l = 0; + for (int index = 0; index < name.length(); index++) { + char c = name.charAt(index); + l *= 37; if (c >= 'A' && c <= 'Z') { l += 1 + c - 65; } else if (c >= 'a' && c <= 'z') { @@ -54,6 +55,7 @@ public final class NameUtil { l += 27 + c - 48; } } + for (; l % 37L == 0L && l != 0L; l /= 37L) { ; } diff --git a/src/org/apollo/util/StatefulFrameDecoder.java b/src/org/apollo/util/StatefulFrameDecoder.java index eef66617..4a46d704 100644 --- a/src/org/apollo/util/StatefulFrameDecoder.java +++ b/src/org/apollo/util/StatefulFrameDecoder.java @@ -6,6 +6,8 @@ import io.netty.handler.codec.ByteToMessageDecoder; import java.util.List; +import com.google.common.base.Preconditions; + /** * A stateful implementation of a {@link ByteToMessageDecoder} which may be extended and used by other classes. The * current state is tracked by this class and is a user-specified enumeration. @@ -17,8 +19,6 @@ import java.util.List; * * This class is not thread safe: it is recommended that the state is only set in the decode methods overriden. * - * {@code null} states are not permitted. - * * @author Graham * @param The state enumeration. */ @@ -77,7 +77,7 @@ public abstract class StatefulFrameDecoder> extends ByteToMess * @param ctx The current context of this handler. * @param in The cumulative buffer, which may contain zero or more bytes. * @param out The {@link List} of objects to pass forward through the pipeline. - * @param state The current state. The state may be changed by calling {@link #setState(Enum)}. + * @param state The current state. The state may be changed by calling {@link #setState}. */ protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List out, T state) { @@ -90,9 +90,7 @@ public abstract class StatefulFrameDecoder> extends ByteToMess * @throws NullPointerException If the state is {@code null}. */ public final void setState(T state) { - if (state == null) { - throw new NullPointerException("state"); - } + Preconditions.checkNotNull(state, "State cannot be null."); this.state = state; } diff --git a/src/org/apollo/util/plugin/DependencyException.java b/src/org/apollo/util/plugin/DependencyException.java index bb40ea2c..8528356b 100644 --- a/src/org/apollo/util/plugin/DependencyException.java +++ b/src/org/apollo/util/plugin/DependencyException.java @@ -1,14 +1,14 @@ package org.apollo.util.plugin; /** - * An {@link Exception} which is thrown when a dependency cannot be resolved, or when there is a circular dependency. + * An {@link Exception} thrown when a dependency cannot be resolved, or when there is a circular dependency. * * @author Graham */ public final class DependencyException extends Exception { /** - * A generated serial version id. + * The generated serial version id. */ private static final long serialVersionUID = -3335727281501054641L; diff --git a/src/org/apollo/util/xml/XmlParser.java b/src/org/apollo/util/xml/XmlParser.java index 6d320ff5..ad236c56 100644 --- a/src/org/apollo/util/xml/XmlParser.java +++ b/src/org/apollo/util/xml/XmlParser.java @@ -13,7 +13,7 @@ import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; /** - * A simple XML parser which uses the internal {@link org.xml.sax} API to create a tree of {@link XmlNode} objects. + * A simple XML parser that uses the internal {@link org.xml.sax} API to create a tree of {@link XmlNode} objects. * * @author Graham */ @@ -72,7 +72,7 @@ public final class XmlParser { private final XmlHandler eventHandler; /** - * The stack of nodes, which is used when traversing the document and going through child nodes. + * The stack of nodes, used when traversing the document and going through child nodes. */ private Stack nodeStack = new Stack<>(); @@ -87,7 +87,7 @@ public final class XmlParser { private final XMLReader xmlReader; /** - * Creates a new xml parser. + * Creates the XML parser. * * @throws SAXException If a SAX error occurs. */