diff --git a/api/build.gradle.kts b/api/build.gradle.kts index a4cbd74193..3e769ef61a 100644 --- a/api/build.gradle.kts +++ b/api/build.gradle.kts @@ -59,7 +59,7 @@ tasks { val o = options as StandardJavadocDocletOptions o.encoding = "UTF-8" - o.source = "17" + o.source = "21" o.use() o.links( diff --git a/build.gradle.kts b/build.gradle.kts index a761de5f48..e01f345a9c 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -12,7 +12,7 @@ subprojects { java { toolchain { - languageVersion.set(JavaLanguageVersion.of(17)) + languageVersion.set(JavaLanguageVersion.of(21)) } } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index c44264face..e992265846 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -2,25 +2,25 @@ configurate3 = "3.7.3" configurate4 = "4.1.2" flare = "2.0.1" -log4j = "2.24.3" -netty = "4.2.5.Final" +log4j = "2.25.2" +netty = "4.2.6.Final" [plugins] fill = "io.papermc.fill.gradle:1.0.3" indra-publishing = "net.kyori.indra.publishing:2.0.6" -shadow = "com.gradleup.shadow:8.3.6" +shadow = "com.gradleup.shadow:9.1.0" spotless = "com.diffplug.spotless:6.25.0" [libraries] adventure-bom = "net.kyori:adventure-bom:4.24.0" adventure-text-serializer-json-legacy-impl = "net.kyori:adventure-text-serializer-json-legacy-impl:4.24.0" -adventure-facet = "net.kyori:adventure-platform-facet:4.3.4" +adventure-facet = "net.kyori:adventure-platform-facet:4.4.1" asm = "org.ow2.asm:asm:9.8" auto-service = "com.google.auto.service:auto-service:1.0.1" auto-service-annotations = "com.google.auto.service:auto-service-annotations:1.0.1" brigadier = "com.velocitypowered:velocity-brigadier:1.0.0-SNAPSHOT" -bstats = "org.bstats:bstats-base:3.0.3" -caffeine = "com.github.ben-manes.caffeine:caffeine:3.1.8" +bstats = "org.bstats:bstats-base:3.1.0" +caffeine = "com.github.ben-manes.caffeine:caffeine:3.2.2" checker-qual = "org.checkerframework:checker-qual:3.42.0" checkstyle = "com.puppycrawl.tools:checkstyle:10.9.3" completablefutures = "com.spotify:completable-futures:0.3.6" @@ -34,13 +34,13 @@ disruptor = "com.lmax:disruptor:4.0.0" fastutil = "it.unimi.dsi:fastutil:8.5.15" flare-core = { module = "space.vectrix.flare:flare", version.ref = "flare" } flare-fastutil = { module = "space.vectrix.flare:flare-fastutil", version.ref = "flare" } -jline = "org.jline:jline-terminal-jansi:3.30.2" +jline = "org.jline:jline-terminal-jansi:3.30.6" jopt = "net.sf.jopt-simple:jopt-simple:5.0.4" junit = "org.junit.jupiter:junit-jupiter:5.10.2" jspecify = "org.jspecify:jspecify:0.3.0" kyori-ansi = "net.kyori:ansi:1.1.1" -guava = "com.google.guava:guava:25.1-jre" -gson = "com.google.code.gson:gson:2.10.1" +guava = "com.google.guava:guava:33.3.1-jre" +gson = "com.google.code.gson:gson:2.11.0" guice = "com.google.inject:guice:6.0.0" lmbda = "org.lanternpowered:lmbda:2.0.0" log4j-api = { module = "org.apache.logging.log4j:log4j-api", version.ref = "log4j" } @@ -56,7 +56,7 @@ netty-handler = { module = "io.netty:netty-handler", version.ref = "netty" } netty-transport-native-epoll = { module = "io.netty:netty-transport-native-epoll", version.ref = "netty" } netty-transport-native-kqueue = { module = "io.netty:netty-transport-native-kqueue", version.ref = "netty" } netty-transport-native-iouring = { module = "io.netty:netty-transport-native-io_uring", version.ref = "netty" } -nightconfig = "com.electronwill.night-config:toml:3.6.7" +nightconfig = "com.electronwill.night-config:toml:3.8.3" slf4j = "org.slf4j:slf4j-api:2.0.17" snakeyaml = "org.yaml:snakeyaml:1.33" spotbugs-annotations = "com.github.spotbugs:spotbugs-annotations:4.7.3" diff --git a/proxy/build.gradle.kts b/proxy/build.gradle.kts index 1559f5fda2..ebdef90aeb 100644 --- a/proxy/build.gradle.kts +++ b/proxy/build.gradle.kts @@ -10,7 +10,7 @@ plugins { application { mainClass.set("com.velocitypowered.proxy.Velocity") - applicationDefaultJvmArgs += listOf("-Dvelocity.packet-decode-logging=true"); + applicationDefaultJvmArgs += listOf("-Dvelocity.packet-decode-logging=true") } tasks { @@ -28,6 +28,9 @@ tasks { shadowJar { transform(Log4j2PluginsCacheFileTransformer::class.java) + filesMatching("META-INF/org/apache/logging/log4j/core/config/plugins/**") { + duplicatesStrategy = DuplicatesStrategy.INCLUDE + } // Exclude all the collection types we don"t intend to use exclude("it/unimi/dsi/fastutil/booleans/**") @@ -131,7 +134,6 @@ fill { dependencies { implementation(project(":velocity-api")) implementation(project(":velocity-native")) - implementation(project(":velocity-proxy-log4j2-plugin")) implementation(libs.bundles.log4j) implementation(libs.kyori.ansi) @@ -168,4 +170,5 @@ dependencies { testImplementation(libs.mockito) annotationProcessor(libs.auto.service) + annotationProcessor(libs.log4j.core) } diff --git a/proxy/log4j2-plugin/build.gradle.kts b/proxy/log4j2-plugin/build.gradle.kts deleted file mode 100644 index 0a193944a8..0000000000 --- a/proxy/log4j2-plugin/build.gradle.kts +++ /dev/null @@ -1,4 +0,0 @@ -dependencies { - implementation(libs.bundles.log4j) - annotationProcessor(libs.log4j.core) -} \ No newline at end of file diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/SuggestionsProvider.java b/proxy/src/main/java/com/velocitypowered/proxy/command/SuggestionsProvider.java index 93088cf623..9c65c023ae 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/SuggestionsProvider.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/SuggestionsProvider.java @@ -344,7 +344,7 @@ private ParseResults parseHints(final CommandNode node, final StringReader return 0; }); } - return potentials.get(0); + return potentials.getFirst(); } return new ParseResults<>(contextSoFar, originalReader, Collections.emptyMap()); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/VelocityCommandManager.java b/proxy/src/main/java/com/velocitypowered/proxy/command/VelocityCommandManager.java index 095445bf0b..8e5a9c95a7 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/VelocityCommandManager.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/VelocityCommandManager.java @@ -140,7 +140,7 @@ public void register(final CommandMeta meta, final Command command) { command + " implements multiple registrable Command subinterfaces: " + implementedInterfaces); } else { - this.internalRegister(commandRegistrars.get(0), command, meta); + this.internalRegister(commandRegistrars.getFirst(), command, meta); } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/VelocityCommands.java b/proxy/src/main/java/com/velocitypowered/proxy/command/VelocityCommands.java index 3c2ad19916..1e4a01ce21 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/VelocityCommands.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/VelocityCommands.java @@ -70,33 +70,34 @@ public static CommandNode wrap(final CommandNode d maybeCommand = VelocityBrigadierCommandWrapper.wrap(delegate.getCommand(), registrant); } - if (delegate instanceof LiteralCommandNode lcn) { - var literalBuilder = shallowCopyAsBuilder(lcn, delegate.getName(), true); - literalBuilder.executes(maybeCommand); - // we also need to wrap any children - for (final CommandNode child : delegate.getChildren()) { - literalBuilder.then(wrap(child, registrant)); + return switch (delegate) { + case LiteralCommandNode lcn -> { + var literalBuilder = shallowCopyAsBuilder(lcn, delegate.getName(), true); + literalBuilder.executes(maybeCommand); + // we also need to wrap any children + for (final CommandNode child : delegate.getChildren()) { + literalBuilder.then(wrap(child, registrant)); + } + if (delegate.getRedirect() != null) { + literalBuilder.redirect(wrap(delegate.getRedirect(), registrant)); + } + yield literalBuilder.build(); } - if (delegate.getRedirect() != null) { - literalBuilder.redirect(wrap(delegate.getRedirect(), registrant)); + case VelocityArgumentCommandNode vacn -> vacn.withCommand(maybeCommand) + .withRedirect(delegate.getRedirect() != null ? wrap(delegate.getRedirect(), registrant) : null); + case ArgumentCommandNode node -> { + var argBuilder = node.createBuilder().executes(maybeCommand); + // we also need to wrap any children + for (final CommandNode child : delegate.getChildren()) { + argBuilder.then(wrap(child, registrant)); + } + if (delegate.getRedirect() != null) { + argBuilder.redirect(wrap(delegate.getRedirect(), registrant)); + } + yield argBuilder.build(); } - return literalBuilder.build(); - } else if (delegate instanceof VelocityArgumentCommandNode vacn) { - return vacn.withCommand(maybeCommand) - .withRedirect(delegate.getRedirect() != null ? wrap(delegate.getRedirect(), registrant) : null); - } else if (delegate instanceof ArgumentCommandNode) { - var argBuilder = delegate.createBuilder().executes(maybeCommand); - // we also need to wrap any children - for (final CommandNode child : delegate.getChildren()) { - argBuilder.then(wrap(child, registrant)); - } - if (delegate.getRedirect() != null) { - argBuilder.redirect(wrap(delegate.getRedirect(), registrant)); - } - return argBuilder.build(); - } else { - throw new IllegalArgumentException("Unsupported node type: " + delegate.getClass()); - } + default -> throw new IllegalArgumentException("Unsupported node type: " + delegate.getClass()); + }; } // Normalization @@ -133,7 +134,7 @@ public static String readAlias(final List> nodes) if (nodes.isEmpty()) { throw new IllegalArgumentException("Cannot read alias from empty node list"); } - return nodes.get(0).getNode().getName(); + return nodes.getFirst().getNode().getName(); } public static final String ARGS_NODE_NAME = "arguments"; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/brigadier/VelocityArgumentCommandNode.java b/proxy/src/main/java/com/velocitypowered/proxy/command/brigadier/VelocityArgumentCommandNode.java index 03ba6d35e5..e5382d000d 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/brigadier/VelocityArgumentCommandNode.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/brigadier/VelocityArgumentCommandNode.java @@ -118,14 +118,12 @@ public boolean equals(final Object o) { if (this == o) { return true; } - if (!(o instanceof VelocityArgumentCommandNode)) { + if (!(o instanceof VelocityArgumentCommandNode that)) { return false; } - if (!super.equals(o)) { + if (!super.equals(that)) { return false; } - - final VelocityArgumentCommandNode that = (VelocityArgumentCommandNode) o; return this.type.equals(that.type); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/VelocityCommand.java b/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/VelocityCommand.java index 6b233b8745..101a506990 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/VelocityCommand.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/command/builtin/VelocityCommand.java @@ -242,7 +242,7 @@ private TextComponent componentForPlugin(PluginDescription description) { hoverText.append(Component.newline()); if (description.getAuthors().size() == 1) { hoverText.append(Component.translatable("velocity.command.plugin-tooltip-author", - Component.text(description.getAuthors().get(0)))); + Component.text(description.getAuthors().getFirst()))); } else { hoverText.append( Component.translatable("velocity.command.plugin-tooltip-author", diff --git a/proxy/src/main/java/com/velocitypowered/proxy/config/VelocityConfiguration.java b/proxy/src/main/java/com/velocitypowered/proxy/config/VelocityConfiguration.java index dfd007acd1..a1a701f228 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/config/VelocityConfiguration.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/config/VelocityConfiguration.java @@ -156,19 +156,16 @@ public boolean validate() { } switch (playerInfoForwardingMode) { - case NONE: - logger.warn("Player info forwarding is disabled! All players will appear to be connecting " + case NONE -> logger.warn("Player info forwarding is disabled! All players will appear to be connecting " + "from the proxy and will have offline-mode UUIDs."); - break; - case MODERN: - case BUNGEEGUARD: + case MODERN, BUNGEEGUARD -> { if (forwardingSecret == null || forwardingSecret.length == 0) { logger.error("You don't have a forwarding secret set. This is required for security."); valid = false; } - break; - default: - break; + } + default -> { + } } if (servers.getServers().isEmpty()) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/MinecraftConnection.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/MinecraftConnection.java index 3d7ed44886..f7de55e0fd 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/MinecraftConnection.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/MinecraftConnection.java @@ -153,13 +153,13 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception if (msg instanceof MinecraftPacket pkt) { if (!pkt.handle(activeSessionHandler)) { - activeSessionHandler.handleGeneric((MinecraftPacket) msg); + activeSessionHandler.handleGeneric(pkt); } } else if (msg instanceof HAProxyMessage proxyMessage) { this.remoteAddress = new InetSocketAddress(proxyMessage.sourceAddress(), proxyMessage.sourcePort()); - } else if (msg instanceof ByteBuf) { - activeSessionHandler.handleUnknown((ByteBuf) msg); + } else if (msg instanceof ByteBuf buf) { + activeSessionHandler.handleUnknown(buf); } } finally { ReferenceCountUtil.release(msg); 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 eb9c9bca65..18adfa0cfd 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 @@ -450,8 +450,8 @@ public boolean handle(ClientboundCookieRequestPacket packet) { @Override public void handleGeneric(MinecraftPacket packet) { - if (packet instanceof PluginMessagePacket) { - ((PluginMessagePacket) packet).retain(); + if (packet instanceof PluginMessagePacket pluginMessage) { + pluginMessage.retain(); } playerConnection.delayedWrite(packet); if (++packetsFlushed >= MAXIMUM_PACKETS_TO_FLUSH) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BungeeCordMessageResponder.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BungeeCordMessageResponder.java index a2ea94d626..50edfaee5f 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BungeeCordMessageResponder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/BungeeCordMessageResponder.java @@ -344,66 +344,30 @@ boolean process(PluginMessagePacket message) { return false; } - ByteBufDataInput in = new ByteBufDataInput(message.content()); - String subChannel = in.readUTF(); + final ByteBufDataInput in = new ByteBufDataInput(message.content()); + final String subChannel = in.readUTF(); switch (subChannel) { - case "GetPlayerServer": - this.processGetPlayerServer(in); - break; - case "ForwardToPlayer": - this.processForwardToPlayer(in); - break; - case "Forward": - this.processForwardToServer(in); - break; - case "Connect": - this.processConnect(in); - break; - case "ConnectOther": - this.processConnectOther(in); - break; - case "IP": - this.processIp(in); - break; - case "PlayerCount": - this.processPlayerCount(in); - break; - case "PlayerList": - this.processPlayerList(in); - break; - case "GetServers": - this.processGetServers(); - break; - case "Message": - this.processMessage(in); - break; - case "MessageRaw": - this.processMessageRaw(in); - break; - case "GetServer": - this.processGetServer(); - break; - case "UUID": - this.processUuid(); - break; - case "UUIDOther": - this.processUuidOther(in); - break; - case "IPOther": - this.processIpOther(in); - break; - case "ServerIP": - this.processServerIp(in); - break; - case "KickPlayer": - this.processKick(in); - break; - case "KickPlayerRaw": - this.processKickRaw(in); - break; - default: - // Do nothing, unknown command - break; + case "GetPlayerServer" -> this.processGetPlayerServer(in); + case "ForwardToPlayer" -> this.processForwardToPlayer(in); + case "Forward" -> this.processForwardToServer(in); + case "Connect" -> this.processConnect(in); + case "ConnectOther" -> this.processConnectOther(in); + case "IP" -> this.processIp(in); + case "PlayerCount" -> this.processPlayerCount(in); + case "PlayerList" -> this.processPlayerList(in); + case "GetServers" -> this.processGetServers(); + case "Message" -> this.processMessage(in); + case "MessageRaw" -> this.processMessageRaw(in); + case "GetServer" -> this.processGetServer(); + case "UUID" -> this.processUuid(); + case "UUIDOther" -> this.processUuidOther(in); + case "IPOther" -> this.processIpOther(in); + case "ServerIP" -> this.processServerIp(in); + case "KickPlayer" -> this.processKick(in); + case "KickPlayerRaw" -> this.processKickRaw(in); + default -> { + // Do nothing, unknown command + } } return true; diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/TransitionSessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/TransitionSessionHandler.java index a74f7c56aa..e713769a6e 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/TransitionSessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/backend/TransitionSessionHandler.java @@ -122,9 +122,8 @@ public boolean handle(JoinGamePacket packet) { // Change the client to use the ClientPlaySessionHandler if required. ClientPlaySessionHandler playHandler; if (player.getConnection() - .getActiveSessionHandler() instanceof ClientPlaySessionHandler) { - playHandler = - (ClientPlaySessionHandler) player.getConnection().getActiveSessionHandler(); + .getActiveSessionHandler() instanceof ClientPlaySessionHandler sessionHandler) { + playHandler = sessionHandler; } else { playHandler = new ClientPlaySessionHandler(server, player); player.getConnection().setActiveSessionHandler(StateRegistry.PLAY, playHandler); 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 71ebd7bc78..c40a7aaac6 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 @@ -180,9 +180,8 @@ private void startHandshake() { handshake.setServerAddress(createBungeeGuardForwardingAddress(secret)); } else if (proxyPlayer.getConnection().getType() == ConnectionTypes.LEGACY_FORGE) { handshake.setServerAddress(playerVhost + HANDSHAKE_HOSTNAME_TOKEN); - } else if (proxyPlayer.getConnection().getType() instanceof ModernForgeConnectionType) { - handshake.setServerAddress(playerVhost + ((ModernForgeConnectionType) proxyPlayer - .getConnection().getType()).getModernToken()); + } else if (proxyPlayer.getConnection().getType() instanceof ModernForgeConnectionType forgeConnection) { + handshake.setServerAddress(playerVhost + forgeConnection.getModernToken()); } else { handshake.setServerAddress(playerVhost); } 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 44fe95c557..cf4060f405 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 @@ -808,63 +808,58 @@ private void handleKickEvent(KickedFromServerEvent originalEvent, Component frie return; } - if (event.getResult() instanceof final DisconnectPlayer res) { - disconnect(res.getReasonComponent()); - } else if (event.getResult() instanceof final RedirectPlayer res) { - createConnectionRequest(res.getServer(), previousConnection).connect() - .whenCompleteAsync((status, throwable) -> { - if (throwable != null) { - handleConnectionException( - status != null ? status.getAttemptedConnection() : res.getServer(), throwable, - true); - return; - } - - switch (status.getStatus()) { - // Impossible/nonsensical cases - case ALREADY_CONNECTED: - logger.error("{}: already connected to {}", this, - status.getAttemptedConnection().getServerInfo().getName()); - break; - case CONNECTION_IN_PROGRESS: - // Fatal case - case CONNECTION_CANCELLED: - Component fallbackMsg = res.getMessageComponent(); - if (fallbackMsg == null) { - fallbackMsg = friendlyReason; + switch (event.getResult()) { + case DisconnectPlayer res -> disconnect(res.getReasonComponent()); + case RedirectPlayer res -> createConnectionRequest(res.getServer(), previousConnection).connect() + .whenCompleteAsync((status, throwable) -> { + if (throwable != null) { + handleConnectionException( + status != null ? status.getAttemptedConnection() : res.getServer(), throwable, + true); + return; } - disconnect(status.getReasonComponent().orElse(fallbackMsg)); - break; - case SERVER_DISCONNECTED: - Component reason = status.getReasonComponent() - .orElse(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR); - handleConnectionException(res.getServer(), - DisconnectPacket.create(reason, getProtocolVersion(), connection.getState()), - ((Impl) status).isSafe()); - break; - case SUCCESS: - Component requestedMessage = res.getMessageComponent(); - if (requestedMessage == null) { - requestedMessage = friendlyReason; - } - if (requestedMessage != Component.empty()) { - sendMessage(requestedMessage); + + switch (status.getStatus()) { + // Impossible/nonsensical cases + case ALREADY_CONNECTED -> logger.error("{}: already connected to {}", this, + status.getAttemptedConnection().getServerInfo().getName()); + case CONNECTION_IN_PROGRESS, CONNECTION_CANCELLED -> { + Component fallbackMsg = res.getMessageComponent(); + if (fallbackMsg == null) { + fallbackMsg = friendlyReason; + } + disconnect(status.getReasonComponent().orElse(fallbackMsg)); + } + case SERVER_DISCONNECTED -> { + Component reason = status.getReasonComponent() + .orElse(ConnectionMessages.INTERNAL_SERVER_CONNECTION_ERROR); + handleConnectionException(res.getServer(), + DisconnectPacket.create(reason, getProtocolVersion(), connection.getState()), + ((Impl) status).isSafe()); + } + case SUCCESS -> { + Component requestedMessage = res.getMessageComponent(); + if (requestedMessage == null) { + requestedMessage = friendlyReason; + } + if (requestedMessage != Component.empty()) { + sendMessage(requestedMessage); + } + } + default -> { + // The only remaining value is successful (no need to do anything!) + } } - break; - default: - // The only remaining value is successful (no need to do anything!) - break; - } - }, connection.eventLoop()); - } else if (event.getResult() instanceof final Notify res) { - if (event.kickedDuringServerConnect() && previousConnection != null) { - sendMessage(res.getMessageComponent()); - } else { - disconnect(res.getMessageComponent()); + }, connection.eventLoop()); + case Notify res -> { + if (event.kickedDuringServerConnect() && previousConnection != null) { + sendMessage(res.getMessageComponent()); + } else { + disconnect(res.getMessageComponent()); + } } - } else { // In case someone gets creative, assume we want to disconnect the player. - disconnect(friendlyReason); + default -> disconnect(friendlyReason); } }, connection.eventLoop()); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/InitialLoginSessionHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/InitialLoginSessionHandler.java index 00187d3470..92f14191ca 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/client/InitialLoginSessionHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/client/InitialLoginSessionHandler.java @@ -214,6 +214,7 @@ public boolean handle(EncryptionResponsePacket packet) { server.getVersion().getName() + "/" + server.getVersion().getVersion()) .uri(URI.create(url)) .build(); + //noinspection resource final HttpClient httpClient = server.createHttpClient(); httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString()) .whenCompleteAsync((response, throwable) -> { @@ -268,14 +269,12 @@ public boolean handle(EncryptionResponsePacket packet) { } }, mcConnection.eventLoop()) .thenRun(() -> { - if (httpClient instanceof final AutoCloseable closeable) { - try { - closeable.close(); - } catch (Exception e) { - // In Java 21, the HttpClient does not throw any Exception - // when trying to clean its resources, so this should not happen - logger.error("An unknown error occurred while trying to close an HttpClient", e); - } + try { + httpClient.close(); + } catch (Exception e) { + // In Java 21, the HttpClient does not throw any Exception + // when trying to clean its resources, so this should not happen + logger.error("An unknown error occurred while trying to close an HttpClient", e); } }); } catch (GeneralSecurityException e) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/player/resourcepack/handler/ModernResourcePackHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/player/resourcepack/handler/ModernResourcePackHandler.java index 077ce701d5..f0fd5e084c 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/player/resourcepack/handler/ModernResourcePackHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/player/resourcepack/handler/ModernResourcePackHandler.java @@ -94,7 +94,7 @@ public void queueResourcePack(final @NotNull ResourcePackInfo info) { this.outstandingResourcePacks.get(info.getId()); outstandingResourcePacks.add(info); if (outstandingResourcePacks.size() == 1) { - tickResourcePackQueue(outstandingResourcePacks.get(0).getId()); + tickResourcePackQueue(outstandingResourcePacks.getFirst().getId()); } } @@ -111,7 +111,7 @@ private void tickResourcePackQueue(final @NotNull UUID uuid) { final List outstandingResourcePacks = this.outstandingResourcePacks.get(uuid); if (!outstandingResourcePacks.isEmpty()) { - sendResourcePackRequestPacket(outstandingResourcePacks.get(0)); + sendResourcePackRequestPacket(outstandingResourcePacks.getFirst()); } } @@ -124,7 +124,7 @@ public boolean onResourcePackResponse( this.outstandingResourcePacks.get(uuid); final boolean peek = bundle.status().isIntermediate(); final ResourcePackInfo queued = outstandingResourcePacks.isEmpty() ? null : - peek ? outstandingResourcePacks.get(0) : outstandingResourcePacks.remove(0); + peek ? outstandingResourcePacks.getFirst() : outstandingResourcePacks.removeFirst(); server.getEventManager() .fire(new PlayerResourcePackStatusEvent(this.player, uuid, bundle.status(), queued)) diff --git a/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ServerListPingHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ServerListPingHandler.java index d1f2b0db16..d772da1d88 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ServerListPingHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/connection/util/ServerListPingHandler.java @@ -99,58 +99,53 @@ private CompletableFuture attemptPingPassthrough(VelocityInboundConn CompletableFuture> pingResponses = CompletableFutures.successfulAsList(pings, (ex) -> fallback); - switch (mode) { - case ALL: - return pingResponses.thenApply(responses -> { - // Find the first non-fallback - for (ServerPing response : responses) { - if (response == fallback) { - continue; - } - return response; + return switch (mode) { + case ALL -> pingResponses.thenApply(responses -> { + // Find the first non-fallback + for (ServerPing response : responses) { + if (response == fallback) { + continue; } - return fallback; - }); - case MODS: - return pingResponses.thenApply(responses -> { - // Find the first non-fallback that contains a mod list - for (ServerPing response : responses) { - if (response == fallback) { - continue; - } - Optional modInfo = response.getModinfo(); - if (modInfo.isPresent()) { - return fallback.asBuilder().mods(modInfo.get()).build(); - } + return response; + } + return fallback; + }); + case MODS -> pingResponses.thenApply(responses -> { + // Find the first non-fallback that contains a mod list + for (ServerPing response : responses) { + if (response == fallback) { + continue; } - return fallback; - }); - case DESCRIPTION: - return pingResponses.thenApply(responses -> { - // Find the first non-fallback. If it includes a modlist, add it too. - for (ServerPing response : responses) { - if (response == fallback) { - continue; - } - - if (response.getDescriptionComponent() == null) { - continue; - } - - return new ServerPing( - fallback.getVersion(), - fallback.getPlayers().orElse(null), - response.getDescriptionComponent(), - fallback.getFavicon().orElse(null), - response.getModinfo().orElse(null) - ); + Optional modInfo = response.getModinfo(); + if (modInfo.isPresent()) { + return fallback.asBuilder().mods(modInfo.get()).build(); + } + } + return fallback; + }); + case DESCRIPTION -> pingResponses.thenApply(responses -> { + // Find the first non-fallback. If it includes a modlist, add it too. + for (ServerPing response : responses) { + if (response == fallback) { + continue; } - return fallback; - }); + if (response.getDescriptionComponent() == null) { + continue; + } + + return new ServerPing( + fallback.getVersion(), + fallback.getPlayers().orElse(null), + response.getDescriptionComponent(), + fallback.getFavicon().orElse(null), + response.getModinfo().orElse(null) + ); + } + return fallback; + }); // Not possible, but covered for completeness. - default: - return CompletableFuture.completedFuture(fallback); - } + default -> CompletableFuture.completedFuture(fallback); + }; } /** 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 90b6292f79..fd7d881d99 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/console/VelocityConsole.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/console/VelocityConsole.java @@ -33,6 +33,7 @@ import net.kyori.adventure.platform.facet.FacetPointers; import net.kyori.adventure.platform.facet.FacetPointers.Type; import net.kyori.adventure.pointer.Pointers; +import net.kyori.adventure.pointer.PointersSupplier; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.logger.slf4j.ComponentLogger; @@ -59,11 +60,11 @@ public final class VelocityConsole extends SimpleTerminalConsole implements Cons private final VelocityServer server; private PermissionFunction permissionFunction = ALWAYS_TRUE; - private final @NotNull Pointers pointers = ConsoleCommandSource.super.pointers().toBuilder() - .withDynamic(PermissionChecker.POINTER, this::getPermissionChecker) - .withDynamic(Identity.LOCALE, () -> ClosestLocaleMatcher.INSTANCE + private static final @NotNull PointersSupplier POINTERS = PointersSupplier.builder() + .resolving(PermissionChecker.POINTER, VelocityConsole::getPermissionChecker) + .resolving(Identity.LOCALE, (console) -> ClosestLocaleMatcher.INSTANCE .lookupClosest(Locale.getDefault())) - .withStatic(FacetPointers.TYPE, Type.CONSOLE) + .resolving(FacetPointers.TYPE, (console) -> Type.CONSOLE) .build(); public VelocityConsole(VelocityServer server) { @@ -153,6 +154,6 @@ protected void shutdown() { @Override public @NotNull Pointers pointers() { - return pointers; + return POINTERS.view(this); } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/network/netty/SeparatePoolInetNameResolver.java b/proxy/src/main/java/com/velocitypowered/proxy/network/netty/SeparatePoolInetNameResolver.java index 2997d84087..5fc309ae9a 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/network/netty/SeparatePoolInetNameResolver.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/network/netty/SeparatePoolInetNameResolver.java @@ -71,7 +71,7 @@ public SeparatePoolInetNameResolver(EventExecutor executor) { protected void doResolve(String inetHost, Promise promise) throws Exception { List addresses = cache.getIfPresent(inetHost); if (addresses != null) { - promise.trySuccess(addresses.get(0)); + promise.trySuccess(addresses.getFirst()); return; } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/java/JavaPluginLoader.java b/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/java/JavaPluginLoader.java index d1df777d35..5b69e49a7a 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/java/JavaPluginLoader.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/plugin/loader/java/JavaPluginLoader.java @@ -83,7 +83,7 @@ public PluginDescription loadCandidate(Path source) throws Exception { @Override public PluginDescription createPluginFromCandidate(PluginDescription candidate) throws Exception { - if (!(candidate instanceof JavaVelocityPluginDescriptionCandidate)) { + if (!(candidate instanceof JavaVelocityPluginDescriptionCandidate candidateInst)) { throw new IllegalArgumentException("Description provided isn't of the Java plugin loader"); } @@ -93,8 +93,6 @@ public PluginDescription createPluginFromCandidate(PluginDescription candidate) PluginClassLoader loader = new PluginClassLoader(new URL[]{pluginJarUrl}); loader.addToClassloaders(); - JavaVelocityPluginDescriptionCandidate candidateInst = - (JavaVelocityPluginDescriptionCandidate) candidate; Class mainClass = loader.loadClass(candidateInst.getMainClass()); return createDescription(candidateInst, mainClass); } @@ -102,11 +100,10 @@ public PluginDescription createPluginFromCandidate(PluginDescription candidate) @Override public Module createModule(PluginContainer container) { PluginDescription description = container.getDescription(); - if (!(description instanceof JavaVelocityPluginDescription)) { + if (!(description instanceof JavaVelocityPluginDescription javaDescription)) { throw new IllegalArgumentException("Description provided isn't of the Java plugin loader"); } - JavaVelocityPluginDescription javaDescription = (JavaVelocityPluginDescription) description; Optional source = javaDescription.getSource(); if (source.isEmpty()) { @@ -118,24 +115,23 @@ public Module createModule(PluginContainer container) { @Override public void createPlugin(PluginContainer container, Module... modules) { - if (!(container instanceof VelocityPluginContainer)) { + if (!(container instanceof VelocityPluginContainer pluginContainer)) { throw new IllegalArgumentException("Container provided isn't of the Java plugin loader"); } - PluginDescription description = container.getDescription(); - if (!(description instanceof JavaVelocityPluginDescription)) { + PluginDescription description = pluginContainer.getDescription(); + if (!(description instanceof JavaVelocityPluginDescription javaPluginDescription)) { throw new IllegalArgumentException("Description provided isn't of the Java plugin loader"); } Injector injector = Guice.createInjector(modules); - Object instance = injector - .getInstance(((JavaVelocityPluginDescription) description).getMainClass()); + Object instance = injector.getInstance(javaPluginDescription.getMainClass()); if (instance == null) { throw new IllegalStateException( "Got nothing from injector for plugin " + description.getId()); } - ((VelocityPluginContainer) container).setInstance(instance); + pluginContainer.setInstance(instance); } private Optional getSerializedPluginInfo(Path source) @@ -145,22 +141,23 @@ private Optional getSerializedPluginInfo(Path sourc new BufferedInputStream(Files.newInputStream(source)))) { JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { - if (entry.getName().equals("velocity-plugin.json")) { - try (Reader pluginInfoReader = new InputStreamReader(in, StandardCharsets.UTF_8)) { - return Optional.of(VelocityServer.GENERAL_GSON.fromJson(pluginInfoReader, - SerializedPluginDescription.class)); + switch (entry.getName()) { + case "velocity-plugin.json" -> { + try (Reader pluginInfoReader = new InputStreamReader(in, StandardCharsets.UTF_8)) { + return Optional.of(VelocityServer.GENERAL_GSON.fromJson(pluginInfoReader, + SerializedPluginDescription.class)); + } + } + case "paper-plugin.yml", "plugin.yml", "bungee.yml" -> foundBungeeBukkitPluginFile = true; + default -> { } - } - - if (entry.getName().equals("plugin.yml") || entry.getName().equals("bungee.yml")) { - foundBungeeBukkitPluginFile = true; } } if (foundBungeeBukkitPluginFile) { throw new InvalidPluginException("The plugin file " + source.getFileName() + " appears to " - + "be a Bukkit or BungeeCord plugin. Velocity does not support Bukkit or BungeeCord " - + "plugins."); + + "be a Paper, Bukkit or BungeeCord plugin. Velocity does not support plugins from these " + + "platforms."); } return Optional.empty(); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/GameSpyQueryHandler.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/GameSpyQueryHandler.java index 57c0b318a2..b22a24428d 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/GameSpyQueryHandler.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/netty/GameSpyQueryHandler.java @@ -119,7 +119,7 @@ protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throw int sessionId = queryMessage.readInt(); switch (type) { - case QUERY_TYPE_HANDSHAKE: { + case QUERY_TYPE_HANDSHAKE -> { // Generate new challenge token and put it into the sessions cache int challengeToken = random.nextInt(); sessions.put(senderAddress, challengeToken); @@ -132,10 +132,9 @@ protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throw DatagramPacket responsePacket = new DatagramPacket(queryResponse, msg.sender()); ctx.writeAndFlush(responsePacket, ctx.voidPromise()); - break; } - case QUERY_TYPE_STAT: { + case QUERY_TYPE_STAT -> { // Check if query was done with session previously generated using a handshake packet int challengeToken = queryMessage.readInt(); Integer session = sessions.getIfPresent(senderAddress); @@ -190,10 +189,10 @@ protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throw "Exception while writing GS4 response for query from {}", senderAddress, ex); return null; }); - break; } - default: - // Invalid query type - just don't respond + default -> { + // Invalid query type - just don't respond + } } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/AvailableCommandsPacket.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/AvailableCommandsPacket.java index 08fe23b2f4..4bddcab4f6 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/AvailableCommandsPacket.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/AvailableCommandsPacket.java @@ -25,7 +25,6 @@ import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.builder.RequiredArgumentBuilder; import com.mojang.brigadier.context.CommandContext; -import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.suggestion.SuggestionProvider; import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.SuggestionsBuilder; @@ -331,12 +330,10 @@ public String toString() { .add("redirectTo", redirectTo); if (args != null) { - if (args instanceof LiteralArgumentBuilder) { - helper.add("argsLabel", - ((LiteralArgumentBuilder) args).getLiteral()); - } else if (args instanceof RequiredArgumentBuilder) { - helper.add("argsName", - ((RequiredArgumentBuilder) args).getName()); + if (args instanceof LiteralArgumentBuilder literal) { + helper.add("argsLabel", literal.getLiteral()); + } else if (args instanceof RequiredArgumentBuilder required) { + helper.add("argsName", required.getName()); } } @@ -348,17 +345,11 @@ public String toString() { * A placeholder {@link SuggestionProvider} used internally to preserve the suggestion provider * name. */ - public static class ProtocolSuggestionProvider implements SuggestionProvider { - - private final String name; - - public ProtocolSuggestionProvider(String name) { - this.name = name; - } + public record ProtocolSuggestionProvider(String name) implements SuggestionProvider { @Override public CompletableFuture getSuggestions(CommandContext context, - SuggestionsBuilder builder) throws CommandSyntaxException { + SuggestionsBuilder builder) { return builder.buildFuture(); } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/BossBarPacket.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/BossBarPacket.java index cc4c267154..d7748efffe 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/BossBarPacket.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/BossBarPacket.java @@ -207,30 +207,22 @@ public void decode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersi this.uuid = ProtocolUtils.readUuid(buf); this.action = ProtocolUtils.readVarInt(buf); switch (action) { - case ADD: + case ADD -> { this.name = ComponentHolder.read(buf, version); this.percent = buf.readFloat(); this.color = ProtocolUtils.readVarInt(buf); this.overlay = ProtocolUtils.readVarInt(buf); this.flags = buf.readUnsignedByte(); - break; - case REMOVE: - break; - case UPDATE_PERCENT: - this.percent = buf.readFloat(); - break; - case UPDATE_NAME: - this.name = ComponentHolder.read(buf, version); - break; - case UPDATE_STYLE: + } + case REMOVE -> {} + case UPDATE_PERCENT -> this.percent = buf.readFloat(); + case UPDATE_NAME -> this.name = ComponentHolder.read(buf, version); + case UPDATE_STYLE -> { this.color = ProtocolUtils.readVarInt(buf); this.overlay = ProtocolUtils.readVarInt(buf); - break; - case UPDATE_PROPERTIES: - this.flags = buf.readUnsignedByte(); - break; - default: - throw new UnsupportedOperationException("Unknown action " + action); + } + case UPDATE_PROPERTIES -> this.flags = buf.readUnsignedByte(); + default -> throw new UnsupportedOperationException("Unknown action " + action); } } @@ -242,36 +234,30 @@ public void encode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersi ProtocolUtils.writeUuid(buf, uuid); ProtocolUtils.writeVarInt(buf, action); switch (action) { - case ADD: - if (name == null) { - throw new IllegalStateException("No name specified!"); - } - name.write(buf); - buf.writeFloat(percent); - ProtocolUtils.writeVarInt(buf, color); - ProtocolUtils.writeVarInt(buf, overlay); - buf.writeByte(flags); - break; - case REMOVE: - break; - case UPDATE_PERCENT: - buf.writeFloat(percent); - break; - case UPDATE_NAME: - if (name == null) { - throw new IllegalStateException("No name specified!"); - } - name.write(buf); - break; - case UPDATE_STYLE: + case ADD -> { + if (name == null) { + throw new IllegalStateException("No name specified!"); + } + name.write(buf); + buf.writeFloat(percent); + ProtocolUtils.writeVarInt(buf, color); + ProtocolUtils.writeVarInt(buf, overlay); + buf.writeByte(flags); + } + case REMOVE -> {} + case UPDATE_PERCENT -> buf.writeFloat(percent); + case UPDATE_NAME -> { + if (name == null) { + throw new IllegalStateException("No name specified!"); + } + name.write(buf); + } + case UPDATE_STYLE -> { ProtocolUtils.writeVarInt(buf, color); ProtocolUtils.writeVarInt(buf, overlay); - break; - case UPDATE_PROPERTIES: - buf.writeByte(flags); - break; - default: - throw new UnsupportedOperationException("Unknown action " + action); + } + case UPDATE_PROPERTIES -> buf.writeByte(flags); + default -> throw new UnsupportedOperationException("Unknown action " + action); } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/LegacyPlayerListItemPacket.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/LegacyPlayerListItemPacket.java index 268c707d6f..41e19568b4 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/LegacyPlayerListItemPacket.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/LegacyPlayerListItemPacket.java @@ -69,33 +69,25 @@ public void decode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersi Item item = new Item(ProtocolUtils.readUuid(buf)); items.add(item); switch (action) { - case ADD_PLAYER: + case ADD_PLAYER -> { item.setName(ProtocolUtils.readString(buf)); item.setProperties(ProtocolUtils.readProperties(buf)); item.setGameMode(ProtocolUtils.readVarInt(buf)); item.setLatency(ProtocolUtils.readVarInt(buf)); item.setDisplayName(readOptionalComponent(buf, version)); - if (version.noLessThan(ProtocolVersion.MINECRAFT_1_19)) { if (buf.readBoolean()) { item.setPlayerKey(ProtocolUtils.readPlayerKey(version, buf)); } } - break; - case UPDATE_GAMEMODE: - item.setGameMode(ProtocolUtils.readVarInt(buf)); - break; - case UPDATE_LATENCY: - item.setLatency(ProtocolUtils.readVarInt(buf)); - break; - case UPDATE_DISPLAY_NAME: - item.setDisplayName(readOptionalComponent(buf, version)); - break; - case REMOVE_PLAYER: + } + case UPDATE_GAMEMODE -> item.setGameMode(ProtocolUtils.readVarInt(buf)); + case UPDATE_LATENCY -> item.setLatency(ProtocolUtils.readVarInt(buf)); + case UPDATE_DISPLAY_NAME -> item.setDisplayName(readOptionalComponent(buf, version)); + case REMOVE_PLAYER -> { //Do nothing, all that is needed is the uuid - break; - default: - throw new UnsupportedOperationException("Unknown action " + action); + } + default -> throw new UnsupportedOperationException("Unknown action " + action); } } } else { @@ -126,7 +118,7 @@ public void encode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersi ProtocolUtils.writeUuid(buf, uuid); switch (action) { - case ADD_PLAYER: + case ADD_PLAYER -> { ProtocolUtils.writeString(buf, item.getName()); ProtocolUtils.writeProperties(buf, item.getProperties()); ProtocolUtils.writeVarInt(buf, item.getGameMode()); @@ -140,25 +132,18 @@ public void encode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersi buf.writeBoolean(false); } } - break; - case UPDATE_GAMEMODE: - ProtocolUtils.writeVarInt(buf, item.getGameMode()); - break; - case UPDATE_LATENCY: - ProtocolUtils.writeVarInt(buf, item.getLatency()); - break; - case UPDATE_DISPLAY_NAME: - writeDisplayName(buf, item.getDisplayName(), version); - break; - case REMOVE_PLAYER: + } + case UPDATE_GAMEMODE -> ProtocolUtils.writeVarInt(buf, item.getGameMode()); + case UPDATE_LATENCY -> ProtocolUtils.writeVarInt(buf, item.getLatency()); + case UPDATE_DISPLAY_NAME -> writeDisplayName(buf, item.getDisplayName(), version); + case REMOVE_PLAYER -> { // Do nothing, all that is needed is the uuid - break; - default: - throw new UnsupportedOperationException("Unknown action " + action); + } + default -> throw new UnsupportedOperationException("Unknown action " + action); } } } else { - Item item = items.get(0); + Item item = items.getFirst(); Component displayNameComponent = item.getDisplayName(); if (displayNameComponent != null) { String displayName = LegacyComponentSerializer.legacySection() @@ -269,7 +254,7 @@ public Item setPlayerKey(IdentifiedKey playerKey) { return this; } - public IdentifiedKey getPlayerKey() { + public @Nullable IdentifiedKey getPlayerKey() { return playerKey; } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/StringArgumentPropertySerializer.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/StringArgumentPropertySerializer.java index 75f5ecc869..d4567095bc 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/StringArgumentPropertySerializer.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/brigadier/StringArgumentPropertySerializer.java @@ -37,32 +37,21 @@ private StringArgumentPropertySerializer() { @Override public StringArgumentType deserialize(ByteBuf buf, ProtocolVersion protocolVersion) { int type = ProtocolUtils.readVarInt(buf); - switch (type) { - case 0: - return StringArgumentType.word(); - case 1: - return StringArgumentType.string(); - case 2: - return StringArgumentType.greedyString(); - default: - throw new IllegalArgumentException("Invalid string argument type " + type); - } + return switch (type) { + case 0 -> StringArgumentType.word(); + case 1 -> StringArgumentType.string(); + case 2 -> StringArgumentType.greedyString(); + default -> throw new IllegalArgumentException("Invalid string argument type " + type); + }; } @Override public void serialize(StringArgumentType object, ByteBuf buf, ProtocolVersion protocolVersion) { switch (object.getType()) { - case SINGLE_WORD: - ProtocolUtils.writeVarInt(buf, 0); - break; - case QUOTABLE_PHRASE: - ProtocolUtils.writeVarInt(buf, 1); - break; - case GREEDY_PHRASE: - ProtocolUtils.writeVarInt(buf, 2); - break; - default: - throw new IllegalArgumentException("Invalid string argument type " + object.getType()); + case SINGLE_WORD -> ProtocolUtils.writeVarInt(buf, 0); + case QUOTABLE_PHRASE -> ProtocolUtils.writeVarInt(buf, 1); + case GREEDY_PHRASE -> ProtocolUtils.writeVarInt(buf, 2); + default -> throw new IllegalArgumentException("Invalid string argument type " + object.getType()); } } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/ComponentHolder.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/ComponentHolder.java index 22b49621b9..be396dfa22 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/ComponentHolder.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/ComponentHolder.java @@ -112,24 +112,19 @@ public BinaryTag getBinaryTag() { public static BinaryTag serialize(JsonElement json) { if (json instanceof JsonPrimitive jsonPrimitive) { - if (jsonPrimitive.isNumber()) { - Number number = json.getAsNumber(); - - if (number instanceof Byte) { - return ByteBinaryTag.byteBinaryTag((Byte) number); - } else if (number instanceof Short) { - return ShortBinaryTag.shortBinaryTag((Short) number); - } else if (number instanceof Integer) { - return IntBinaryTag.intBinaryTag((Integer) number); - } else if (number instanceof Long) { - return LongBinaryTag.longBinaryTag((Long) number); - } else if (number instanceof Float) { - return FloatBinaryTag.floatBinaryTag((Float) number); - } else if (number instanceof Double) { - return DoubleBinaryTag.doubleBinaryTag((Double) number); - } else if (number instanceof LazilyParsedNumber) { - return IntBinaryTag.intBinaryTag(number.intValue()); - } + if (jsonPrimitive.isNumber()) { + final Number number = json.getAsNumber(); + + return switch (number) { + case Byte b -> ByteBinaryTag.byteBinaryTag(b); + case Short s -> ShortBinaryTag.shortBinaryTag(s); + case Integer i -> IntBinaryTag.intBinaryTag(i); + case Long l -> LongBinaryTag.longBinaryTag(l); + case Float f -> FloatBinaryTag.floatBinaryTag(f); + case Double d -> DoubleBinaryTag.doubleBinaryTag(d); + case LazilyParsedNumber l -> IntBinaryTag.intBinaryTag(l.intValue()); + default -> throw new IllegalArgumentException("Unknown number type: " + number); + }; } else if (jsonPrimitive.isString()) { return StringBinaryTag.stringBinaryTag(jsonPrimitive.getAsString()); } else if (jsonPrimitive.isBoolean()) { @@ -137,16 +132,16 @@ public static BinaryTag serialize(JsonElement json) { } else { throw new IllegalArgumentException("Unknown JSON primitive: " + jsonPrimitive); } - } else if (json instanceof JsonObject) { + } else if (json instanceof JsonObject object) { CompoundBinaryTag.Builder compound = CompoundBinaryTag.builder(); - for (Map.Entry property : ((JsonObject) json).entrySet()) { + for (Map.Entry property : object.entrySet()) { compound.put(property.getKey(), serialize(property.getValue())); } return compound.build(); - } else if (json instanceof JsonArray) { - List jsonArray = ((JsonArray) json).asList(); + } else if (json instanceof JsonArray array) { + List jsonArray = array.asList(); if (jsonArray.isEmpty()) { return ListBinaryTag.empty(); @@ -206,20 +201,21 @@ public static BinaryTag serialize(JsonElement json) { } public static JsonElement deserialize(BinaryTag tag) { - switch (tag.type().id()) { - case 1://BinaryTagTypes.BYTE: - return new JsonPrimitive(((ByteBinaryTag) tag).value()); - case 2://BinaryTagTypes.SHORT: - return new JsonPrimitive(((ShortBinaryTag) tag).value()); - case 3://BinaryTagTypes.INT: - return new JsonPrimitive(((IntBinaryTag) tag).value()); - case 4://BinaryTagTypes.LONG: - return new JsonPrimitive(((LongBinaryTag) tag).value()); - case 5://BinaryTagTypes.FLOAT: - return new JsonPrimitive(((FloatBinaryTag) tag).value()); - case 6://BinaryTagTypes.DOUBLE: - return new JsonPrimitive(((DoubleBinaryTag) tag).value()); - case 7://BinaryTagTypes.BYTE_ARRAY: + return switch (tag.type().id()) { + //BinaryTagTypes.BYTE + case 1 -> new JsonPrimitive(((ByteBinaryTag) tag).value()); + //BinaryTagTypes.SHORT + case 2 -> new JsonPrimitive(((ShortBinaryTag) tag).value()); + //BinaryTagTypes.INT: + case 3 -> new JsonPrimitive(((IntBinaryTag) tag).value()); + //BinaryTagTypes.LONG: + case 4 -> new JsonPrimitive(((LongBinaryTag) tag).value()); + //BinaryTagTypes.FLOAT: + case 5 -> new JsonPrimitive(((FloatBinaryTag) tag).value()); + //BinaryTagTypes.DOUBLE: + case 6 -> new JsonPrimitive(((DoubleBinaryTag) tag).value()); + //BinaryTagTypes.BYTE_ARRAY: + case 7 -> { byte[] byteArray = ((ByteArrayBinaryTag) tag).value(); JsonArray jsonByteArray = new JsonArray(byteArray.length); @@ -227,10 +223,12 @@ public static JsonElement deserialize(BinaryTag tag) { jsonByteArray.add(new JsonPrimitive(b)); } - return jsonByteArray; - case 8://BinaryTagTypes.STRING: - return new JsonPrimitive(((StringBinaryTag) tag).value()); - case 9://BinaryTagTypes.LIST: + yield jsonByteArray; + } + //BinaryTagTypes.STRING: + case 8 -> new JsonPrimitive(((StringBinaryTag) tag).value()); + //BinaryTagTypes.LIST: + case 9 -> { ListBinaryTag items = (ListBinaryTag) tag; JsonArray jsonList = new JsonArray(items.size()); @@ -238,8 +236,10 @@ public static JsonElement deserialize(BinaryTag tag) { jsonList.add(deserialize(subTag)); } - return jsonList; - case 10://BinaryTagTypes.COMPOUND: + yield jsonList; + } + //BinaryTagTypes.COMPOUND: + case 10 -> { CompoundBinaryTag compound = (CompoundBinaryTag) tag; JsonObject jsonObject = new JsonObject(); @@ -252,8 +252,10 @@ public static JsonElement deserialize(BinaryTag tag) { jsonObject.add(key.isEmpty() ? "text" : key, deserialize(compound.get(key))); }); - return jsonObject; - case 11://BinaryTagTypes.INT_ARRAY: + yield jsonObject; + } + //BinaryTagTypes.INT_ARRAY: + case 11 -> { int[] intArray = ((IntArrayBinaryTag) tag).value(); JsonArray jsonIntArray = new JsonArray(intArray.length); @@ -261,8 +263,10 @@ public static JsonElement deserialize(BinaryTag tag) { jsonIntArray.add(new JsonPrimitive(i)); } - return jsonIntArray; - case 12://BinaryTagTypes.LONG_ARRAY: + yield jsonIntArray; + } + //BinaryTagTypes.LONG_ARRAY: + case 12 -> { long[] longArray = ((LongArrayBinaryTag) tag).value(); JsonArray jsonLongArray = new JsonArray(longArray.length); @@ -270,10 +274,10 @@ public static JsonElement deserialize(BinaryTag tag) { jsonLongArray.add(new JsonPrimitive(l)); } - return jsonLongArray; - default: - throw new IllegalArgumentException("Unknown NBT tag: " + tag); - } + yield jsonLongArray; + } + default -> throw new IllegalArgumentException("Unknown NBT tag: " + tag); + }; } public static ComponentHolder read(ByteBuf buf, ProtocolVersion version) { diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/SystemChatPacket.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/SystemChatPacket.java index b36014d5b4..1a26affda4 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/SystemChatPacket.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/chat/SystemChatPacket.java @@ -59,14 +59,9 @@ public void encode(ByteBuf buf, ProtocolUtils.Direction direction, ProtocolVersi component.write(buf); if (version.noLessThan(ProtocolVersion.MINECRAFT_1_19_1)) { switch (type) { - case SYSTEM: - buf.writeBoolean(false); - break; - case GAME_INFO: - buf.writeBoolean(true); - break; - default: - throw new IllegalArgumentException("Invalid chat type"); + case SYSTEM -> buf.writeBoolean(false); + case GAME_INFO -> buf.writeBoolean(true); + default -> throw new IllegalArgumentException("Invalid chat type"); } } else { ProtocolUtils.writeVarInt(buf, type.getId()); diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/title/GenericTitlePacket.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/title/GenericTitlePacket.java index d6f5e0e540..8641173e74 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/title/GenericTitlePacket.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/title/GenericTitlePacket.java @@ -105,26 +105,14 @@ public final void decode(ByteBuf buf, ProtocolUtils.Direction direction, public static GenericTitlePacket constructTitlePacket(ActionType type, ProtocolVersion version) { GenericTitlePacket packet = null; if (version.noLessThan(ProtocolVersion.MINECRAFT_1_17)) { - switch (type) { - case SET_ACTION_BAR: - packet = new TitleActionbarPacket(); - break; - case SET_SUBTITLE: - packet = new TitleSubtitlePacket(); - break; - case SET_TIMES: - packet = new TitleTimesPacket(); - break; - case SET_TITLE: - packet = new TitleTextPacket(); - break; - case HIDE: - case RESET: - packet = new TitleClearPacket(); - break; - default: - throw new IllegalArgumentException("Invalid ActionType"); - } + packet = switch (type) { + case SET_ACTION_BAR -> new TitleActionbarPacket(); + case SET_SUBTITLE -> new TitleSubtitlePacket(); + case SET_TIMES -> new TitleTimesPacket(); + case SET_TITLE -> new TitleTextPacket(); + case HIDE, RESET -> new TitleClearPacket(); + default -> throw new IllegalArgumentException("Invalid ActionType"); + }; } else { packet = new LegacyTitlePacket(); } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/title/LegacyTitlePacket.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/title/LegacyTitlePacket.java index 0425f2d3c2..ebae8a9e5b 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/title/LegacyTitlePacket.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/packet/title/LegacyTitlePacket.java @@ -40,24 +40,19 @@ && getAction() == ActionType.SET_ACTION_BAR) { ProtocolUtils.writeVarInt(buf, getAction().getAction(version)); switch (getAction()) { - case SET_TITLE: - case SET_SUBTITLE: - case SET_ACTION_BAR: + case SET_TITLE, SET_SUBTITLE, SET_ACTION_BAR -> { if (component == null) { throw new IllegalStateException("No component found for " + getAction()); } component.write(buf); - break; - case SET_TIMES: + } + case SET_TIMES -> { buf.writeInt(fadeIn); buf.writeInt(stay); buf.writeInt(fadeOut); - break; - case HIDE: - case RESET: - break; - default: - throw new UnsupportedOperationException("Unknown action " + getAction()); + } + case HIDE, RESET -> {} + default -> throw new UnsupportedOperationException("Unknown action " + getAction()); } } 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 1936eb3ff1..298e74d4f2 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 @@ -230,23 +230,20 @@ public static String transformLegacyToModernChannel(String name) { } // Before falling into the fallback, explicitly rewrite certain messages. - switch (name) { - case REGISTER_CHANNEL_LEGACY: - return REGISTER_CHANNEL; - case UNREGISTER_CHANNEL_LEGACY: - return UNREGISTER_CHANNEL; - case BRAND_CHANNEL_LEGACY: - return BRAND_CHANNEL; - case "BungeeCord": - // This is a special historical case we are compelled to support for the benefit of - // BungeeQuack. - return "bungeecord:main"; - default: + return switch (name) { + case REGISTER_CHANNEL_LEGACY -> REGISTER_CHANNEL; + case UNREGISTER_CHANNEL_LEGACY -> UNREGISTER_CHANNEL; + case BRAND_CHANNEL_LEGACY -> BRAND_CHANNEL; + // This is a special historical case we are compelled to support for the benefit of + // BungeeQuack. + case "BungeeCord" -> "bungeecord:main"; + default -> { // This is very likely a legacy name, so transform it. Velocity uses the same scheme as // BungeeCord does to transform channels, but also removes clearly invalid characters as // well. - String lower = name.toLowerCase(Locale.ROOT); - return "legacy:" + INVALID_IDENTIFIER_REGEX.matcher(lower).replaceAll(""); - } + final String lower = name.toLowerCase(Locale.ROOT); + yield "legacy:" + INVALID_IDENTIFIER_REGEX.matcher(lower).replaceAll(""); + } + }; } } diff --git a/proxy/src/main/java/com/velocitypowered/proxy/tablist/VelocityTabListLegacy.java b/proxy/src/main/java/com/velocitypowered/proxy/tablist/VelocityTabListLegacy.java index a49d24de49..037ab26286 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/tablist/VelocityTabListLegacy.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/tablist/VelocityTabListLegacy.java @@ -85,7 +85,7 @@ public void clearAllSilent() { @Override public void processLegacy(LegacyPlayerListItemPacket packet) { - Item item = packet.getItems().get(0); // Only one item per packet in 1.7 + Item item = packet.getItems().getFirst(); // Only one item per packet in 1.7 switch (packet.getAction()) { case LegacyPlayerListItemPacket.ADD_PLAYER: diff --git a/proxy/src/main/java/com/velocitypowered/proxy/util/InformationUtils.java b/proxy/src/main/java/com/velocitypowered/proxy/util/InformationUtils.java index d8cdb7c3d1..59aae3e43e 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/util/InformationUtils.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/util/InformationUtils.java @@ -145,45 +145,44 @@ public static JsonObject collectForcedHosts(ProxyConfig config) { * @return {@link String} address with public parts redacted */ public static String anonymizeInetAddress(InetAddress address) { - if (address instanceof Inet4Address) { - Inet4Address v4 = (Inet4Address) address; - if (v4.isAnyLocalAddress() || v4.isLoopbackAddress() - || v4.isLinkLocalAddress() - || v4.isSiteLocalAddress()) { - return address.getHostAddress(); - } else { - byte[] addr = v4.getAddress(); - return (addr[0] & 0xff) + "." + (addr[1] & 0xff) + ".XXX.XXX"; - } - } else if (address instanceof Inet6Address) { - Inet6Address v6 = (Inet6Address) address; - if (v6.isAnyLocalAddress() || v6.isLoopbackAddress() - || v6.isSiteLocalAddress() - || v6.isSiteLocalAddress()) { - return address.getHostAddress(); - } else { - String[] bits = v6.getHostAddress().split(":"); - String ret = ""; - boolean flag = false; - for (int iter = 0; iter < bits.length; iter++) { - if (flag) { - ret += ":X"; - continue; - } - if (!bits[iter].equals("0")) { - if (iter == 0) { - ret = bits[iter]; - } else { - ret = "::" + bits[iter]; + return switch (address) { + case Inet4Address v4 -> { + if (v4.isAnyLocalAddress() || v4.isLoopbackAddress() + || v4.isLinkLocalAddress() + || v4.isSiteLocalAddress()) { + yield address.getHostAddress(); + } else { + byte[] addr = v4.getAddress(); + yield (addr[0] & 0xff) + "." + (addr[1] & 0xff) + ".XXX.XXX"; + } + } case Inet6Address v6 -> { + if (v6.isAnyLocalAddress() || v6.isLoopbackAddress() + || v6.isSiteLocalAddress() + || v6.isSiteLocalAddress()) { + yield address.getHostAddress(); + } else { + String[] bits = v6.getHostAddress().split(":"); + String ret = ""; + boolean flag = false; + for (int iter = 0; iter < bits.length; iter++) { + if (flag) { + ret += ":X"; + continue; + } + if (!bits[iter].equals("0")) { + if (iter == 0) { + ret = bits[iter]; + } else { + ret = "::" + bits[iter]; + } + flag = true; } - flag = true; } + yield ret; } - return ret; } - } else { - return address.getHostAddress(); - } + default -> address.getHostAddress(); + }; } /** diff --git a/proxy/log4j2-plugin/src/main/java/com/velocitypowered/proxy/util/StripAnsiConverter.java b/proxy/src/main/java/com/velocitypowered/proxy/util/StripAnsiConverter.java similarity index 100% rename from proxy/log4j2-plugin/src/main/java/com/velocitypowered/proxy/util/StripAnsiConverter.java rename to proxy/src/main/java/com/velocitypowered/proxy/util/StripAnsiConverter.java diff --git a/proxy/src/test/java/com/velocitypowered/proxy/command/brigadier/VelocityArgumentCommandNodeTests.java b/proxy/src/test/java/com/velocitypowered/proxy/command/brigadier/VelocityArgumentCommandNodeTests.java index fb5f57e391..90420da02f 100644 --- a/proxy/src/test/java/com/velocitypowered/proxy/command/brigadier/VelocityArgumentCommandNodeTests.java +++ b/proxy/src/test/java/com/velocitypowered/proxy/command/brigadier/VelocityArgumentCommandNodeTests.java @@ -64,8 +64,8 @@ void testParse() throws CommandSyntaxException { assertFalse(reader.canRead()); assertFalse(this.contextBuilder.getNodes().isEmpty()); - assertSame(node, this.contextBuilder.getNodes().get(0).getNode()); - assertEquals(expectedRange, this.contextBuilder.getNodes().get(0).getRange()); + assertSame(node, this.contextBuilder.getNodes().getFirst().getNode()); + assertEquals(expectedRange, this.contextBuilder.getNodes().getFirst().getRange()); assertTrue(this.contextBuilder.getArguments().containsKey("foo")); final ParsedArgument parsed = diff --git a/proxy/src/test/java/com/velocitypowered/proxy/testutil/FakePluginManager.java b/proxy/src/test/java/com/velocitypowered/proxy/testutil/FakePluginManager.java index 7992ac52e6..4d1f66cc5d 100644 --- a/proxy/src/test/java/com/velocitypowered/proxy/testutil/FakePluginManager.java +++ b/proxy/src/test/java/com/velocitypowered/proxy/testutil/FakePluginManager.java @@ -62,16 +62,12 @@ public class FakePluginManager implements PluginManager { @Override public @NonNull Optional getPlugin(@NonNull String id) { - switch (id) { - case "a": - return Optional.of(containerA); - case "b": - return Optional.of(containerB); - case "velocity": - return Optional.of(containerVelocity); - default: - return Optional.empty(); - } + return switch (id) { + case "a" -> Optional.of(containerA); + case "b" -> Optional.of(containerB); + case "velocity" -> Optional.of(containerVelocity); + default -> Optional.empty(); + }; } @Override diff --git a/settings.gradle.kts b/settings.gradle.kts index 403844654a..3159fc73b8 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -17,7 +17,7 @@ pluginManagement { } plugins { - id("org.gradle.toolchains.foojay-resolver-convention") version "0.9.0" + id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" } rootProject.name = "velocity" @@ -36,8 +36,3 @@ sequenceOf( val deprecatedConfigurateModule = ":deprecated-configurate3" include(deprecatedConfigurateModule) project(deprecatedConfigurateModule).projectDir = file("proxy/deprecated/configurate3") - -// Log4J2 plugin -val log4j2ProxyPlugin = ":velocity-proxy-log4j2-plugin" -include(log4j2ProxyPlugin) -project(log4j2ProxyPlugin).projectDir = file("proxy/log4j2-plugin")