From 53aa92db92dc89605826cbc1550a726a90ff9a79 Mon Sep 17 00:00:00 2001 From: Andrew Steinborn Date: Sat, 27 Oct 2018 22:18:30 -0400 Subject: [PATCH] Fix some low-hanging code smells using SonarLint. --- .../api/event/ResultedEvent.java | 18 +++++------ .../event/connection/PluginMessageEvent.java | 8 ++--- .../api/event/player/PlayerChatEvent.java | 10 +++--- .../api/permission/Tristate.java | 6 ++-- .../api/plugin/Dependency.java | 2 -- .../messages/LegacyChannelIdentifier.java | 2 +- .../api/proxy/player/SkinParts.java | 2 +- .../api/scheduler/Scheduler.java | 1 - .../velocitypowered/api/util/GameProfile.java | 2 +- .../velocitypowered/proxy/VelocityServer.java | 12 ++++--- .../backend/BackendPlaySessionHandler.java | 12 +++---- .../backend/VelocityServerConnection.java | 9 +++--- .../client/ClientPlaySessionHandler.java | 31 +++++++------------ .../client/ClientSettingsWrapper.java | 7 +++-- .../connection/client/ConnectedPlayer.java | 23 ++++++-------- .../client/HandshakeSessionHandler.java | 8 +++-- .../client/StatusSessionHandler.java | 5 ++- .../connection/forge/ForgeConstants.java | 11 ++++++- .../util/ConnectionRequestResults.java | 1 - .../proxy/console/VelocityConsole.java | 1 - .../proxy/network/ConnectionManager.java | 2 +- .../proxy/network/Connections.java | 30 ++++++++++-------- .../proxy/network/http/NettyHttpClient.java | 8 ++--- .../proxy/plugin/VelocityEventManager.java | 18 ++++++----- .../proxy/plugin/VelocityPluginManager.java | 7 ++--- .../proxy/plugin/loader/JavaPluginLoader.java | 1 - .../plugin/util/PluginDependencyUtils.java | 4 +++ .../proxy/protocol/StateRegistry.java | 8 ++--- .../proxy/protocol/netty/GS4QueryHandler.java | 18 +++++------ .../protocol/netty/MinecraftDecoder.java | 8 ++--- .../protocol/netty/MinecraftEncoder.java | 4 +-- .../proxy/protocol/packet/BossBar.java | 4 +++ .../proxy/protocol/packet/Chat.java | 6 ++-- .../proxy/protocol/packet/PlayerListItem.java | 26 ++++++++++------ .../proxy/protocol/packet/StatusRequest.java | 4 +-- .../proxy/protocol/packet/TitlePacket.java | 4 +++ .../protocol/util/FaviconSerializer.java | 2 +- .../protocol/util/PluginMessageUtil.java | 4 --- .../proxy/server/ping/PingSessionHandler.java | 2 +- 39 files changed, 171 insertions(+), 160 deletions(-) diff --git a/api/src/main/java/com/velocitypowered/api/event/ResultedEvent.java b/api/src/main/java/com/velocitypowered/api/event/ResultedEvent.java index ade22cbd9..6888260e6 100644 --- a/api/src/main/java/com/velocitypowered/api/event/ResultedEvent.java +++ b/api/src/main/java/com/velocitypowered/api/event/ResultedEvent.java @@ -43,20 +43,20 @@ public interface ResultedEvent { private static final GenericResult ALLOWED = new GenericResult(true); private static final GenericResult DENIED = new GenericResult(false); - private final boolean allowed; + private final boolean status; private GenericResult(boolean b) { - this.allowed = b; + this.status = b; } @Override public boolean isAllowed() { - return allowed; + return status; } @Override public String toString() { - return allowed ? "allowed" : "denied"; + return status ? "allowed" : "denied"; } public static GenericResult allowed() { @@ -74,17 +74,17 @@ public interface ResultedEvent { final class ComponentResult implements Result { private static final ComponentResult ALLOWED = new ComponentResult(true, null); - private final boolean allowed; + private final boolean status; private final @Nullable Component reason; - protected ComponentResult(boolean allowed, @Nullable Component reason) { - this.allowed = allowed; + protected ComponentResult(boolean status, @Nullable Component reason) { + this.status = status; this.reason = reason; } @Override public boolean isAllowed() { - return allowed; + return status; } public Optional getReason() { @@ -93,7 +93,7 @@ public interface ResultedEvent { @Override public String toString() { - if (allowed) { + if (status) { return "allowed"; } if (reason != null) { diff --git a/api/src/main/java/com/velocitypowered/api/event/connection/PluginMessageEvent.java b/api/src/main/java/com/velocitypowered/api/event/connection/PluginMessageEvent.java index 3540cf2a4..2ff72a55a 100644 --- a/api/src/main/java/com/velocitypowered/api/event/connection/PluginMessageEvent.java +++ b/api/src/main/java/com/velocitypowered/api/event/connection/PluginMessageEvent.java @@ -78,20 +78,20 @@ public final class PluginMessageEvent implements ResultedEventnull, true or false, respectively. */ public static Tristate fromNullableBoolean(@Nullable Boolean val) { - return val == null ? UNDEFINED : val ? TRUE : FALSE; + if (val == null) { + return UNDEFINED; + } + return val ? TRUE : FALSE; } private final boolean booleanValue; diff --git a/api/src/main/java/com/velocitypowered/api/plugin/Dependency.java b/api/src/main/java/com/velocitypowered/api/plugin/Dependency.java index 6af5d11e7..031f4598e 100644 --- a/api/src/main/java/com/velocitypowered/api/plugin/Dependency.java +++ b/api/src/main/java/com/velocitypowered/api/plugin/Dependency.java @@ -18,8 +18,6 @@ public @interface Dependency { */ String id(); - // TODO Add required version field - /** * If this dependency is optional for the plugin to work. By default * this is {@code false}. diff --git a/api/src/main/java/com/velocitypowered/api/proxy/messages/LegacyChannelIdentifier.java b/api/src/main/java/com/velocitypowered/api/proxy/messages/LegacyChannelIdentifier.java index 7ccc00ae0..b71983e96 100644 --- a/api/src/main/java/com/velocitypowered/api/proxy/messages/LegacyChannelIdentifier.java +++ b/api/src/main/java/com/velocitypowered/api/proxy/messages/LegacyChannelIdentifier.java @@ -42,6 +42,6 @@ public final class LegacyChannelIdentifier implements ChannelIdentifier { @Override public String getId() { - return name; + return this.getName(); } } diff --git a/api/src/main/java/com/velocitypowered/api/proxy/player/SkinParts.java b/api/src/main/java/com/velocitypowered/api/proxy/player/SkinParts.java index fcd43c2c5..c9fd2bbac 100644 --- a/api/src/main/java/com/velocitypowered/api/proxy/player/SkinParts.java +++ b/api/src/main/java/com/velocitypowered/api/proxy/player/SkinParts.java @@ -8,7 +8,7 @@ public final class SkinParts { } public boolean hasCape() { - return ((bitmask >> 0) & 1) == 1; + return (bitmask & 1) == 1; } public boolean hasJacket() { diff --git a/api/src/main/java/com/velocitypowered/api/scheduler/Scheduler.java b/api/src/main/java/com/velocitypowered/api/scheduler/Scheduler.java index 2e8bfec06..5a8848519 100644 --- a/api/src/main/java/com/velocitypowered/api/scheduler/Scheduler.java +++ b/api/src/main/java/com/velocitypowered/api/scheduler/Scheduler.java @@ -1,7 +1,6 @@ package com.velocitypowered.api.scheduler; import org.checkerframework.common.value.qual.IntRange; -import org.checkerframework.common.value.qual.IntRangeFromNonNegative; import java.util.concurrent.TimeUnit; diff --git a/api/src/main/java/com/velocitypowered/api/util/GameProfile.java b/api/src/main/java/com/velocitypowered/api/util/GameProfile.java index 93968b026..c9f290ff0 100644 --- a/api/src/main/java/com/velocitypowered/api/util/GameProfile.java +++ b/api/src/main/java/com/velocitypowered/api/util/GameProfile.java @@ -56,7 +56,7 @@ public final class GameProfile { '}'; } - public final static class Property { + public static final class Property { private final String name; private final String value; private final String signature; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/VelocityServer.java b/proxy/src/main/java/com/velocitypowered/proxy/VelocityServer.java index 334d9af4d..e2826b21b 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/VelocityServer.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/VelocityServer.java @@ -51,7 +51,6 @@ import java.nio.file.Paths; import java.security.KeyPair; import java.util.*; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicBoolean; public class VelocityServer implements ProxyServer { @@ -98,7 +97,9 @@ public class VelocityServer implements ProxyServer { @Override public ProxyVersion getVersion() { Package pkg = VelocityServer.class.getPackage(); - String implName, implVersion, implVendor; + String implName; + String implVersion; + String implVendor; if (pkg != null) { implName = MoreObjects.firstNonNull(pkg.getImplementationTitle(), "Velocity"); implVersion = MoreObjects.firstNonNull(pkg.getImplementationVersion(), ""); @@ -148,7 +149,7 @@ public class VelocityServer implements ProxyServer { AnnotatedConfig.saveConfig(configuration.dumpConfig(), configPath); //Resave config to add new values - } catch (Throwable e) { + } catch (Exception e) { logger.error("Unable to read/load/save your velocity.toml. The server will shut down.", e); LogManager.shutdown(); System.exit(1); @@ -183,10 +184,10 @@ public class VelocityServer implements ProxyServer { try { Path pluginPath = Paths.get("plugins"); - if (Files.notExists(pluginPath)) { + if (!pluginPath.toFile().exists()) { Files.createDirectory(pluginPath); } else { - if (!Files.isDirectory(pluginPath)) { + if (!pluginPath.toFile().isDirectory()) { logger.warn("Plugin location {} is not a directory, continuing without loading plugins", pluginPath); return; } @@ -242,6 +243,7 @@ public class VelocityServer implements ProxyServer { } } catch (InterruptedException e) { // Not much we can do about this... + Thread.currentThread().interrupt(); } shutdown = true; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BackendPlaySessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BackendPlaySessionHandler.java index c4a1193bf..6f6318ed6 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BackendPlaySessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BackendPlaySessionHandler.java @@ -1,7 +1,6 @@ package com.velocitypowered.proxy.connection.backend; import com.velocitypowered.api.event.connection.PluginMessageEvent; -import com.velocitypowered.api.event.player.ServerConnectedEvent; import com.velocitypowered.api.proxy.messages.ChannelIdentifier; import com.velocitypowered.proxy.VelocityServer; import com.velocitypowered.proxy.connection.MinecraftConnection; @@ -67,13 +66,10 @@ public class BackendPlaySessionHandler implements MinecraftSessionHandler { @Override public boolean handle(BossBar packet) { - switch (packet.getAction()) { - case BossBar.ADD: - playerSessionHandler.getServerBossBars().add(packet.getUuid()); - break; - case BossBar.REMOVE: - playerSessionHandler.getServerBossBars().remove(packet.getUuid()); - break; + if (packet.getAction() == BossBar.ADD) { + playerSessionHandler.getServerBossBars().add(packet.getUuid()); + } else if (packet.getAction() == BossBar.REMOVE) { + playerSessionHandler.getServerBossBars().remove(packet.getUuid()); } return false; // forward } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/VelocityServerConnection.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/VelocityServerConnection.java index d7bc52c2f..7abf631b3 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/VelocityServerConnection.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/VelocityServerConnection.java @@ -1,7 +1,6 @@ package com.velocitypowered.proxy.connection.backend; import com.google.common.base.Preconditions; -import com.google.common.base.Verify; import com.google.common.base.VerifyException; import com.velocitypowered.api.proxy.ConnectionRequestBuilder; import com.velocitypowered.api.proxy.ServerConnection; @@ -65,10 +64,10 @@ public class VelocityServerConnection implements MinecraftConnectionAssociation, .addLast(MINECRAFT_DECODER, new MinecraftDecoder(ProtocolConstants.Direction.CLIENTBOUND)) .addLast(MINECRAFT_ENCODER, new MinecraftEncoder(ProtocolConstants.Direction.SERVERBOUND)); - MinecraftConnection connection = new MinecraftConnection(ch, server); - connection.setState(StateRegistry.HANDSHAKE); - connection.setAssociation(VelocityServerConnection.this); - ch.pipeline().addLast(HANDLER, connection); + MinecraftConnection mc = new MinecraftConnection(ch, server); + mc.setState(StateRegistry.HANDSHAKE); + mc.setAssociation(VelocityServerConnection.this); + ch.pipeline().addLast(HANDLER, mc); } }) .connect(registeredServer.getServerInfo().getAddress()) diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientPlaySessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientPlaySessionHandler.java index 771f7367e..5dc5e261b 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientPlaySessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientPlaySessionHandler.java @@ -1,6 +1,5 @@ package com.velocitypowered.proxy.connection.client; -import com.google.common.base.Preconditions; import com.velocitypowered.api.event.connection.PluginMessageEvent; import com.velocitypowered.api.event.player.PlayerChatEvent; import com.velocitypowered.api.proxy.messages.ChannelIdentifier; @@ -57,13 +56,11 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { VelocityServerConnection serverConnection = player.getConnectedServer(); if (serverConnection != null && packet.getRandomId() == serverConnection.getLastPingId()) { MinecraftConnection smc = serverConnection.getConnection(); - if (smc == null) { - // eat the packet - return true; + if (smc != null) { + player.setPing(System.currentTimeMillis() - serverConnection.getLastPingSent()); + smc.write(packet); + serverConnection.resetLastPingId(); } - player.setPing(System.currentTimeMillis() - serverConnection.getLastPingSent()); - smc.write(packet); - serverConnection.resetLastPingId(); } return true; } @@ -122,7 +119,7 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { String cmd = packet.getCommand().substring(1, spacePos); if (server.getCommandManager().hasCommand(cmd)) { List suggestions = server.getCommandManager().offerSuggestions(player, packet.getCommand().substring(1)); - if (suggestions.size() > 0) { + if (!suggestions.isEmpty()) { TabCompleteResponse resp = new TabCompleteResponse(); resp.getOffers().addAll(suggestions); player.getConnection().write(resp); @@ -153,20 +150,17 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { } } - if (actuallyRegistered.size() > 0) { + if (!actuallyRegistered.isEmpty()) { PluginMessage newRegisterPacket = PluginMessageUtil.constructChannelsPacket(backendConn .getProtocolVersion(), actuallyRegistered); backendConn.write(newRegisterPacket); } - return true; } else if (PluginMessageUtil.isMCUnregister(packet)) { List channels = PluginMessageUtil.getChannels(packet); clientPluginMsgChannels.removeAll(channels); backendConn.write(packet); - return true; } else if (PluginMessageUtil.isMCBrand(packet)) { backendConn.write(PluginMessageUtil.rewriteMCBrand(packet)); - return true; } else if (backendConn.isLegacyForge() && !serverConn.hasCompletedJoin()) { if (packet.getChannel().equals(ForgeConstants.FORGE_LEGACY_HANDSHAKE_CHANNEL)) { if (!player.getModInfo().isPresent()) { @@ -184,17 +178,14 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { // be sent once the JoinGame packet has been received by the proxy. loginPluginMessages.add(packet); } - return true; } else { ChannelIdentifier id = server.getChannelRegistrar().getFromId(packet.getChannel()); if (id == null) { backendConn.write(packet); } else { PluginMessageEvent event = new PluginMessageEvent(player, serverConn, id, packet.getData()); - server.getEventManager().fire(event) - .thenAcceptAsync(pme -> { - backendConn.write(packet); - }, backendConn.eventLoop()); + server.getEventManager().fire(event).thenAcceptAsync(pme -> backendConn.write(packet), + backendConn.eventLoop()); } } } @@ -246,10 +237,10 @@ public class ClientPlaySessionHandler implements MinecraftSessionHandler { @Override public void writabilityChanged() { - VelocityServerConnection server = player.getConnectedServer(); - if (server != null) { + VelocityServerConnection serverConn = player.getConnectedServer(); + if (serverConn != null) { boolean writable = player.getConnection().getChannel().isWritable(); - MinecraftConnection smc = server.getConnection(); + MinecraftConnection smc = serverConn.getConnection(); if (smc != null) { smc.getChannel().config().setAutoRead(writable); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientSettingsWrapper.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientSettingsWrapper.java index 41c5a0da8..5881b7692 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientSettingsWrapper.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ClientSettingsWrapper.java @@ -8,7 +8,7 @@ import org.checkerframework.checker.nullness.qual.Nullable; import java.util.Locale; public class ClientSettingsWrapper implements PlayerSettings { - static PlayerSettings DEFAULT = new ClientSettingsWrapper(new ClientSettings("en_US", (byte) 10, 0, true, (short)127, 1)); + static final PlayerSettings DEFAULT = new ClientSettingsWrapper(new ClientSettings("en_US", (byte) 10, 0, true, (short)127, 1)); private final ClientSettings settings; private final SkinParts parts; @@ -21,7 +21,10 @@ public class ClientSettingsWrapper implements PlayerSettings { @Override public Locale getLocale() { - return locale == null ? locale = Locale.forLanguageTag(settings.getLocale().replaceAll("_", "-")) : locale; //Will throw error if locale not found + if (locale == null) { + locale = Locale.forLanguageTag(settings.getLocale().replaceAll("_", "-")); + } + return locale; } @Override diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ConnectedPlayer.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ConnectedPlayer.java index acd7e0128..6e934d1ed 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ConnectedPlayer.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/ConnectedPlayer.java @@ -43,27 +43,24 @@ import net.kyori.text.serializer.PlainComponentSerializer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; -import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import java.net.InetSocketAddress; -import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; -import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; public class ConnectedPlayer implements MinecraftConnectionAssociation, Player { - private static final PlainComponentSerializer PASS_THRU_TRANSLATE = new PlainComponentSerializer((c) -> "", TranslatableComponent::key); + private static final PlainComponentSerializer PASS_THRU_TRANSLATE = new PlainComponentSerializer(c -> "", TranslatableComponent::key); static final PermissionProvider DEFAULT_PERMISSIONS = s -> PermissionFunction.ALWAYS_UNDEFINED; private static final Logger logger = LogManager.getLogger(ConnectedPlayer.class); private final MinecraftConnection connection; - private @Nullable final InetSocketAddress virtualHost; + private final @Nullable InetSocketAddress virtualHost; private GameProfile profile; private PermissionFunction permissionFunction; private int tryIndex = 0; @@ -84,7 +81,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player { this.profile = profile; this.connection = connection; this.virtualHost = virtualHost; - this.permissionFunction = (permission) -> Tristate.UNDEFINED; + this.permissionFunction = PermissionFunction.ALWAYS_UNDEFINED; } @Override @@ -364,8 +361,8 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player { Optional getNextServerToTry() { if (serversToTry == null) { - String virtualHost = getVirtualHost().map(InetSocketAddress::getHostString).orElse(""); - serversToTry = server.getConfiguration().getForcedHosts().getOrDefault(virtualHost, Collections.emptyList()); + String virtualHostStr = getVirtualHost().map(InetSocketAddress::getHostString).orElse(""); + serversToTry = server.getConfiguration().getForcedHosts().getOrDefault(virtualHostStr, Collections.emptyList()); } if (serversToTry.isEmpty()) { @@ -401,7 +398,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player { // Otherwise, initiate the connection. ServerPreConnectEvent event = new ServerPreConnectEvent(this, request.getServer()); return server.getEventManager().fire(event) - .thenCompose((newEvent) -> { + .thenCompose(newEvent -> { Optional connectTo = newEvent.getResult().getServer(); if (!connectTo.isPresent()) { return CompletableFuture.completedFuture( @@ -431,10 +428,7 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player { public void sendLegacyForgeHandshakeResetPacket() { if (connection.canSendLegacyFMLResetPacket()) { - PluginMessage resetPacket = new PluginMessage(); - resetPacket.setChannel(ForgeConstants.FORGE_LEGACY_HANDSHAKE_CHANNEL); - resetPacket.setData(ForgeConstants.FORGE_LEGACY_HANDSHAKE_RESET_DATA); - connection.write(resetPacket); + connection.write(ForgeConstants.resetPacket()); connection.setCanSendLegacyFMLResetPacket(false); } } @@ -534,6 +528,9 @@ public class ConnectedPlayer implements MinecraftConnectionAssociation, Player { case SERVER_DISCONNECTED: handleConnectionException(server, Disconnect.create(status.getReason().orElse(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR))); break; + default: + // The only remaining value is successful (no need to do anything!) + break; } }, connection.eventLoop()) .thenApply(Result::isSuccessful); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/HandshakeSessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/HandshakeSessionHandler.java index 74e73cc0b..aa3efa01d 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/HandshakeSessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/HandshakeSessionHandler.java @@ -48,7 +48,8 @@ public class HandshakeSessionHandler implements MinecraftSessionHandler { server.getEventManager().fire(event) .thenRunAsync(() -> { // The disconnect packet is the same as the server response one. - connection.closeWith(LegacyDisconnect.fromPingResponse(LegacyPingResponse.from(event.getPing()))); + LegacyPingResponse response = LegacyPingResponse.from(event.getPing()); + connection.closeWith(LegacyDisconnect.fromPingResponse(response)); }, connection.eventLoop()); return true; } @@ -116,12 +117,13 @@ public class HandshakeSessionHandler implements MinecraftSessionHandler { @Override public void handleGeneric(MinecraftPacket packet) { - + // Unknown packet received. Better to close the connection. + connection.close(); } @Override public void handleUnknown(ByteBuf buf) { - // what even is going on? + // Unknown packet received. Better to close the connection. connection.close(); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/StatusSessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/StatusSessionHandler.java index 077dce0aa..1bbf81914 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/StatusSessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/StatusSessionHandler.java @@ -48,9 +48,8 @@ public class StatusSessionHandler implements MinecraftSessionHandler { ProxyPingEvent event = new ProxyPingEvent(inboundWrapper, initialPing); server.getEventManager().fire(event) - .thenRunAsync(() -> { - connection.write(new StatusResponse(VelocityServer.GSON.toJson(event.getPing()))); - }, connection.eventLoop()); + .thenRunAsync(() -> connection.write(new StatusResponse(VelocityServer.GSON.toJson(event.getPing()))), + connection.eventLoop()); return true; } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/forge/ForgeConstants.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/forge/ForgeConstants.java index ac09d2981..d4be8e585 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/forge/ForgeConstants.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/forge/ForgeConstants.java @@ -1,12 +1,21 @@ package com.velocitypowered.proxy.connection.forge; +import com.velocitypowered.proxy.protocol.packet.PluginMessage; + public class ForgeConstants { public static final String FORGE_LEGACY_HANDSHAKE_CHANNEL = "FML|HS"; public static final String FORGE_LEGACY_CHANNEL = "FML"; public static final String FORGE_MULTIPART_LEGACY_CHANNEL = "FML|MP"; - public static final byte[] FORGE_LEGACY_HANDSHAKE_RESET_DATA = new byte[] { -2, 0 }; + private static final byte[] FORGE_LEGACY_HANDSHAKE_RESET_DATA = new byte[] { -2, 0 }; private ForgeConstants() { throw new AssertionError(); } + + public static PluginMessage resetPacket() { + PluginMessage msg = new PluginMessage(); + msg.setChannel(FORGE_LEGACY_HANDSHAKE_CHANNEL); + msg.setData(FORGE_LEGACY_HANDSHAKE_RESET_DATA.clone()); + return msg; + } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ConnectionRequestResults.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ConnectionRequestResults.java index 968e8f378..5d36b2ed0 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ConnectionRequestResults.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ConnectionRequestResults.java @@ -3,7 +3,6 @@ package com.velocitypowered.proxy.connection.util; import com.velocitypowered.api.proxy.ConnectionRequestBuilder; import com.velocitypowered.proxy.protocol.packet.Disconnect; import net.kyori.text.Component; -import net.kyori.text.TextComponent; import net.kyori.text.serializer.ComponentSerializers; import java.util.Optional; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/console/VelocityConsole.java b/proxy/src/main/java/com/velocitypowered/proxy/console/VelocityConsole.java index 44e7bbfe2..be213db4d 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/console/VelocityConsole.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/console/VelocityConsole.java @@ -18,7 +18,6 @@ import org.jline.reader.LineReader; import org.jline.reader.LineReaderBuilder; import java.util.List; -import java.util.Optional; public final class VelocityConsole extends SimpleTerminalConsole implements CommandSource { private static final Logger logger = LogManager.getLogger(VelocityConsole.class); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/network/ConnectionManager.java b/proxy/src/main/java/com/velocitypowered/proxy/network/ConnectionManager.java index 41652415a..524887f4a 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/network/ConnectionManager.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/network/ConnectionManager.java @@ -12,7 +12,6 @@ import io.netty.channel.EventLoopGroup; import io.netty.channel.WriteBufferWaterMark; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.checkerframework.checker.initialization.qual.UnderInitialization; import java.net.InetSocketAddress; import java.util.HashSet; @@ -94,6 +93,7 @@ public final class ConnectionManager { endpoint.close().sync(); } catch (final InterruptedException e) { LOGGER.info("Interrupted whilst closing endpoint", e); + Thread.currentThread().interrupt(); } } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/network/Connections.java b/proxy/src/main/java/com/velocitypowered/proxy/network/Connections.java index fb248dc6a..57a8aa53d 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/network/Connections.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/network/Connections.java @@ -1,16 +1,20 @@ package com.velocitypowered.proxy.network; -public interface Connections { - String CIPHER_DECODER = "cipher-decoder"; - String CIPHER_ENCODER = "cipher-encoder"; - String COMPRESSION_DECODER = "compression-decoder"; - String COMPRESSION_ENCODER = "compression-encoder"; - String FRAME_DECODER = "frame-decoder"; - String FRAME_ENCODER = "frame-encoder"; - String HANDLER = "handler"; - String LEGACY_PING_DECODER = "legacy-ping-decoder"; - String LEGACY_PING_ENCODER = "legacy-ping-encoder"; - String MINECRAFT_DECODER = "minecraft-decoder"; - String MINECRAFT_ENCODER = "minecraft-encoder"; - String READ_TIMEOUT = "read-timeout"; +public class Connections { + public static final String CIPHER_DECODER = "cipher-decoder"; + public static final String CIPHER_ENCODER = "cipher-encoder"; + public static final String COMPRESSION_DECODER = "compression-decoder"; + public static final String COMPRESSION_ENCODER = "compression-encoder"; + public static final String FRAME_DECODER = "frame-decoder"; + public static final String FRAME_ENCODER = "frame-encoder"; + public static final String HANDLER = "handler"; + public static final String LEGACY_PING_DECODER = "legacy-ping-decoder"; + public static final String LEGACY_PING_ENCODER = "legacy-ping-encoder"; + public static final String MINECRAFT_DECODER = "minecraft-decoder"; + public static final String MINECRAFT_ENCODER = "minecraft-encoder"; + public static final String READ_TIMEOUT = "read-timeout"; + + private Connections() { + throw new AssertionError(); + } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/network/http/NettyHttpClient.java b/proxy/src/main/java/com/velocitypowered/proxy/network/http/NettyHttpClient.java index dc83343d5..128911d34 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/network/http/NettyHttpClient.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/network/http/NettyHttpClient.java @@ -31,6 +31,8 @@ public class NettyHttpClient { @Override public void channelAcquired(Channel channel) throws Exception { + // We don't do anything special when acquiring channels. The channel handler cleans up after + // each connection is used. } @Override @@ -72,10 +74,8 @@ public class NettyHttpClient { request.headers().add(HttpHeaderNames.USER_AGENT, "Velocity"); channel.writeAndFlush(request); - reply.whenComplete((resp, err) -> { - // Make sure to release this connection - poolMap.get(address).release(channel, channel.voidPromise()); - }); + // Make sure to release this connection + reply.whenComplete((resp, err) -> poolMap.get(address).release(channel)); } else { reply.completeExceptionally(future.cause()); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/plugin/VelocityEventManager.java b/proxy/src/main/java/com/velocitypowered/proxy/plugin/VelocityEventManager.java index c26b04284..8a9e677ac 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/plugin/VelocityEventManager.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/plugin/VelocityEventManager.java @@ -55,11 +55,15 @@ public class VelocityEventManager implements EventManager { .setNameFormat("Velocity Event Executor - #%d").setDaemon(true).build()); } + private void ensurePlugin(Object plugin) { + Preconditions.checkNotNull(plugin, "plugin"); + Preconditions.checkArgument(pluginManager.fromInstance(plugin).isPresent(), "Specified plugin is not loaded"); + } + @Override public void register(Object plugin, Object listener) { - Preconditions.checkNotNull(plugin, "plugin"); + ensurePlugin(plugin); Preconditions.checkNotNull(listener, "listener"); - Preconditions.checkArgument(pluginManager.fromInstance(plugin).isPresent(), "Specified plugin is not loaded"); if (plugin == listener && registeredListenersByPlugin.containsEntry(plugin, plugin)) { throw new IllegalArgumentException("Trying to register the plugin main instance. Velocity already takes care of this for you."); } @@ -70,7 +74,7 @@ public class VelocityEventManager implements EventManager { @Override @SuppressWarnings("type.argument.type.incompatible") public void register(Object plugin, Class eventClass, PostOrder postOrder, EventHandler handler) { - Preconditions.checkNotNull(plugin, "plugin"); + ensurePlugin(plugin); Preconditions.checkNotNull(eventClass, "eventClass"); Preconditions.checkNotNull(postOrder, "postOrder"); Preconditions.checkNotNull(handler, "listener"); @@ -108,8 +112,7 @@ public class VelocityEventManager implements EventManager { @Override public void unregisterListeners(Object plugin) { - Preconditions.checkNotNull(plugin, "plugin"); - Preconditions.checkArgument(pluginManager.fromInstance(plugin).isPresent(), "Specified plugin is not loaded"); + ensurePlugin(plugin); Collection listeners = registeredListenersByPlugin.removeAll(plugin); listeners.forEach(methodAdapter::unregister); Collection> handlers = registeredHandlersByPlugin.removeAll(plugin); @@ -118,16 +121,15 @@ public class VelocityEventManager implements EventManager { @Override public void unregisterListener(Object plugin, Object listener) { - Preconditions.checkNotNull(plugin, "plugin"); + ensurePlugin(plugin); Preconditions.checkNotNull(listener, "listener"); - Preconditions.checkArgument(pluginManager.fromInstance(plugin).isPresent(), "Specified plugin is not loaded"); registeredListenersByPlugin.remove(plugin, listener); methodAdapter.unregister(listener); } @Override public void unregister(Object plugin, EventHandler handler) { - Preconditions.checkNotNull(plugin, "plugin"); + ensurePlugin(plugin); Preconditions.checkNotNull(handler, "listener"); registeredHandlersByPlugin.remove(plugin, handler); bus.unregister(new KyoriToVelocityHandler<>(handler, PostOrder.LAST)); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/plugin/VelocityPluginManager.java b/proxy/src/main/java/com/velocitypowered/proxy/plugin/VelocityPluginManager.java index 5556dca0f..880025a6e 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/plugin/VelocityPluginManager.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/plugin/VelocityPluginManager.java @@ -9,7 +9,6 @@ import com.velocitypowered.proxy.plugin.loader.JavaPluginLoader; import com.velocitypowered.proxy.plugin.util.PluginDependencyUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.checkerframework.checker.nullness.qual.NonNull; import java.io.IOException; import java.nio.file.DirectoryStream; @@ -41,12 +40,12 @@ public class VelocityPluginManager implements PluginManager { public void loadPlugins(Path directory) throws IOException { checkNotNull(directory, "directory"); - checkArgument(Files.isDirectory(directory), "provided path isn't a directory"); + checkArgument(directory.toFile().isDirectory(), "provided path isn't a directory"); List found = new ArrayList<>(); JavaPluginLoader loader = new JavaPluginLoader(server, directory); - try (DirectoryStream stream = Files.newDirectoryStream(directory, p -> Files.isRegularFile(p) && p.toString().endsWith(".jar"))) { + try (DirectoryStream stream = Files.newDirectoryStream(directory, p -> p.toFile().isFile() && p.toString().endsWith(".jar"))) { for (Path path : stream) { try { found.add(loader.loadPlugin(path)); @@ -79,7 +78,7 @@ public class VelocityPluginManager implements PluginManager { try { pluginObject = loader.createPlugin(plugin); - } catch (Throwable e) { + } catch (Exception e) { logger.error("Can't create plugin {}", plugin.getId(), e); continue; } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/JavaPluginLoader.java b/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/JavaPluginLoader.java index e1c184dca..fda0836d3 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/JavaPluginLoader.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/JavaPluginLoader.java @@ -12,7 +12,6 @@ import com.velocitypowered.proxy.VelocityServer; import com.velocitypowered.proxy.plugin.PluginClassLoader; import com.velocitypowered.proxy.plugin.loader.java.JavaVelocityPluginDescription; import com.velocitypowered.proxy.plugin.loader.java.VelocityPluginModule; -import org.checkerframework.checker.nullness.qual.NonNull; import java.io.BufferedInputStream; import java.io.InputStreamReader; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/plugin/util/PluginDependencyUtils.java b/proxy/src/main/java/com/velocitypowered/proxy/plugin/util/PluginDependencyUtils.java index ecb25f527..c222ad643 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/plugin/util/PluginDependencyUtils.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/plugin/util/PluginDependencyUtils.java @@ -13,6 +13,10 @@ import org.checkerframework.checker.nullness.qual.NonNull; import java.util.*; public class PluginDependencyUtils { + private PluginDependencyUtils() { + throw new AssertionError(); + } + public static List sortCandidates(List<@NonNull PluginDescription> candidates) { // Create our graph, we're going to be using this for Kahn's algorithm. MutableGraph graph = GraphBuilder.directed().allowsSelfLoops(false).build(); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/StateRegistry.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/StateRegistry.java index 25711266a..61b332ff9 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/StateRegistry.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/StateRegistry.java @@ -217,12 +217,12 @@ public enum StateRegistry { } public class ProtocolVersion { - public final int id; + public final int version; final IntObjectMap> packetIdToSupplier = new IntObjectHashMap<>(16, 0.5f); final Object2IntMap> packetClassToId = new Object2IntOpenHashMap<>(16, 0.5f); - ProtocolVersion(final int id) { - this.id = id; + ProtocolVersion(final int version) { + this.version = version; this.packetClassToId.defaultReturnValue(Integer.MIN_VALUE); } @@ -239,7 +239,7 @@ public enum StateRegistry { if (id == Integer.MIN_VALUE) { throw new IllegalArgumentException(String.format( "Unable to find id for packet of type %s in %s protocol %s", - packet.getClass().getName(), PacketRegistry.this.direction, this.id + packet.getClass().getName(), PacketRegistry.this.direction, this.version )); } return id; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/GS4QueryHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/GS4QueryHandler.java index e9a6a016e..29e998110 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/GS4QueryHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/GS4QueryHandler.java @@ -35,15 +35,15 @@ import static com.velocitypowered.api.event.query.ProxyQueryEvent.QueryType.FULL public class GS4QueryHandler extends SimpleChannelInboundHandler { private static final Logger logger = LogManager.getLogger(GS4QueryHandler.class); - private final static short QUERY_MAGIC_FIRST = 0xFE; - private final static short QUERY_MAGIC_SECOND = 0xFD; - private final static byte QUERY_TYPE_HANDSHAKE = 0x09; - private final static byte QUERY_TYPE_STAT = 0x00; - private final static byte[] QUERY_RESPONSE_FULL_PADDING = new byte[] { 0x73, 0x70, 0x6C, 0x69, 0x74, 0x6E, 0x75, 0x6D, 0x00, (byte) 0x80, 0x00 }; - private final static byte[] QUERY_RESPONSE_FULL_PADDING2 = new byte[] { 0x01, 0x70, 0x6C, 0x61, 0x79, 0x65, 0x72, 0x5F, 0x00, 0x00 }; + private static final short QUERY_MAGIC_FIRST = 0xFE; + private static final short QUERY_MAGIC_SECOND = 0xFD; + private static final byte QUERY_TYPE_HANDSHAKE = 0x09; + private static final byte QUERY_TYPE_STAT = 0x00; + private static final byte[] QUERY_RESPONSE_FULL_PADDING = new byte[] { 0x73, 0x70, 0x6C, 0x69, 0x74, 0x6E, 0x75, 0x6D, 0x00, (byte) 0x80, 0x00 }; + private static final byte[] QUERY_RESPONSE_FULL_PADDING2 = new byte[] { 0x01, 0x70, 0x6C, 0x61, 0x79, 0x65, 0x72, 0x5F, 0x00, 0x00 }; // Contents to add into basic stat response. See ResponseWriter class below - private final static Set QUERY_BASIC_RESPONSE_CONTENTS = ImmutableSet.of( + private static final Set QUERY_BASIC_RESPONSE_CONTENTS = ImmutableSet.of( "hostname", "gametype", "map", @@ -159,10 +159,8 @@ public class GS4QueryHandler extends SimpleChannelInboundHandler break; } - - default: { + default: throw new IllegalStateException("Invalid query type: " + type); - } } } catch (Exception e) { logger.warn("Error while trying to handle a query packet from {}", msg.sender(), e); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftDecoder.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftDecoder.java index 6ffd51f4c..c28adca2b 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftDecoder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftDecoder.java @@ -38,14 +38,14 @@ public class MinecraftDecoder extends MessageToMessageDecoder { out.add(slice.retain()); } else { try { - packet.decode(msg, direction, protocolVersion.id); + packet.decode(msg, direction, protocolVersion.version); } catch (Exception e) { throw new CorruptedFrameException("Error decoding " + packet.getClass() + " Direction " + direction - + " Protocol " + protocolVersion.id + " State " + state + " ID " + Integer.toHexString(packetId), e); + + " Protocol " + protocolVersion.version + " State " + state + " ID " + Integer.toHexString(packetId), e); } if (msg.isReadable()) { throw new CorruptedFrameException("Did not read full packet for " + packet.getClass() + " Direction " + direction - + " Protocol " + protocolVersion.id + " State " + state + " ID " + Integer.toHexString(packetId)); + + " Protocol " + protocolVersion.version + " State " + state + " ID " + Integer.toHexString(packetId)); } out.add(packet); } @@ -57,6 +57,6 @@ public class MinecraftDecoder extends MessageToMessageDecoder { public void setState(StateRegistry state) { this.state = state; - this.setProtocolVersion(protocolVersion.id); + this.setProtocolVersion(protocolVersion.version); } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftEncoder.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftEncoder.java index 8efcaa398..bba53d49e 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftEncoder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/MinecraftEncoder.java @@ -24,7 +24,7 @@ public class MinecraftEncoder extends MessageToByteEncoder { protected void encode(ChannelHandlerContext ctx, MinecraftPacket msg, ByteBuf out) { int packetId = this.protocolVersion.getPacketId(msg); ProtocolUtils.writeVarInt(out, packetId); - msg.encode(out, direction, protocolVersion.id); + msg.encode(out, direction, protocolVersion.version); } public void setProtocolVersion(final int protocolVersion) { @@ -33,6 +33,6 @@ public class MinecraftEncoder extends MessageToByteEncoder { public void setState(StateRegistry state) { this.state = state; - this.setProtocolVersion(protocolVersion.id); + this.setProtocolVersion(protocolVersion.version); } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/BossBar.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/BossBar.java index d2a11f41b..8c2dd2ae7 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/BossBar.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/BossBar.java @@ -123,6 +123,8 @@ public class BossBar implements MinecraftPacket { case UPDATE_PROPERTIES: this.flags = buf.readUnsignedByte(); break; + default: + throw new UnsupportedOperationException("Unknown action " + action); } } @@ -162,6 +164,8 @@ public class BossBar implements MinecraftPacket { case UPDATE_PROPERTIES: buf.writeByte(flags); break; + default: + throw new UnsupportedOperationException("Unknown action " + action); } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/Chat.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/Chat.java index 1b8b8d88c..2944d4d7d 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/Chat.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/Chat.java @@ -11,7 +11,7 @@ import net.kyori.text.serializer.ComponentSerializers; import org.checkerframework.checker.nullness.qual.Nullable; public class Chat implements MinecraftPacket { - public static final byte CHAT = (byte) 0; + public static final byte CHAT_TYPE = (byte) 0; public static final int MAX_SERVERBOUND_MESSAGE_LENGTH = 256; private @Nullable String message; @@ -77,7 +77,7 @@ public class Chat implements MinecraftPacket { } public static Chat createClientbound(Component component) { - return createClientbound(component, CHAT); + return createClientbound(component, CHAT_TYPE); } public static Chat createClientbound(Component component, byte type) { @@ -86,6 +86,6 @@ public class Chat implements MinecraftPacket { } public static Chat createServerbound(String message) { - return new Chat(message, CHAT); + return new Chat(message, CHAT_TYPE); } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/PlayerListItem.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/PlayerListItem.java index 6e3533084..0fa2e4c3c 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/PlayerListItem.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/PlayerListItem.java @@ -54,10 +54,7 @@ public class PlayerListItem implements MinecraftPacket { item.setProperties(ProtocolUtils.readProperties(buf)); item.setGameMode(ProtocolUtils.readVarInt(buf)); item.setLatency(ProtocolUtils.readVarInt(buf)); - boolean hasDisplayName = buf.readBoolean(); - if (hasDisplayName) { - item.setDisplayName(ComponentSerializers.JSON.deserialize(ProtocolUtils.readString(buf))); - } + item.setDisplayName(readOptionalComponent(buf)); break; } case UPDATE_GAMEMODE: @@ -66,19 +63,26 @@ public class PlayerListItem implements MinecraftPacket { case UPDATE_LATENCY: item.setLatency(ProtocolUtils.readVarInt(buf)); break; - case UPDATE_DISPLAY_NAME: { - boolean hasDisplayName = buf.readBoolean(); - if (hasDisplayName) { - item.setDisplayName(ComponentSerializers.JSON.deserialize(ProtocolUtils.readString(buf))); - } - } break; + case UPDATE_DISPLAY_NAME: + item.setDisplayName(readOptionalComponent(buf)); + break; case REMOVE_PLAYER: //Do nothing, all that is needed is the uuid break; + default: + throw new UnsupportedOperationException("Unknown action " + action); } } } + @Nullable + private static Component readOptionalComponent(ByteBuf buf) { + if (buf.readBoolean()) { + return ComponentSerializers.JSON.deserialize(ProtocolUtils.readString(buf)); + } + return null; + } + @Override public void encode(ByteBuf buf, ProtocolConstants.Direction direction, int protocolVersion) { ProtocolUtils.writeVarInt(buf, action); @@ -106,6 +110,8 @@ public class PlayerListItem implements MinecraftPacket { case REMOVE_PLAYER: //Do nothing, all that is needed is the uuid break; + default: + throw new UnsupportedOperationException("Unknown action " + action); } } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/StatusRequest.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/StatusRequest.java index e119bb574..cc2ad9e36 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/StatusRequest.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/StatusRequest.java @@ -14,12 +14,12 @@ public class StatusRequest implements MinecraftPacket { @Override public void decode(ByteBuf buf, ProtocolConstants.Direction direction, int protocolVersion) { - + // There is no additional data to decode. } @Override public void encode(ByteBuf buf, ProtocolConstants.Direction direction, int protocolVersion) { - + // There is no data to decode. } @Override diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/TitlePacket.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/TitlePacket.java index 58238862f..af9fd9a79 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/TitlePacket.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/TitlePacket.java @@ -51,6 +51,8 @@ public class TitlePacket implements MinecraftPacket { case HIDE: case RESET: break; + default: + throw new UnsupportedOperationException("Unknown action " + action); } } else { switch (action) { @@ -69,6 +71,8 @@ public class TitlePacket implements MinecraftPacket { case HIDE_OLD: case RESET_OLD: break; + default: + throw new UnsupportedOperationException("Unknown action " + action); } } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/FaviconSerializer.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/FaviconSerializer.java index 012c9fca0..21cdd6784 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/FaviconSerializer.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/FaviconSerializer.java @@ -7,7 +7,7 @@ import java.lang.reflect.Type; public class FaviconSerializer implements JsonSerializer, JsonDeserializer { @Override - public Favicon deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + public Favicon deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { return new Favicon(json.getAsString()); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/PluginMessageUtil.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/PluginMessageUtil.java index 67fc67ec9..c2d537f12 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/PluginMessageUtil.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/util/PluginMessageUtil.java @@ -2,9 +2,6 @@ package com.velocitypowered.proxy.protocol.util; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.velocitypowered.api.util.ModInfo; -import com.velocitypowered.proxy.connection.VelocityConstants; import com.velocitypowered.proxy.protocol.ProtocolConstants; import com.velocitypowered.proxy.protocol.ProtocolUtils; import com.velocitypowered.proxy.protocol.packet.PluginMessage; @@ -14,7 +11,6 @@ import io.netty.buffer.Unpooled; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.List; -import java.util.Optional; public class PluginMessageUtil { public static final String BRAND_CHANNEL_LEGACY = "MC|Brand"; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/server/ping/PingSessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/server/ping/PingSessionHandler.java index 84d43e611..415e51ce2 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/server/ping/PingSessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/server/ping/PingSessionHandler.java @@ -45,7 +45,7 @@ public class PingSessionHandler implements MinecraftSessionHandler { completed = true; connection.close(); - ServerPing ping = VelocityServer.GSON.fromJson(((StatusResponse) packet).getStatus(), ServerPing.class); + ServerPing ping = VelocityServer.GSON.fromJson(packet.getStatus(), ServerPing.class); result.complete(ping); return true; }